From ab25e047c0a56e93dc9a6114844f8337c51ba320 Mon Sep 17 00:00:00 2001 From: Scrutinizer Auto-Fixer Date: Sat, 31 Oct 2020 17:51:30 +0000 Subject: [PATCH] Scrutinizer Auto-Fixes This commit consists of patches automatically generated for this project on https://scrutinizer-ci.com --- .../bookkeeping/listbysubaccount.php | 46 +- .../accountancy/class/bookkeeping.class.php | 12 +- htdocs/adherents/class/api_members.class.php | 832 ++--- .../class/api_memberstypes.class.php | 512 +-- htdocs/admin/fckeditor.php | 120 +- htdocs/admin/modulehelp.php | 2 +- htdocs/admin/system/modules.php | 8 +- htdocs/admin/workflow.php | 2 +- htdocs/api/class/api_access.class.php | 2 +- htdocs/api/index.php | 2 +- htdocs/bom/class/api_boms.class.php | 518 +-- htdocs/bom/tpl/linkedobjectblock.tpl.php | 6 +- htdocs/comm/action/card.php | 82 +- .../action/class/api_agendaevents.class.php | 626 ++-- .../comm/action/class/cactioncomm.class.php | 346 +- htdocs/comm/action/index.php | 2 +- htdocs/comm/card.php | 40 +- htdocs/comm/mailing/card.php | 6 +- .../comm/propal/class/api_proposals.class.php | 4 +- htdocs/commande/class/api_orders.class.php | 4 +- htdocs/compta/accounting-files.php | 10 +- .../bank/class/api_bankaccounts.class.php | 788 ++-- .../facture/class/api_invoices.class.php | 2086 +++++------ htdocs/compta/prelevement/list.php | 4 +- htdocs/compta/stats/cabyprodserv.php | 8 +- htdocs/compta/tva/clients.php | 4 +- htdocs/contact/class/contact.class.php | 12 +- htdocs/contrat/card.php | 26 +- htdocs/contrat/class/api_contracts.class.php | 1120 +++--- htdocs/core/actions_linkedfiles.inc.php | 344 +- .../box_accountancy_last_manual_entries.php | 2 +- htdocs/core/boxes/box_actions.php | 158 +- htdocs/core/boxes/box_task.php | 114 +- htdocs/core/boxes/box_validated_projects.php | 36 +- htdocs/core/boxes/modules_boxes.php | 2 +- .../core/class/commondocgenerator.class.php | 2 +- htdocs/core/class/cproductnature.class.php | 8 +- htdocs/core/class/cstate.class.php | 4 +- htdocs/core/class/doleditor.class.php | 2 +- htdocs/core/class/dolgraph.class.php | 4 +- htdocs/core/class/dolreceiptprinter.class.php | 2 +- htdocs/core/class/html.form.class.php | 28 +- htdocs/core/class/html.formmargin.class.php | 2 +- htdocs/core/class/menu.class.php | 2 +- htdocs/core/class/smtps.class.php | 14 +- htdocs/core/customreports.php | 2 +- htdocs/core/lib/admin.lib.php | 480 +-- htdocs/core/lib/contact.lib.php | 2 +- htdocs/core/lib/fourn.lib.php | 36 +- htdocs/core/lib/functions.lib.php | 2 +- htdocs/core/menus/standard/eldy.lib.php | 2 +- .../delivery/doc/pdf_storm.modules.php | 4 +- .../core/modules/modIntracommreport.class.php | 10 +- htdocs/core/photos_resize.php | 2 +- htdocs/dav/fileserver.php | 2 +- htdocs/debugbar/class/autoloader.php | 2 +- htdocs/don/class/api_donations.class.php | 96 +- .../expedition/class/api_shipments.class.php | 102 +- .../class/api_expensereports.class.php | 400 +- .../class/api_interventions.class.php | 376 +- .../class/api_supplier_invoices.class.php | 4 +- .../fourn/class/api_supplier_orders.class.php | 4 +- .../fourn/class/fournisseur.product.class.php | 8 +- htdocs/fourn/facture/card.php | 82 +- htdocs/holiday/class/holiday.class.php | 4 +- htdocs/install/upgrade.php | 486 +-- .../intracommreport/admin/intracommreport.php | 20 +- htdocs/intracommreport/card.php | 28 +- .../class/intracommreport.class.php | 8 +- htdocs/intracommreport/list.php | 146 +- htdocs/loan/class/loanschedule.class.php | 44 +- htdocs/loan/payment/payment.php | 22 +- htdocs/loan/schedule.php | 2 +- htdocs/margin/agentMargins.php | 2 +- htdocs/margin/tabs/thirdpartyMargins.php | 304 +- .../template/class/api_mymodule.class.php | 4 +- htdocs/mrp/class/api_mos.class.php | 4 +- htdocs/mrp/class/mo.class.php | 2 +- htdocs/mrp/index.php | 2 +- htdocs/multicurrency/multicurrency_rate.php | 260 +- htdocs/product/admin/price_rules.php | 2 +- htdocs/product/class/api_products.class.php | 3328 ++++++++--------- htdocs/product/fournisseurs.php | 16 +- htdocs/product/reassort.php | 12 +- .../stock/class/api_stockmovements.class.php | 142 +- .../stock/class/api_warehouses.class.php | 448 +-- htdocs/product/stock/productlot_card.php | 22 +- htdocs/projet/class/api_projects.class.php | 808 ++-- htdocs/projet/class/api_tasks.class.php | 4 +- htdocs/societe/card.php | 548 +-- htdocs/societe/class/api_contacts.class.php | 222 +- htdocs/societe/class/societe.class.php | 4 +- .../class/api_supplier_proposals.class.php | 316 +- htdocs/takepos/ajax/ajax.php | 14 +- htdocs/ticket/class/api_tickets.class.php | 976 ++--- htdocs/ticket/class/utils_diff.class.php | 2 +- htdocs/user/passwordforgotten.php | 6 +- htdocs/webservices/server_invoice.php | 2 +- htdocs/website/class/website.class.php | 30 +- scripts/cron/cron_run_jobs.php | 52 +- 100 files changed, 8931 insertions(+), 8931 deletions(-) diff --git a/htdocs/accountancy/bookkeeping/listbysubaccount.php b/htdocs/accountancy/bookkeeping/listbysubaccount.php index 6810d455085..c286780e572 100644 --- a/htdocs/accountancy/bookkeeping/listbysubaccount.php +++ b/htdocs/accountancy/bookkeeping/listbysubaccount.php @@ -138,7 +138,7 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php'; + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; 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 { @@ -172,55 +172,55 @@ if (empty($reshook)) if (!empty($search_date_start)) { $filter['t.doc_date>='] = $search_date_start; - $param .= '&search_date_startmonth=' . GETPOST('search_date_startmonth', 'int') . '&search_date_startday=' . GETPOST('search_date_startday', 'int') . '&search_date_startyear=' . GETPOST('search_date_startyear', 'int'); + $param .= '&search_date_startmonth='.GETPOST('search_date_startmonth', 'int').'&search_date_startday='.GETPOST('search_date_startday', 'int').'&search_date_startyear='.GETPOST('search_date_startyear', 'int'); } if (!empty($search_date_end)) { $filter['t.doc_date<='] = $search_date_end; - $param .= '&search_date_endmonth=' . GETPOST('search_date_endmonth', 'int') . '&search_date_endday=' . GETPOST('search_date_endday', 'int') . '&search_date_endyear=' . GETPOST('search_date_endyear', 'int'); + $param .= '&search_date_endmonth='.GETPOST('search_date_endmonth', 'int').'&search_date_endday='.GETPOST('search_date_endday', 'int').'&search_date_endyear='.GETPOST('search_date_endyear', 'int'); } if (!empty($search_doc_date)) { $filter['t.doc_date'] = $search_doc_date; - $param .= '&doc_datemonth=' . GETPOST('doc_datemonth', 'int') . '&doc_dateday=' . GETPOST('doc_dateday', 'int') . '&doc_dateyear=' . GETPOST('doc_dateyear', 'int'); + $param .= '&doc_datemonth='.GETPOST('doc_datemonth', 'int').'&doc_dateday='.GETPOST('doc_dateday', 'int').'&doc_dateyear='.GETPOST('doc_dateyear', 'int'); } if (!empty($search_accountancy_code_start)) { $filter['t.subledger_account>='] = $search_accountancy_code_start; - $param .= '&search_accountancy_code_start=' . urlencode($search_accountancy_code_start); + $param .= '&search_accountancy_code_start='.urlencode($search_accountancy_code_start); } if (!empty($search_accountancy_code_end)) { $filter['t.subledger_account<='] = $search_accountancy_code_end; - $param .= '&search_accountancy_code_end=' . urlencode($search_accountancy_code_end); + $param .= '&search_accountancy_code_end='.urlencode($search_accountancy_code_end); } if (!empty($search_label_account)) { $filter['t.label_compte'] = $search_label_account; - $param .= '&search_label_compte=' . urlencode($search_label_account); + $param .= '&search_label_compte='.urlencode($search_label_account); } if (!empty($search_mvt_num)) { $filter['t.piece_num'] = $search_mvt_num; - $param .= '&search_mvt_num=' . urlencode($search_mvt_num); + $param .= '&search_mvt_num='.urlencode($search_mvt_num); } if (!empty($search_doc_ref)) { $filter['t.doc_ref'] = $search_doc_ref; - $param .= '&search_doc_ref=' . urlencode($search_doc_ref); + $param .= '&search_doc_ref='.urlencode($search_doc_ref); } if (!empty($search_label_operation)) { $filter['t.label_operation'] = $search_label_operation; - $param .= '&search_label_operation=' . urlencode($search_label_operation); + $param .= '&search_label_operation='.urlencode($search_label_operation); } if (!empty($search_direction)) { $filter['t.sens'] = $search_direction; - $param .= '&search_direction=' . urlencode($search_direction); + $param .= '&search_direction='.urlencode($search_direction); } if (!empty($search_ledger_code)) { $filter['t.code_journal'] = $search_ledger_code; - $param .= '&search_ledger_code=' . urlencode($search_ledger_code); + $param .= '&search_ledger_code='.urlencode($search_ledger_code); } if (!empty($search_debit)) { $filter['t.debit'] = $search_debit; - $param .= '&search_debit=' . urlencode($search_debit); + $param .= '&search_debit='.urlencode($search_debit); } if (!empty($search_credit)) { $filter['t.credit'] = $search_credit; - $param .= '&search_credit=' . urlencode($search_credit); + $param .= '&search_credit='.urlencode($search_credit); } if (!empty($search_lettering_code)) { $filter['t.lettering_code'] = $search_lettering_code; @@ -423,7 +423,7 @@ print ''; // Code journal if (!empty($arrayfields['t.code_journal']['checked'])) { - print ''; + print ''; } // Date document if (!empty($arrayfields['t.doc_date']['checked'])) { @@ -443,19 +443,19 @@ if (!empty($arrayfields['t.piece_num']['checked'])) } // Ref document if (!empty($arrayfields['t.doc_ref']['checked'])) { - print ''; + print ''; } // Label operation if (!empty($arrayfields['t.label_operation']['checked'])) { - print ''; + print ''; } // Debit if (!empty($arrayfields['t.debit']['checked'])) { - print ''; + print ''; } // Credit if (!empty($arrayfields['t.credit']['checked'])) { - print ''; + print ''; } // Lettering code if (!empty($arrayfields['t.lettering_code']['checked'])) @@ -531,7 +531,7 @@ while ($i < min($num, $limit)) $balance = $sous_total_debit - $sous_total_credit; print ''; print ''.$langs->trans("Balance").':'; - if ($balance > 0 ) + if ($balance > 0) { print ''; print price($sous_total_debit - $sous_total_credit); @@ -662,7 +662,7 @@ while ($i < min($num, $limit)) if (!empty($arrayfields['t.label_operation']['checked'])) { // Affiche un lien vers la facture client/fournisseur $doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref); - print strlen(length_accounta($line->subledger_account)) == 0 ? '' . $line->label_operation . '' : '' . $line->label_operation . '
(' . length_accounta($line->subledger_account) . ')'; + print strlen(length_accounta($line->subledger_account)) == 0 ? ''.$line->label_operation.'' : ''.$line->label_operation.'
('.length_accounta($line->subledger_account).')'; if (!$i) $totalarray['nbfield']++; } @@ -677,7 +677,7 @@ while ($i < min($num, $limit)) // Amount credit if (!empty($arrayfields['t.credit']['checked'])) { - print '' . ($line->credit ? price($line->credit) : '') . ''; + print ''.($line->credit ? price($line->credit) : '').''; if (!$i) $totalarray['nbfield']++; if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalcredit'; $totalarray['val']['totalcredit'] += $line->credit; @@ -730,7 +730,7 @@ print ''; $balance = $sous_total_debit - $sous_total_credit; print ''; print ''.$langs->trans("Balance").':'; -if ($balance > 0 ) +if ($balance > 0) { print ''; print price($sous_total_debit - $sous_total_credit); diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 0313798eb09..505c51d27fe 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -837,12 +837,12 @@ class BookKeeping extends CommonObject $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); } // Affichage par compte comptable - if (!empty($option)) { - $sql .= ' AND t.subledger_account IS NOT NULL'; - $sql .= ' ORDER BY t.subledger_account ASC'; - } else { - $sql .= ' ORDER BY t.numero_compte ASC'; - } + if (!empty($option)) { + $sql .= ' AND t.subledger_account IS NOT NULL'; + $sql .= ' ORDER BY t.subledger_account ASC'; + } else { + $sql .= ' ORDER BY t.numero_compte ASC'; + } if (!empty($sortfield)) { $sql .= ', '.$sortfield.' '.$sortorder; diff --git a/htdocs/adherents/class/api_members.class.php b/htdocs/adherents/class/api_members.class.php index bf57d723589..321d789e03a 100644 --- a/htdocs/adherents/class/api_members.class.php +++ b/htdocs/adherents/class/api_members.class.php @@ -32,477 +32,477 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; */ class Members extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'morphy', - 'typeid' - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'morphy', + 'typeid' + ); - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - } + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + } - /** - * Get properties of a member object - * - * Return an array with member informations - * - * @param int $id ID of member - * @return array|mixed data without useless information - * - * @throws RestException - */ - public function get($id) - { - if (!DolibarrApiAccess::$user->rights->adherent->lire) { - throw new RestException(401); - } + /** + * Get properties of a member object + * + * Return an array with member informations + * + * @param int $id ID of member + * @return array|mixed data without useless information + * + * @throws RestException + */ + public function get($id) + { + if (!DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } - $member = new Adherent($this->db); - $result = $member->fetch($id); - if (!$result) { - throw new RestException(404, 'member not found'); - } + $member = new Adherent($this->db); + $result = $member->fetch($id); + if (!$result) { + throw new RestException(404, 'member not found'); + } - if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - return $this->_cleanObjectDatas($member); - } + return $this->_cleanObjectDatas($member); + } - /** - * Get properties of a member object by linked thirdparty - * - * Return an array with member informations - * - * @param int $thirdparty ID of third party - * - * @return array|mixed Data without useless information - * - * @url GET thirdparty/{thirdparty} - * - * @throws RestException 401 - * @throws RestException 404 - */ - public function getByThirdparty($thirdparty) - { - if (!DolibarrApiAccess::$user->rights->adherent->lire) { - throw new RestException(401); - } + /** + * Get properties of a member object by linked thirdparty + * + * Return an array with member informations + * + * @param int $thirdparty ID of third party + * + * @return array|mixed Data without useless information + * + * @url GET thirdparty/{thirdparty} + * + * @throws RestException 401 + * @throws RestException 404 + */ + public function getByThirdparty($thirdparty) + { + if (!DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } - $member = new Adherent($this->db); - $result = $member->fetch('', '', $thirdparty); - if (!$result) { - throw new RestException(404, 'member not found'); - } + $member = new Adherent($this->db); + $result = $member->fetch('', '', $thirdparty); + if (!$result) { + throw new RestException(404, 'member not found'); + } - if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - return $this->_cleanObjectDatas($member); - } + return $this->_cleanObjectDatas($member); + } - /** - * Get properties of a member object by linked thirdparty email - * - * Return an array with member informations - * - * @param string $email Email of third party - * - * @return array|mixed Data without useless information - * - * @url GET thirdparty/email/{email} - * - * @throws RestException 401 - * @throws RestException 404 - */ - public function getByThirdpartyEmail($email) - { - if (!DolibarrApiAccess::$user->rights->adherent->lire) { - throw new RestException(401); - } + /** + * Get properties of a member object by linked thirdparty email + * + * Return an array with member informations + * + * @param string $email Email of third party + * + * @return array|mixed Data without useless information + * + * @url GET thirdparty/email/{email} + * + * @throws RestException 401 + * @throws RestException 404 + */ + public function getByThirdpartyEmail($email) + { + if (!DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } - $thirdparty = new Societe($this->db); - $result = $thirdparty->fetch('', '', '', '', '', '', '', '', '', '', $email); - if (!$result) { - throw new RestException(404, 'thirdparty not found'); - } + $thirdparty = new Societe($this->db); + $result = $thirdparty->fetch('', '', '', '', '', '', '', '', '', '', $email); + if (!$result) { + throw new RestException(404, 'thirdparty not found'); + } - $member = new Adherent($this->db); - $result = $member->fetch('', '', $thirdparty->id); - if (!$result) { - throw new RestException(404, 'member not found'); - } + $member = new Adherent($this->db); + $result = $member->fetch('', '', $thirdparty->id); + if (!$result) { + throw new RestException(404, 'member not found'); + } - if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - return $this->_cleanObjectDatas($member); - } + return $this->_cleanObjectDatas($member); + } - /** - * Get properties of a member object by linked thirdparty barcode - * - * Return an array with member informations - * - * @param string $barcode Barcode of third party - * - * @return array|mixed Data without useless information - * - * @url GET thirdparty/barcode/{barcode} - * - * @throws RestException 401 - * @throws RestException 404 - */ - public function getByThirdpartyBarcode($barcode) - { - if (!DolibarrApiAccess::$user->rights->adherent->lire) { - throw new RestException(401); - } + /** + * Get properties of a member object by linked thirdparty barcode + * + * Return an array with member informations + * + * @param string $barcode Barcode of third party + * + * @return array|mixed Data without useless information + * + * @url GET thirdparty/barcode/{barcode} + * + * @throws RestException 401 + * @throws RestException 404 + */ + public function getByThirdpartyBarcode($barcode) + { + if (!DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } - $thirdparty = new Societe($this->db); - $result = $thirdparty->fetch('', '', '', $barcode); - if (!$result) { - throw new RestException(404, 'thirdparty not found'); - } + $thirdparty = new Societe($this->db); + $result = $thirdparty->fetch('', '', '', $barcode); + if (!$result) { + throw new RestException(404, 'thirdparty not found'); + } - $member = new Adherent($this->db); - $result = $member->fetch('', '', $thirdparty->id); - if (!$result) { - throw new RestException(404, 'member not found'); - } + $member = new Adherent($this->db); + $result = $member->fetch('', '', $thirdparty->id); + if (!$result) { + throw new RestException(404, 'member not found'); + } - if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - return $this->_cleanObjectDatas($member); - } + return $this->_cleanObjectDatas($member); + } - /** - * List members - * - * Get a list of members - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $typeid ID of the type of member + /** + * List members + * + * Get a list of members + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $typeid ID of the type of member * @param int $category Use this param to filter list by category - * @param string $sqlfilters Other criteria to filter answers separated by a comma. - * Example: "(t.ref:like:'SO-%') and ((t.date_creation:<:'20160101') or (t.nature:is:NULL))" - * @return array Array of member objects - * - * @throws RestException - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $typeid = '', $category = 0, $sqlfilters = '') - { - global $db, $conf; + * @param string $sqlfilters Other criteria to filter answers separated by a comma. + * Example: "(t.ref:like:'SO-%') and ((t.date_creation:<:'20160101') or (t.nature:is:NULL))" + * @return array Array of member objects + * + * @throws RestException + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $typeid = '', $category = 0, $sqlfilters = '') + { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - if (!DolibarrApiAccess::$user->rights->adherent->lire) { - throw new RestException(401); - } + if (!DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } - $sql = "SELECT t.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."adherent as t"; - if ($category > 0) { + $sql = "SELECT t.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."adherent as t"; + if ($category > 0) { $sql .= ", ".MAIN_DB_PREFIX."categorie_member as c"; - } - $sql .= ' WHERE t.entity IN ('.getEntity('adherent').')'; - if (!empty($typeid)) { - $sql .= ' AND t.fk_adherent_type='.$typeid; - } - // Select members of given category - if ($category > 0) { + } + $sql .= ' WHERE t.entity IN ('.getEntity('adherent').')'; + if (!empty($typeid)) { + $sql .= ' AND t.fk_adherent_type='.$typeid; + } + // Select members of given category + if ($category > 0) { $sql .= " AND c.fk_categorie = ".$this->db->escape($category); $sql .= " AND c.fk_member = t.rowid "; - } - // Add sql filters - if ($sqlfilters) { - if (!DolibarrApi::_checkFilters($sqlfilters)) { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + } + // Add sql filters + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; - $sql .= $this->db->plimit($limit + 1, $offset); - } + $sql .= $this->db->plimit($limit + 1, $offset); + } - $result = $this->db->query($sql); - if ($result) { - $i = 0; - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) { - $obj = $this->db->fetch_object($result); - $member = new Adherent($this->db); - if ($member->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($member); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve member list : '.$this->db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No member found'); - } + $result = $this->db->query($sql); + if ($result) { + $i = 0; + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { + $obj = $this->db->fetch_object($result); + $member = new Adherent($this->db); + if ($member->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($member); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve member list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No member found'); + } - return $obj_ret; - } + return $obj_ret; + } - /** - * Create member object - * - * @param array $request_data Request data - * @return int ID of member - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->adherent->creer) { - throw new RestException(401); - } - // Check mandatory fields - $result = $this->_validate($request_data); + /** + * Create member object + * + * @param array $request_data Request data + * @return int ID of member + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validate($request_data); - $member = new Adherent($this->db); - foreach ($request_data as $field => $value) { - $member->$field = $value; - } - if ($member->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, 'Error creating member', array_merge(array($member->error), $member->errors)); - } - return $member->id; - } + $member = new Adherent($this->db); + foreach ($request_data as $field => $value) { + $member->$field = $value; + } + if ($member->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, 'Error creating member', array_merge(array($member->error), $member->errors)); + } + return $member->id; + } - /** - * Update member - * - * @param int $id ID of member to update - * @param array $request_data Datas - * @return int - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->adherent->creer) { - throw new RestException(401); - } + /** + * Update member + * + * @param int $id ID of member to update + * @param array $request_data Datas + * @return int + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->adherent->creer) { + throw new RestException(401); + } - $member = new Adherent($this->db); - $result = $member->fetch($id); - if (!$result) { - throw new RestException(404, 'member not found'); - } + $member = new Adherent($this->db); + $result = $member->fetch($id); + if (!$result) { + throw new RestException(404, 'member not found'); + } - if (!DolibarrApi::_checkAccessToResource('member', $member->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('member', $member->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - foreach ($request_data as $field => $value) { - if ($field == 'id') continue; - // Process the status separately because it must be updated using - // the validate() and resiliate() methods of the class Adherent. - if ($field == 'statut') { - if ($value == '0') { - $result = $member->resiliate(DolibarrApiAccess::$user); - if ($result < 0) { - throw new RestException(500, 'Error when resiliating member: '.$member->error); - } - } elseif ($value == '1') { - $result = $member->validate(DolibarrApiAccess::$user); - if ($result < 0) { - throw new RestException(500, 'Error when validating member: '.$member->error); - } - } - } else { - $member->$field = $value; - } - } + foreach ($request_data as $field => $value) { + if ($field == 'id') continue; + // Process the status separately because it must be updated using + // the validate() and resiliate() methods of the class Adherent. + if ($field == 'statut') { + if ($value == '0') { + $result = $member->resiliate(DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(500, 'Error when resiliating member: '.$member->error); + } + } elseif ($value == '1') { + $result = $member->validate(DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(500, 'Error when validating member: '.$member->error); + } + } + } else { + $member->$field = $value; + } + } - // If there is no error, update() returns the number of affected rows - // so if the update is a no op, the return value is zero. - if ($member->update(DolibarrApiAccess::$user) >= 0) { - return $this->get($id); - } else { - throw new RestException(500, $member->error); - } - } + // If there is no error, update() returns the number of affected rows + // so if the update is a no op, the return value is zero. + if ($member->update(DolibarrApiAccess::$user) >= 0) { + return $this->get($id); + } else { + throw new RestException(500, $member->error); + } + } - /** - * Delete member - * - * @param int $id member ID - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->adherent->supprimer) { - throw new RestException(401); - } - $member = new Adherent($this->db); - $result = $member->fetch($id); - if (!$result) { - throw new RestException(404, 'member not found'); - } + /** + * Delete member + * + * @param int $id member ID + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->adherent->supprimer) { + throw new RestException(401); + } + $member = new Adherent($this->db); + $result = $member->fetch($id); + if (!$result) { + throw new RestException(404, 'member not found'); + } - if (!DolibarrApi::_checkAccessToResource('member', $member->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('member', $member->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if (!$member->delete($member->id, DolibarrApiAccess::$user)) { - throw new RestException(401, 'error when deleting member'); - } + if (!$member->delete($member->id, DolibarrApiAccess::$user)) { + throw new RestException(401, 'error when deleting member'); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'member deleted' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'member deleted' + ) + ); + } - /** - * Validate fields before creating an object - * - * @param array|null $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $member = array(); - foreach (Members::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $member[$field] = $data[$field]; - } - return $member; - } + /** + * Validate fields before creating an object + * + * @param array|null $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $member = array(); + foreach (Members::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $member[$field] = $data[$field]; + } + return $member; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - // Remove the subscriptions because they are handled as a subresource. - unset($object->subscriptions); - unset($object->fk_incoterms); - unset($object->label_incoterms); - unset($object->location_incoterms); - unset($object->fk_delivery_address); - unset($object->shipping_method_id); + // Remove the subscriptions because they are handled as a subresource. + unset($object->subscriptions); + unset($object->fk_incoterms); + unset($object->label_incoterms); + unset($object->location_incoterms); + unset($object->fk_delivery_address); + unset($object->shipping_method_id); - unset($object->total_ht); - unset($object->total_ttc); - unset($object->total_tva); - unset($object->total_localtax1); - unset($object->total_localtax2); + unset($object->total_ht); + unset($object->total_ttc); + unset($object->total_tva); + unset($object->total_localtax1); + unset($object->total_localtax2); - return $object; - } + return $object; + } - /** - * List subscriptions of a member - * - * Get a list of subscriptions - * - * @param int $id ID of member - * @return array Array of subscription objects - * - * @throws RestException - * - * @url GET {id}/subscriptions - */ - public function getSubscriptions($id) - { - $obj_ret = array(); + /** + * List subscriptions of a member + * + * Get a list of subscriptions + * + * @param int $id ID of member + * @return array Array of subscription objects + * + * @throws RestException + * + * @url GET {id}/subscriptions + */ + public function getSubscriptions($id) + { + $obj_ret = array(); - if (!DolibarrApiAccess::$user->rights->adherent->cotisation->lire) { - throw new RestException(401); - } + if (!DolibarrApiAccess::$user->rights->adherent->cotisation->lire) { + throw new RestException(401); + } - $member = new Adherent($this->db); - $result = $member->fetch($id); - if (!$result) { - throw new RestException(404, 'member not found'); - } + $member = new Adherent($this->db); + $result = $member->fetch($id); + if (!$result) { + throw new RestException(404, 'member not found'); + } - $obj_ret = array(); - foreach ($member->subscriptions as $subscription) { - $obj_ret[] = $this->_cleanObjectDatas($subscription); - } - return $obj_ret; - } + $obj_ret = array(); + foreach ($member->subscriptions as $subscription) { + $obj_ret[] = $this->_cleanObjectDatas($subscription); + } + return $obj_ret; + } - /** - * Add a subscription for a member - * - * @param int $id ID of member - * @param int $start_date Start date {@from body} {@type timestamp} - * @param int $end_date End date {@from body} {@type timestamp} - * @param float $amount Amount (may be 0) {@from body} - * @param string $label Label {@from body} - * @return int ID of subscription - * - * @url POST {id}/subscriptions - */ - public function createSubscription($id, $start_date, $end_date, $amount, $label = '') - { - if (!DolibarrApiAccess::$user->rights->adherent->cotisation->creer) { - throw new RestException(401); - } + /** + * Add a subscription for a member + * + * @param int $id ID of member + * @param int $start_date Start date {@from body} {@type timestamp} + * @param int $end_date End date {@from body} {@type timestamp} + * @param float $amount Amount (may be 0) {@from body} + * @param string $label Label {@from body} + * @return int ID of subscription + * + * @url POST {id}/subscriptions + */ + public function createSubscription($id, $start_date, $end_date, $amount, $label = '') + { + if (!DolibarrApiAccess::$user->rights->adherent->cotisation->creer) { + throw new RestException(401); + } - $member = new Adherent($this->db); - $result = $member->fetch($id); - if (!$result) { - throw new RestException(404, 'member not found'); - } + $member = new Adherent($this->db); + $result = $member->fetch($id); + if (!$result) { + throw new RestException(404, 'member not found'); + } - return $member->subscription($start_date, $amount, 0, '', $label, '', '', '', $end_date); - } + return $member->subscription($start_date, $amount, 0, '', $label, '', '', '', $end_date); + } - /** - * Get categories for a member - * - * @param int $id ID of member - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * - * @return mixed - * - * @url GET {id}/categories - */ + /** + * Get categories for a member + * + * @param int $id ID of member + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * + * @return mixed + * + * @url GET {id}/categories + */ public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) { if (!DolibarrApiAccess::$user->rights->categorie->lire) { diff --git a/htdocs/adherents/class/api_memberstypes.class.php b/htdocs/adherents/class/api_memberstypes.class.php index 0e65a25c551..f9f410f34aa 100644 --- a/htdocs/adherents/class/api_memberstypes.class.php +++ b/htdocs/adherents/class/api_memberstypes.class.php @@ -27,289 +27,289 @@ require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php'; */ class MembersTypes extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'label', - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'label', + ); - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - } + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + } - /** - * Get properties of a member type object - * - * Return an array with member type informations - * - * @param int $id ID of member type - * @return array|mixed data without useless information - * - * @throws RestException - */ - public function get($id) - { - if (!DolibarrApiAccess::$user->rights->adherent->lire) { - throw new RestException(401); - } + /** + * Get properties of a member type object + * + * Return an array with member type informations + * + * @param int $id ID of member type + * @return array|mixed data without useless information + * + * @throws RestException + */ + public function get($id) + { + if (!DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } - $membertype = new AdherentType($this->db); - $result = $membertype->fetch($id); - if (!$result) { - throw new RestException(404, 'member type not found'); - } + $membertype = new AdherentType($this->db); + $result = $membertype->fetch($id); + if (!$result) { + throw new RestException(404, 'member type not found'); + } - if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - return $this->_cleanObjectDatas($membertype); - } + return $this->_cleanObjectDatas($membertype); + } - /** - * List members types - * - * Get a list of members types - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.libelle:like:'SO-%') and (t.subscription:=:'1')" - * @return array Array of member type objects - * - * @throws RestException - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') - { - global $db, $conf; + /** + * List members types + * + * Get a list of members types + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.libelle:like:'SO-%') and (t.subscription:=:'1')" + * @return array Array of member type objects + * + * @throws RestException + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') + { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - if (!DolibarrApiAccess::$user->rights->adherent->lire) { - throw new RestException(401); - } + if (!DolibarrApiAccess::$user->rights->adherent->lire) { + throw new RestException(401); + } - $sql = "SELECT t.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."adherent_type as t"; - $sql .= ' WHERE t.entity IN ('.getEntity('member_type').')'; + $sql = "SELECT t.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."adherent_type as t"; + $sql .= ' WHERE t.entity IN ('.getEntity('member_type').')'; - // Add sql filters - if ($sqlfilters) { - if (!DolibarrApi::_checkFilters($sqlfilters)) { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + // Add sql filters + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; - $sql .= $this->db->plimit($limit + 1, $offset); - } + $sql .= $this->db->plimit($limit + 1, $offset); + } - $result = $this->db->query($sql); - if ($result) { - $i = 0; - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) { - $obj = $this->db->fetch_object($result); - $membertype = new AdherentType($this->db); - if ($membertype->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($membertype); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve member type list : '.$this->db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No member type found'); - } + $result = $this->db->query($sql); + if ($result) { + $i = 0; + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) { + $obj = $this->db->fetch_object($result); + $membertype = new AdherentType($this->db); + if ($membertype->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($membertype); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve member type list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No member type found'); + } - return $obj_ret; - } + return $obj_ret; + } - /** - * Create member type object - * - * @param array $request_data Request data - * @return int ID of member type - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->adherent->configurer) { - throw new RestException(401); - } - // Check mandatory fields - $result = $this->_validate($request_data); + /** + * Create member type object + * + * @param array $request_data Request data + * @return int ID of member type + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->adherent->configurer) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validate($request_data); - $membertype = new AdherentType($this->db); - foreach ($request_data as $field => $value) { - $membertype->$field = $value; - } - if ($membertype->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, 'Error creating member type', array_merge(array($membertype->error), $membertype->errors)); - } - return $membertype->id; - } + $membertype = new AdherentType($this->db); + foreach ($request_data as $field => $value) { + $membertype->$field = $value; + } + if ($membertype->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, 'Error creating member type', array_merge(array($membertype->error), $membertype->errors)); + } + return $membertype->id; + } - /** - * Update member type - * - * @param int $id ID of member type to update - * @param array $request_data Datas - * @return int - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->adherent->configurer) { - throw new RestException(401); - } + /** + * Update member type + * + * @param int $id ID of member type to update + * @param array $request_data Datas + * @return int + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->adherent->configurer) { + throw new RestException(401); + } - $membertype = new AdherentType($this->db); - $result = $membertype->fetch($id); - if (!$result) { - throw new RestException(404, 'member type not found'); - } + $membertype = new AdherentType($this->db); + $result = $membertype->fetch($id); + if (!$result) { + throw new RestException(404, 'member type not found'); + } - if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - foreach ($request_data as $field => $value) { - if ($field == 'id') continue; - // Process the status separately because it must be updated using - // the validate() and resiliate() methods of the class AdherentType. - $membertype->$field = $value; - } + foreach ($request_data as $field => $value) { + if ($field == 'id') continue; + // Process the status separately because it must be updated using + // the validate() and resiliate() methods of the class AdherentType. + $membertype->$field = $value; + } - // If there is no error, update() returns the number of affected rows - // so if the update is a no op, the return value is zero. - if ($membertype->update(DolibarrApiAccess::$user) >= 0) { - return $this->get($id); - } else { - throw new RestException(500, $membertype->error); - } - } + // If there is no error, update() returns the number of affected rows + // so if the update is a no op, the return value is zero. + if ($membertype->update(DolibarrApiAccess::$user) >= 0) { + return $this->get($id); + } else { + throw new RestException(500, $membertype->error); + } + } - /** - * Delete member type - * - * @param int $id member type ID - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->adherent->configurer) { - throw new RestException(401); - } - $membertype = new AdherentType($this->db); - $result = $membertype->fetch($id); - if (!$result) { - throw new RestException(404, 'member type not found'); - } + /** + * Delete member type + * + * @param int $id member type ID + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->adherent->configurer) { + throw new RestException(401); + } + $membertype = new AdherentType($this->db); + $result = $membertype->fetch($id); + if (!$result) { + throw new RestException(404, 'member type not found'); + } - if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if (!$membertype->delete()) { - throw new RestException(401, 'error when deleting member type'); - } + if (!$membertype->delete()) { + throw new RestException(401, 'error when deleting member type'); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'member type deleted' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'member type deleted' + ) + ); + } - /** - * Validate fields before creating an object - * - * @param array|null $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $membertype = array(); - foreach (MembersTypes::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $membertype[$field] = $data[$field]; - } - return $membertype; - } + /** + * Validate fields before creating an object + * + * @param array|null $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $membertype = array(); + foreach (MembersTypes::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $membertype[$field] = $data[$field]; + } + return $membertype; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->array_options); - unset($object->linkedObjectsIds); - unset($object->context); - unset($object->canvas); - unset($object->fk_project); - unset($object->contact); - unset($object->contact_id); - unset($object->thirdparty); - unset($object->user); - unset($object->origin); - unset($object->origin_id); - unset($object->ref_ext); - unset($object->country); - unset($object->country_id); - unset($object->country_code); - unset($object->barcode_type); - unset($object->barcode_type_code); - unset($object->barcode_type_label); - unset($object->barcode_type_coder); - unset($object->mode_reglement_id); - unset($object->cond_reglement_id); - unset($object->cond_reglement); - unset($object->fk_delivery_address); - unset($object->shipping_method_id); - unset($object->model_pdf); - unset($object->fk_account); - unset($object->note_public); - unset($object->note_private); - unset($object->fk_incoterms); - unset($object->label_incoterms); - unset($object->location_incoterms); - unset($object->name); - unset($object->lastname); - unset($object->firstname); - unset($object->civility_id); - unset($object->total_ht); - unset($object->total_tva); - unset($object->total_localtax1); - unset($object->total_localtax2); - unset($object->total_ttc); + unset($object->array_options); + unset($object->linkedObjectsIds); + unset($object->context); + unset($object->canvas); + unset($object->fk_project); + unset($object->contact); + unset($object->contact_id); + unset($object->thirdparty); + unset($object->user); + unset($object->origin); + unset($object->origin_id); + unset($object->ref_ext); + unset($object->country); + unset($object->country_id); + unset($object->country_code); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); + unset($object->mode_reglement_id); + unset($object->cond_reglement_id); + unset($object->cond_reglement); + unset($object->fk_delivery_address); + unset($object->shipping_method_id); + unset($object->model_pdf); + unset($object->fk_account); + unset($object->note_public); + unset($object->note_private); + unset($object->fk_incoterms); + unset($object->label_incoterms); + unset($object->location_incoterms); + unset($object->name); + unset($object->lastname); + unset($object->firstname); + unset($object->civility_id); + unset($object->total_ht); + unset($object->total_tva); + unset($object->total_localtax1); + unset($object->total_localtax2); + unset($object->total_ttc); - return $object; - } + return $object; + } } diff --git a/htdocs/admin/fckeditor.php b/htdocs/admin/fckeditor.php index b01cc5dd19c..8f4ea7ec9c4 100644 --- a/htdocs/admin/fckeditor.php +++ b/htdocs/admin/fckeditor.php @@ -145,79 +145,79 @@ if (empty($conf->use_javascript_ajax)) { setEventMessages(array($langs->trans("NotAvailable"), $langs->trans("JavascriptDisabled")), null, 'errors'); } else { - print ''; - print ''; - print ''; - print ''; - print "\n"; + print '
'.$langs->trans("ActivateFCKeditor").''.$langs->trans("Action").'
'; + print ''; + print ''; + print ''; + print "\n"; - // Modules - foreach ($modules as $const => $desc) - { - // Si condition non remplie, on ne propose pas l'option - if (!$conditions[$const]) continue; + // Modules + foreach ($modules as $const => $desc) + { + // Si condition non remplie, on ne propose pas l'option + if (!$conditions[$const]) continue; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print '"; - print ''; - } + print ""; + print ''; + } - print '
'.$langs->trans("ActivateFCKeditor").''.$langs->trans("Action").'
'.img_object("", $picto[$const]).''.$langs->trans($desc).''; - $constante = 'FCKEDITOR_ENABLE_'.$const; - $value = (isset($conf->global->$constante) ? $conf->global->$constante : 0); - if ($value == 0) - { - print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; - } elseif ($value == 1) - { - print ''.img_picto($langs->trans("Enabled"), 'switch_on').''; - } + print '
'.img_object("", $picto[$const]).''.$langs->trans($desc).''; + $constante = 'FCKEDITOR_ENABLE_'.$const; + $value = (isset($conf->global->$constante) ? $conf->global->$constante : 0); + if ($value == 0) + { + print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; + } elseif ($value == 1) + { + print ''.img_picto($langs->trans("Enabled"), 'switch_on').''; + } - print "
'."\n"; + print ''."\n"; print '
'."\n"; print '
'."\n"; - print ''; + print ''; // Skins - show_skin(null, 1); - print '
'."\n"; + show_skin(null, 1); + print '
'."\n"; - $listofmodes = array('dolibarr_mailings', 'dolibarr_notes', 'dolibarr_details', 'dolibarr_readonly', 'Full', 'Full_inline'); - $linkstomode = ''; - foreach ($listofmodes as $newmode) - { - if ($linkstomode) $linkstomode .= ' - '; - $linkstomode .= ''; - if ($mode == $newmode) $linkstomode .= ''; - $linkstomode .= $newmode; - if ($mode == $newmode) $linkstomode .= ''; - $linkstomode .= ''; - } - $linkstomode .= ''; + $listofmodes = array('dolibarr_mailings', 'dolibarr_notes', 'dolibarr_details', 'dolibarr_readonly', 'Full', 'Full_inline'); + $linkstomode = ''; + foreach ($listofmodes as $newmode) + { + if ($linkstomode) $linkstomode .= ' - '; + $linkstomode .= ''; + if ($mode == $newmode) $linkstomode .= ''; + $linkstomode .= $newmode; + if ($mode == $newmode) $linkstomode .= ''; + $linkstomode .= ''; + } + $linkstomode .= ''; print load_fiche_titre($langs->trans("TestSubmitForm"), $linkstomode, ''); - print ''; - if ($mode != 'Full_inline') - { - $uselocalbrowser = true; - $readonly = ($mode == 'dolibarr_readonly' ? 1 : 0); - $editor = new DolEditor('formtestfield', isset($conf->global->FCKEDITOR_TEST) ? $conf->global->FCKEDITOR_TEST : 'Test', '', 200, $mode, 'In', true, $uselocalbrowser, 1, 120, 8, $readonly); - $editor->Create(); - } else { - print '
'; - print $conf->global->FCKEDITOR_TEST; - print '
'; - } - print '
'."\n"; - print '
'; - print '
'."\n"; + print ''; + if ($mode != 'Full_inline') + { + $uselocalbrowser = true; + $readonly = ($mode == 'dolibarr_readonly' ? 1 : 0); + $editor = new DolEditor('formtestfield', isset($conf->global->FCKEDITOR_TEST) ? $conf->global->FCKEDITOR_TEST : 'Test', '', 200, $mode, 'In', true, $uselocalbrowser, 1, 120, 8, $readonly); + $editor->Create(); + } else { + print '
'; + print $conf->global->FCKEDITOR_TEST; + print '
'; + } + print '
'."\n"; + print '
'; + print ''."\n"; - // Add env of ckeditor - // This is to show how CKEditor detect browser to understand why editor is disabled or not. To help debug. - /* + // Add env of ckeditor + // This is to show how CKEditor detect browser to understand why editor is disabled or not. To help debug. + /* print '
'; - // set cookie by js - $boxcontent .= ''; - } - $this->info_box_contents[0][] = array( - 'tr'=>'class="nohover showiffilter'.$this->boxcode.' hideobject"', - 'td' => 'class="nohover"', - 'textnoformat' => $boxcontent, - ); + // set cookie by js + $boxcontent .= ''; + } + $this->info_box_contents[0][] = array( + 'tr'=>'class="nohover showiffilter'.$this->boxcode.' hideobject"', + 'td' => 'class="nohover"', + 'textnoformat' => $boxcontent, + ); - // Get list of project id allowed to user (in a string list separated by coma) - $projectsListId = ''; - if (!$user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid); + // Get list of project id allowed to user (in a string list separated by coma) + $projectsListId = ''; + if (!$user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid); - $sql = "SELECT pt.rowid, pt.ref, pt.fk_projet, pt.fk_task_parent, pt.datec, pt.dateo, pt.datee, pt.datev, pt.label, pt.description, pt.duration_effective, pt.planned_workload, pt.progress"; + $sql = "SELECT pt.rowid, pt.ref, pt.fk_projet, pt.fk_task_parent, pt.datec, pt.dateo, pt.datee, pt.datev, pt.label, pt.description, pt.duration_effective, pt.planned_workload, pt.progress"; $sql .= ", p.rowid project_id, p.ref project_ref, p.title project_title"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task as pt"; $sql .= " JOIN ".MAIN_DB_PREFIX."projet as p ON (pt.fk_projet = p.rowid)"; - if ($filterValue === 'im_task_contact') { - $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = pt.rowid AND ec.fk_socpeople = ".((int) $user->id).")"; - $sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project_task' AND tc.source = 'internal' )"; - } elseif ($filterValue === 'im_project_contact') { - $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = p.rowid AND ec.fk_socpeople = ".((int) $user->id).")"; - $sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project' AND tc.source = 'internal' )"; - } + if ($filterValue === 'im_task_contact') { + $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = pt.rowid AND ec.fk_socpeople = ".((int) $user->id).")"; + $sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project_task' AND tc.source = 'internal' )"; + } elseif ($filterValue === 'im_project_contact') { + $sql .= " JOIN ".MAIN_DB_PREFIX."element_contact as ec ON (ec.element_id = p.rowid AND ec.fk_socpeople = ".((int) $user->id).")"; + $sql .= " JOIN ".MAIN_DB_PREFIX."c_type_contact as tc ON (ec.fk_c_type_contact = tc.rowid AND tc.element = 'project' AND tc.source = 'internal' )"; + } $sql .= " WHERE "; $sql .= " pt.entity = ".$conf->entity; $sql .= " AND p.fk_statut = ".Project::STATUS_VALIDATED; $sql .= " AND (pt.progress < 100 OR pt.progress IS NULL ) "; // 100% is done and not displayed - $sql .= " AND p.usage_task = 1 "; - if (!$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users + $sql .= " AND p.usage_task = 1 "; + if (!$user->rights->projet->all->lire) $sql .= " AND p.rowid IN (".$projectsListId.")"; // public and assigned to, or restricted to company for external users $sql .= " ORDER BY pt.datee ASC, pt.dateo ASC"; $sql .= $this->db->plimit($max, 0); diff --git a/htdocs/core/boxes/box_validated_projects.php b/htdocs/core/boxes/box_validated_projects.php index 87f0664ecb9..537e88b9bdf 100644 --- a/htdocs/core/boxes/box_validated_projects.php +++ b/htdocs/core/boxes/box_validated_projects.php @@ -31,8 +31,8 @@ include_once DOL_DOCUMENT_ROOT."/core/boxes/modules_boxes.php"; */ class box_validated_projects extends ModeleBoxes { - public $boxcode="validated_project"; - public $boximg="object_projectpub"; + public $boxcode = "validated_project"; + public $boximg = "object_projectpub"; public $boxlabel; //var $depends = array("projet"); @@ -65,7 +65,7 @@ class box_validated_projects extends ModeleBoxes $this->db = $db; $this->boxlabel = "ProjectsWithTask"; - $this->hidden = ! ($user->rights->projet->lire); + $this->hidden = !($user->rights->projet->lire); if ($conf->global->MAIN_FEATURES_LEVEL < 2) $this->enabled = 0; } @@ -80,11 +80,11 @@ class box_validated_projects extends ModeleBoxes { global $conf, $user, $langs; - $this->max=$max; + $this->max = $max; $totalMnt = 0; $totalnb = 0; - $totalnbTask=0; + $totalnbTask = 0; $textHead = $langs->trans("ProjectTasksWithoutTimeSpent"); $this->info_box_head = array('text' => $textHead, 'limit'=> dol_strlen($textHead)); @@ -94,27 +94,27 @@ class box_validated_projects extends ModeleBoxes include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $projectstatic = new Project($this->db); - $socid=0; + $socid = 0; //if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. // Get list of project id allowed to user (in a string list separated by coma) - $projectsListId=''; - if (! $user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid); + $projectsListId = ''; + if (!$user->rights->projet->all->lire) $projectsListId = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, $socid); // I tried to solve sql error and performance problem, rewriting sql request but it is not clear what we want. // Count of tasks without time spent for tasks we are assigned too or // Count of tasks without time spent for all tasks of projects we are allowed to read (what it does) ? $sql = "SELECT p.rowid, p.ref, p.fk_soc, p.dateo as startdate,"; - $sql.= " COUNT(DISTINCT t.rowid) as tasknumber"; - $sql.= " FROM ".MAIN_DB_PREFIX."projet AS p"; - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."projet_task AS t ON p.rowid = t.fk_projet"; + $sql .= " COUNT(DISTINCT t.rowid) as tasknumber"; + $sql .= " FROM ".MAIN_DB_PREFIX."projet AS p"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."projet_task AS t ON p.rowid = t.fk_projet"; // TODO Replace -1, -2, -3 with ID used for type of contat project_task into llx_c_type_contact. Once done, we can switch widget as stable. - $sql.= " INNER JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = t.rowid AND fk_c_type_contact IN (-1, -2, -3)"; - $sql.= " WHERE p.fk_statut = 1"; // Only open projects + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."element_contact as ec ON ec.element_id = t.rowid AND fk_c_type_contact IN (-1, -2, -3)"; + $sql .= " WHERE p.fk_statut = 1"; // Only open projects if ($projectsListId) $sql .= ' AND p.rowid IN ('.$this->db->sanitize($projectsListId).')'; // Only project we ara allowed - $sql.= " AND t.rowid NOT IN (SELECT fk_task FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_user =".$user->id.")"; - $sql.= " GROUP BY p.rowid, p.ref, p.fk_soc, p.dateo"; - $sql.= " ORDER BY p.dateo ASC"; + $sql .= " AND t.rowid NOT IN (SELECT fk_task FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_user =".$user->id.")"; + $sql .= " GROUP BY p.rowid, p.ref, p.fk_soc, p.dateo"; + $sql .= " ORDER BY p.dateo ASC"; $result = $this->db->query($sql); if ($result) { @@ -138,7 +138,7 @@ class box_validated_projects extends ModeleBoxes ); $i++; - while ($i < min($num+1, $max+1)) { + while ($i < min($num + 1, $max + 1)) { $objp = $this->db->fetch_object($result); $projectstatic->id = $objp->rowid; @@ -183,7 +183,7 @@ class box_validated_projects extends ModeleBoxes ); $i++; } - }else { + } else { dol_print_error($this->db); } } diff --git a/htdocs/core/boxes/modules_boxes.php b/htdocs/core/boxes/modules_boxes.php index a4d9aca57fd..2ac7ee05c6b 100644 --- a/htdocs/core/boxes/modules_boxes.php +++ b/htdocs/core/boxes/modules_boxes.php @@ -458,7 +458,7 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" box { // Define disabledbyname and disabledbymodule $disabledbyname = 0; - $disabledbymodule = 0; // TODO Set to 2 if module is not enabled + $disabledbymodule = 0; // TODO Set to 2 if module is not enabled $module = ''; // Check if widget file is disabled by name diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index 6015bbceece..7e8d2da34ce 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -1288,7 +1288,7 @@ abstract class CommonDocGenerator if (!empty($fields)) { // Sort extrafields by rank - uasort($fields, function ($a, $b) { + uasort($fields, function($a, $b) { return ($a->rank > $b->rank) ? 1 : -1; }); diff --git a/htdocs/core/class/cproductnature.class.php b/htdocs/core/class/cproductnature.class.php index 801a44682c9..eb16cff53ea 100644 --- a/htdocs/core/class/cproductnature.class.php +++ b/htdocs/core/class/cproductnature.class.php @@ -51,12 +51,12 @@ class CProductNature // extends CommonObject /** * @var string element */ - public $element='cproductnbature'; + public $element = 'cproductnbature'; /** * @var string table element */ - public $table_element='c_product_nature'; + public $table_element = 'c_product_nature'; /** * @var int ID @@ -108,7 +108,7 @@ class CProductNature // extends CommonObject $sql .= "label,"; $sql .= "active"; $sql .= ") VALUES ("; - $sql .= " ".(!isset($this->id) ? 'NULL' : ((int) $this->id)) .","; + $sql .= " ".(!isset($this->id) ? 'NULL' : ((int) $this->id)).","; $sql .= " ".(!isset($this->code) ? 'NULL' : ((int) $this->code)).","; $sql .= " ".(!isset($this->label) ? 'NULL' : "'".$this->db->escape(trim($this->label))."'").","; $sql .= " ".(!isset($this->active) ? 'NULL' : ((int) $this->active)).","; @@ -151,7 +151,7 @@ class CProductNature // extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; $sql_where = array(); if ($id) $sql_where[] = " t.rowid = ".$id; - if ($code>=0) $sql_where[] = " t.code = ". ((int) $code); + if ($code >= 0) $sql_where[] = " t.code = ".((int) $code); if (count($sql_where) > 0) { $sql .= ' WHERE '.implode(' AND ', $sql_where); } diff --git a/htdocs/core/class/cstate.class.php b/htdocs/core/class/cstate.class.php index b778b13c512..75ef9cc7f77 100644 --- a/htdocs/core/class/cstate.class.php +++ b/htdocs/core/class/cstate.class.php @@ -167,9 +167,9 @@ class Cstate // extends CommonObject $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; - $this->code_departement = $obj->code_departement; //deprecated + $this->code_departement = $obj->code_departement; //deprecated $this->code = $obj->code_departement; - $this->nom = $obj->nom; //deprecated + $this->nom = $obj->nom; //deprecated $this->name = $obj->nom; $this->active = $obj->active; } diff --git a/htdocs/core/class/doleditor.class.php b/htdocs/core/class/doleditor.class.php index a47ebbacd9f..a5405fd7158 100644 --- a/htdocs/core/class/doleditor.class.php +++ b/htdocs/core/class/doleditor.class.php @@ -88,7 +88,7 @@ class DolEditor // Define some properties if (in_array($this->tool, array('textarea', 'ckeditor', 'ace'))) { - if ($this->tool == 'ckeditor' && ! dol_textishtml($content)) { // We force content to be into HTML if we are using an advanced editor if content is not HTML. + if ($this->tool == 'ckeditor' && !dol_textishtml($content)) { // We force content to be into HTML if we are using an advanced editor if content is not HTML. $this->content = dol_nl2br($content); } else { diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index 0c6d15784f2..0ff627ba20c 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -881,13 +881,13 @@ class DolGraph if ($i > $firstlot) $this->stringtoshow .= ', '."\n"; $color = sprintf("%02x%02x%02x", $this->datacolor[$i][0], $this->datacolor[$i][1], $this->datacolor[$i][2]); $this->stringtoshow .= '{ '; - if (! isset($this->type[$i]) || $this->type[$i] == 'bars') { + if (!isset($this->type[$i]) || $this->type[$i] == 'bars') { if ($nblot == 3) { if ($i == $firstlot) $align = 'right'; elseif ($i == $firstlot + 1) $align = 'center'; else $align = 'left'; $this->stringtoshow .= 'bars: { lineWidth: 1, show: true, align: "'.$align.'", barWidth: 0.45 }, '; - } else $this->stringtoshow.='bars: { lineWidth: 1, show: true, align: "'.($i==$firstlot?'center':'left').'", barWidth: 0.5 }, '; + } else $this->stringtoshow .= 'bars: { lineWidth: 1, show: true, align: "'.($i == $firstlot ? 'center' : 'left').'", barWidth: 0.5 }, '; } if (isset($this->type[$i]) && ($this->type[$i] == 'lines' || $this->type[$i] == 'linesnopoint')) $this->stringtoshow .= 'lines: { show: true, fill: false }, points: { show: '.($this->type[$i] == 'linesnopoint' ? 'false' : 'true').' }, '; $this->stringtoshow .= 'color: "#'.$color.'", label: "'.(isset($this->Legend[$i]) ? dol_escape_js($this->Legend[$i]) : '').'", data: d'.$i.' }'; diff --git a/htdocs/core/class/dolreceiptprinter.class.php b/htdocs/core/class/dolreceiptprinter.class.php index c8905e756d6..5ff3f397813 100644 --- a/htdocs/core/class/dolreceiptprinter.class.php +++ b/htdocs/core/class/dolreceiptprinter.class.php @@ -868,7 +868,7 @@ class dolReceiptPrinter extends Printer public function initPrinter($printerid) { global $conf; - if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector"){ + if ($conf->global->TAKEPOS_PRINT_METHOD == "takeposconnector") { $this->connector = new DummyPrintConnector(); $this->printer = new Printer($this->connector, $this->profile); return; diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 3bdbea18702..cb8416276bc 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -3577,16 +3577,16 @@ class Form // phpcs:enable global $langs; - $num=count($this->cache_transport_mode); - if ($num > 0) return $num; // Cache already loaded + $num = count($this->cache_transport_mode); + if ($num > 0) return $num; // Cache already loaded dol_syslog(__METHOD__, LOG_DEBUG); $this->cache_transport_mode = array(); $sql = "SELECT rowid, code, label, active"; - $sql.= " FROM ".MAIN_DB_PREFIX."c_transport_mode"; - $sql.= " WHERE entity IN (".getEntity('c_transport_mode').")"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_transport_mode"; + $sql .= " WHERE entity IN (".getEntity('c_transport_mode').")"; //if ($active >= 0) $sql.= " AND active = ".$active; $resql = $this->db->query($sql); @@ -3599,10 +3599,10 @@ class Form $obj = $this->db->fetch_object($resql); // If traduction exist, we use it else we take the default label - $label=($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code)!=("PaymentTypeShort".$obj->code)?$langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code):($obj->label!='-'?$obj->label:'')); + $label = ($langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) != ("PaymentTypeShort".$obj->code) ? $langs->transnoentitiesnoconv("PaymentTypeShort".$obj->code) : ($obj->label != '-' ? $obj->label : '')); $this->cache_transport_mode[$obj->rowid]['rowid'] = $obj->rowid; $this->cache_transport_mode[$obj->rowid]['code'] = $obj->code; - $this->cache_transport_mode[$obj->rowid]['label']= $label; + $this->cache_transport_mode[$obj->rowid]['label'] = $label; $this->cache_transport_mode[$obj->rowid]['active'] = $obj->active; $i++; } @@ -3632,13 +3632,13 @@ class Form */ public function selectTransportMode($selected = '', $htmlname = 'transportmode', $format = 0, $empty = 1, $noadmininfo = 0, $maxlength = 0, $active = 1, $morecss = '') { - global $langs,$user; + global $langs, $user; dol_syslog(__METHOD__." ".$selected.", ".$htmlname.", ".$format, LOG_DEBUG); $this->load_cache_transport_mode(); - print ''; if ($empty) print ''; foreach ($this->cache_transport_mode as $id => $arraytypes) { @@ -3656,15 +3656,15 @@ class Form if (preg_match('/[a-z]/i', $selected) && $selected == $arraytypes['code']) print ' selected'; elseif ($selected == $id) print ' selected'; print '>'; - if ($format == 0) $value=($maxlength?dol_trunc($arraytypes['label'], $maxlength):$arraytypes['label']); - elseif ($format == 1) $value=$arraytypes['code']; - elseif ($format == 2) $value=($maxlength?dol_trunc($arraytypes['label'], $maxlength):$arraytypes['label']); - elseif ($format == 3) $value=$arraytypes['code']; - print $value?$value:' '; + if ($format == 0) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']); + elseif ($format == 1) $value = $arraytypes['code']; + elseif ($format == 2) $value = ($maxlength ?dol_trunc($arraytypes['label'], $maxlength) : $arraytypes['label']); + elseif ($format == 3) $value = $arraytypes['code']; + print $value ? $value : ' '; print ''; } print ''; - if ($user->admin && ! $noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin && !$noadmininfo) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); } /** diff --git a/htdocs/core/class/html.formmargin.class.php b/htdocs/core/class/html.formmargin.class.php index f66685936da..233f98df662 100644 --- a/htdocs/core/class/html.formmargin.class.php +++ b/htdocs/core/class/html.formmargin.class.php @@ -204,7 +204,7 @@ class FormMargin if (!empty($conf->global->MARGIN_ADD_SHOWHIDE_BUTTON)) // TODO Warning this feature rely on an external js file that may be removed. Using native js function document.cookie should be better { print $langs->trans('ShowMarginInfos').' : '; - $hidemargininfos = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW']); // Clean cookie + $hidemargininfos = preg_replace('/[^a-zA-Z0-9_\-]/', '', $_COOKIE['DOLUSER_MARGININFO_HIDE_SHOW']); // Clean cookie print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; print ''.img_picto($langs->trans("Enabled"), 'switch_on').''; diff --git a/htdocs/core/class/menu.class.php b/htdocs/core/class/menu.class.php index d73c7d60eab..52bd1ebddad 100644 --- a/htdocs/core/class/menu.class.php +++ b/htdocs/core/class/menu.class.php @@ -121,7 +121,7 @@ class Menu foreach ($this->liste as $val) { //if (dol_eval($val['enabled'], 1)) $nb++; - if (!empty($val['enabled'])) $nb++; // $val['enabled'] is already evaluated to 0 or 1, no need for dol_eval() + if (!empty($val['enabled'])) $nb++; // $val['enabled'] is already evaluated to 0 or 1, no need for dol_eval() } return $nb; } diff --git a/htdocs/core/class/smtps.class.php b/htdocs/core/class/smtps.class.php index 2252b46bbcd..e42622c4170 100644 --- a/htdocs/core/class/smtps.class.php +++ b/htdocs/core/class/smtps.class.php @@ -392,17 +392,17 @@ class SMTPs $socket_context = stream_context_create($this->_options); // An array of options for stream_context_create() set_error_handler([$this, 'errorHandler']); $this->socket = @stream_socket_client( - preg_replace('@tls://@i', '', $this->getHost()) . // Host to 'hit', IP or domain - ':' . $this->getPort(), // which Port number to use - $this->errno, // actual system level error - $this->errstr, // and any text that goes with the error - $this->_smtpTimeout, // timeout for reading/writing data over the socket + preg_replace('@tls://@i', '', $this->getHost()).// Host to 'hit', IP or domain + ':'.$this->getPort(), // which Port number to use + $this->errno, // actual system level error + $this->errstr, // and any text that goes with the error + $this->_smtpTimeout, // timeout for reading/writing data over the socket STREAM_CLIENT_CONNECT, $socket_context // Options for connection ); } else { $this->socket = @fsockopen( - preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain + preg_replace('@tls://@i', '', $this->getHost()), // Host to 'hit', IP or domain $this->getPort(), // which Port number to use $this->errno, // actual system level error $this->errstr, // and any text that goes with the error @@ -590,7 +590,7 @@ class SMTPs $host = preg_replace('@ssl://@i', '', $host); // Remove prefix $host = preg_replace('@tls://@i', '', $host); // Remove prefix - if ($usetls && ! empty($conf->global->MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO)) $host = 'tls://'.$host; + if ($usetls && !empty($conf->global->MAIN_SMTPS_ADD_TLS_TO_HOST_FOR_HELO)) $host = 'tls://'.$host; $hosth = $host; diff --git a/htdocs/core/customreports.php b/htdocs/core/customreports.php index 8eaf7f6da5c..0a7f4ce9826 100644 --- a/htdocs/core/customreports.php +++ b/htdocs/core/customreports.php @@ -483,7 +483,7 @@ if (!empty($search_measures) && !empty($search_xaxis)) $tmpval = preg_replace('/\-average$/', '', $val); $sql .= 'AVG('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', '; } elseif (preg_match('/\-min$/', $val)) { - $tmpval = preg_replace('/\-min$/', '', $val); + $tmpval = preg_replace('/\-min$/', '', $val); $sql .= 'MIN('.$db->ifsql($tmpval.' IS NULL', '0', $tmpval).') as y_'.$key.', '; } elseif (preg_match('/\-max$/', $val)) { $tmpval = preg_replace('/\-max$/', '', $val); diff --git a/htdocs/core/lib/admin.lib.php b/htdocs/core/lib/admin.lib.php index cdb68dbbae8..6cab3638eb5 100644 --- a/htdocs/core/lib/admin.lib.php +++ b/htdocs/core/lib/admin.lib.php @@ -131,246 +131,246 @@ function versiondolibarrarray() */ function run_sql($sqlfile, $silent = 1, $entity = '', $usesavepoint = 1, $handler = '', $okerror = 'default', $linelengthlimit = 32768, $nocommentremoval = 0, $offsetforchartofaccount = 0) { - global $db, $conf, $langs, $user; + global $db, $conf, $langs, $user; - dol_syslog("Admin.lib::run_sql run sql file ".$sqlfile." silent=".$silent." entity=".$entity." usesavepoint=".$usesavepoint." handler=".$handler." okerror=".$okerror, LOG_DEBUG); + dol_syslog("Admin.lib::run_sql run sql file ".$sqlfile." silent=".$silent." entity=".$entity." usesavepoint=".$usesavepoint." handler=".$handler." okerror=".$okerror, LOG_DEBUG); - if (!is_numeric($linelengthlimit)) - { - dol_syslog("Admin.lib::run_sql param linelengthlimit is not a numeric", LOG_ERR); - return -1; - } + if (!is_numeric($linelengthlimit)) + { + dol_syslog("Admin.lib::run_sql param linelengthlimit is not a numeric", LOG_ERR); + return -1; + } - $ok = 0; - $error = 0; - $i = 0; - $buffer = ''; - $arraysql = array(); + $ok = 0; + $error = 0; + $i = 0; + $buffer = ''; + $arraysql = array(); - // Get version of database - $versionarray = $db->getVersionArray(); + // Get version of database + $versionarray = $db->getVersionArray(); - $fp = fopen($sqlfile, "r"); - if ($fp) - { - while (!feof($fp)) - { - // Warning fgets with second parameter that is null or 0 hang. - if ($linelengthlimit > 0) $buf = fgets($fp, $linelengthlimit); - else $buf = fgets($fp); + $fp = fopen($sqlfile, "r"); + if ($fp) + { + while (!feof($fp)) + { + // Warning fgets with second parameter that is null or 0 hang. + if ($linelengthlimit > 0) $buf = fgets($fp, $linelengthlimit); + else $buf = fgets($fp); - // Test if request must be ran only for particular database or version (if yes, we must remove the -- comment) - $reg = array(); - if (preg_match('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', $buf, $reg)) - { - $qualified = 1; + // Test if request must be ran only for particular database or version (if yes, we must remove the -- comment) + $reg = array(); + if (preg_match('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', $buf, $reg)) + { + $qualified = 1; - // restrict on database type - if (!empty($reg[1])) - { - if (!preg_match('/'.preg_quote($reg[1]).'/i', $db->type)) $qualified = 0; - } + // restrict on database type + if (!empty($reg[1])) + { + if (!preg_match('/'.preg_quote($reg[1]).'/i', $db->type)) $qualified = 0; + } - // restrict on version - if ($qualified) - { - if (!empty($reg[2])) - { - if (is_numeric($reg[2])) // This is a version - { - $versionrequest = explode('.', $reg[2]); - //print var_dump($versionrequest); - //print var_dump($versionarray); - if (!count($versionrequest) || !count($versionarray) || versioncompare($versionrequest, $versionarray) > 0) - { - $qualified = 0; - } - } else // This is a test on a constant. For example when we have -- VMYSQLUTF8UNICODE, we test constant $conf->global->UTF8UNICODE - { - $dbcollation = strtoupper(preg_replace('/_/', '', $conf->db->dolibarr_main_db_collation)); - //var_dump($reg[2]); - //var_dump($dbcollation); - if (empty($conf->db->dolibarr_main_db_collation) || ($reg[2] != $dbcollation)) $qualified = 0; - //var_dump($qualified); - } - } - } + // restrict on version + if ($qualified) + { + if (!empty($reg[2])) + { + if (is_numeric($reg[2])) // This is a version + { + $versionrequest = explode('.', $reg[2]); + //print var_dump($versionrequest); + //print var_dump($versionarray); + if (!count($versionrequest) || !count($versionarray) || versioncompare($versionrequest, $versionarray) > 0) + { + $qualified = 0; + } + } else // This is a test on a constant. For example when we have -- VMYSQLUTF8UNICODE, we test constant $conf->global->UTF8UNICODE + { + $dbcollation = strtoupper(preg_replace('/_/', '', $conf->db->dolibarr_main_db_collation)); + //var_dump($reg[2]); + //var_dump($dbcollation); + if (empty($conf->db->dolibarr_main_db_collation) || ($reg[2] != $dbcollation)) $qualified = 0; + //var_dump($qualified); + } + } + } - if ($qualified) - { - // Version qualified, delete SQL comments - $buf = preg_replace('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', '', $buf); - //print "Ligne $i qualifi?e par version: ".$buf.'
'; - } - } + if ($qualified) + { + // Version qualified, delete SQL comments + $buf = preg_replace('/^--\sV(MYSQL|PGSQL)([^\s]*)/i', '', $buf); + //print "Ligne $i qualifi?e par version: ".$buf.'
'; + } + } - // Add line buf to buffer if not a comment - if ($nocommentremoval || !preg_match('/^\s*--/', $buf)) - { - if (empty($nocommentremoval)) $buf = preg_replace('/([,;ERLT\)])\s*--.*$/i', '\1', $buf); //remove comment from a line that not start with -- before add it to the buffer - $buffer .= trim($buf); - } + // Add line buf to buffer if not a comment + if ($nocommentremoval || !preg_match('/^\s*--/', $buf)) + { + if (empty($nocommentremoval)) $buf = preg_replace('/([,;ERLT\)])\s*--.*$/i', '\1', $buf); //remove comment from a line that not start with -- before add it to the buffer + $buffer .= trim($buf); + } - //print $buf.'
';exit; + //print $buf.'
';exit; - if (preg_match('/;/', $buffer)) // If string contains ';', it's end of a request string, we save it in arraysql. - { - // Found new request - if ($buffer) $arraysql[$i] = $buffer; - $i++; - $buffer = ''; - } - } + if (preg_match('/;/', $buffer)) // If string contains ';', it's end of a request string, we save it in arraysql. + { + // Found new request + if ($buffer) $arraysql[$i] = $buffer; + $i++; + $buffer = ''; + } + } - if ($buffer) $arraysql[$i] = $buffer; - fclose($fp); - } else { - dol_syslog("Admin.lib::run_sql failed to open file ".$sqlfile, LOG_ERR); - } + if ($buffer) $arraysql[$i] = $buffer; + fclose($fp); + } else { + dol_syslog("Admin.lib::run_sql failed to open file ".$sqlfile, LOG_ERR); + } - // Loop on each request to see if there is a __+MAX_table__ key - $listofmaxrowid = array(); // This is a cache table - foreach ($arraysql as $i => $sql) - { - $newsql = $sql; + // Loop on each request to see if there is a __+MAX_table__ key + $listofmaxrowid = array(); // This is a cache table + foreach ($arraysql as $i => $sql) + { + $newsql = $sql; - // Replace __+MAX_table__ with max of table - while (preg_match('/__\+MAX_([A-Za-z0-9_]+)__/i', $newsql, $reg)) - { - $table = $reg[1]; - if (!isset($listofmaxrowid[$table])) - { - //var_dump($db); - $sqlgetrowid = 'SELECT MAX(rowid) as max from '.preg_replace('/^llx_/', MAIN_DB_PREFIX, $table); - $resql = $db->query($sqlgetrowid); - if ($resql) - { - $obj = $db->fetch_object($resql); - $listofmaxrowid[$table] = $obj->max; - if (empty($listofmaxrowid[$table])) $listofmaxrowid[$table] = 0; - } else { - if (!$silent) print ''; - if (!$silent) print '
'.$langs->trans("Failed to get max rowid for ".$table)."
"; - if (!$silent) print ''; - $error++; - break; - } - } - // Replace __+MAX_llx_table__ with +999 - $from = '__+MAX_'.$table.'__'; - $to = '+'.$listofmaxrowid[$table]; - $newsql = str_replace($from, $to, $newsql); - dol_syslog('Admin.lib::run_sql New Request '.($i + 1).' (replacing '.$from.' to '.$to.')', LOG_DEBUG); + // Replace __+MAX_table__ with max of table + while (preg_match('/__\+MAX_([A-Za-z0-9_]+)__/i', $newsql, $reg)) + { + $table = $reg[1]; + if (!isset($listofmaxrowid[$table])) + { + //var_dump($db); + $sqlgetrowid = 'SELECT MAX(rowid) as max from '.preg_replace('/^llx_/', MAIN_DB_PREFIX, $table); + $resql = $db->query($sqlgetrowid); + if ($resql) + { + $obj = $db->fetch_object($resql); + $listofmaxrowid[$table] = $obj->max; + if (empty($listofmaxrowid[$table])) $listofmaxrowid[$table] = 0; + } else { + if (!$silent) print ''; + if (!$silent) print '
'.$langs->trans("Failed to get max rowid for ".$table)."
"; + if (!$silent) print ''; + $error++; + break; + } + } + // Replace __+MAX_llx_table__ with +999 + $from = '__+MAX_'.$table.'__'; + $to = '+'.$listofmaxrowid[$table]; + $newsql = str_replace($from, $to, $newsql); + dol_syslog('Admin.lib::run_sql New Request '.($i + 1).' (replacing '.$from.' to '.$to.')', LOG_DEBUG); - $arraysql[$i] = $newsql; - } + $arraysql[$i] = $newsql; + } - if ($offsetforchartofaccount > 0) - { - // Replace lines - // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401, 'PCG99-ABREGE', 'CAPIT', '1234', 1400, '...', 1);' - // with - // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401 + 200100000, 'PCG99-ABREGE','CAPIT', '1234', 1400 + 200100000, '...', 1);' - // Note: string with 1234 instead of '1234' is also supported - $newsql = preg_replace('/VALUES\s*\(__ENTITY__, \s*(\d+)\s*,(\s*\'[^\',]*\'\s*,\s*\'[^\',]*\'\s*,\s*\'?[^\',]*\'?\s*),\s*\'?([^\',]*)\'?/ims', 'VALUES (__ENTITY__, \1 + '.$offsetforchartofaccount.', \2, \3 + '.$offsetforchartofaccount, $newsql); - $newsql = preg_replace('/([,\s])0 \+ '.$offsetforchartofaccount.'/ims', '\1 0', $newsql); - //var_dump($newsql); - $arraysql[$i] = $newsql; - } - } + if ($offsetforchartofaccount > 0) + { + // Replace lines + // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401, 'PCG99-ABREGE', 'CAPIT', '1234', 1400, '...', 1);' + // with + // 'INSERT INTO llx_accounting_account (entity, rowid, fk_pcg_version, pcg_type, account_number, account_parent, label, active) VALUES (__ENTITY__, 1401 + 200100000, 'PCG99-ABREGE','CAPIT', '1234', 1400 + 200100000, '...', 1);' + // Note: string with 1234 instead of '1234' is also supported + $newsql = preg_replace('/VALUES\s*\(__ENTITY__, \s*(\d+)\s*,(\s*\'[^\',]*\'\s*,\s*\'[^\',]*\'\s*,\s*\'?[^\',]*\'?\s*),\s*\'?([^\',]*)\'?/ims', 'VALUES (__ENTITY__, \1 + '.$offsetforchartofaccount.', \2, \3 + '.$offsetforchartofaccount, $newsql); + $newsql = preg_replace('/([,\s])0 \+ '.$offsetforchartofaccount.'/ims', '\1 0', $newsql); + //var_dump($newsql); + $arraysql[$i] = $newsql; + } + } - // Loop on each request to execute request - $cursorinsert = 0; - $listofinsertedrowid = array(); - foreach ($arraysql as $i => $sql) - { - if ($sql) - { - // Replace the prefix tables - if (MAIN_DB_PREFIX != 'llx_') - { - $sql = preg_replace('/llx_/i', MAIN_DB_PREFIX, $sql); - } + // Loop on each request to execute request + $cursorinsert = 0; + $listofinsertedrowid = array(); + foreach ($arraysql as $i => $sql) + { + if ($sql) + { + // Replace the prefix tables + if (MAIN_DB_PREFIX != 'llx_') + { + $sql = preg_replace('/llx_/i', MAIN_DB_PREFIX, $sql); + } - if (!empty($handler)) $sql = preg_replace('/__HANDLER__/i', "'".$db->escape($handler)."'", $sql); + if (!empty($handler)) $sql = preg_replace('/__HANDLER__/i', "'".$db->escape($handler)."'", $sql); - $newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : $conf->entity), $sql); + $newsql = preg_replace('/__ENTITY__/i', (!empty($entity) ? $entity : $conf->entity), $sql); - // Add log of request - if (!$silent) print ''.$langs->trans("Request").' '.($i + 1)." sql='".dol_htmlentities($newsql, ENT_NOQUOTES)."'\n"; - dol_syslog('Admin.lib::run_sql Request '.($i + 1), LOG_DEBUG); + // Add log of request + if (!$silent) print ''.$langs->trans("Request").' '.($i + 1)." sql='".dol_htmlentities($newsql, ENT_NOQUOTES)."'\n"; + dol_syslog('Admin.lib::run_sql Request '.($i + 1), LOG_DEBUG); $sqlmodified = 0; - // Replace for encrypt data - if (preg_match_all('/__ENCRYPT\(\'([^\']+)\'\)__/i', $newsql, $reg)) - { - $num = count($reg[0]); + // Replace for encrypt data + if (preg_match_all('/__ENCRYPT\(\'([^\']+)\'\)__/i', $newsql, $reg)) + { + $num = count($reg[0]); - for ($j = 0; $j < $num; $j++) - { - $from = $reg[0][$j]; - $to = $db->encrypt($reg[1][$j], 1); - $newsql = str_replace($from, $to, $newsql); - } - $sqlmodified++; - } + for ($j = 0; $j < $num; $j++) + { + $from = $reg[0][$j]; + $to = $db->encrypt($reg[1][$j], 1); + $newsql = str_replace($from, $to, $newsql); + } + $sqlmodified++; + } - // Replace for decrypt data - if (preg_match_all('/__DECRYPT\(\'([A-Za-z0-9_]+)\'\)__/i', $newsql, $reg)) - { - $num = count($reg[0]); + // Replace for decrypt data + if (preg_match_all('/__DECRYPT\(\'([A-Za-z0-9_]+)\'\)__/i', $newsql, $reg)) + { + $num = count($reg[0]); - for ($j = 0; $j < $num; $j++) - { - $from = $reg[0][$j]; - $to = $db->decrypt($reg[1][$j]); - $newsql = str_replace($from, $to, $newsql); - } - $sqlmodified++; - } + for ($j = 0; $j < $num; $j++) + { + $from = $reg[0][$j]; + $to = $db->decrypt($reg[1][$j]); + $newsql = str_replace($from, $to, $newsql); + } + $sqlmodified++; + } - // Replace __x__ with rowid of insert nb x - while (preg_match('/__([0-9]+)__/', $newsql, $reg)) - { - $cursor = $reg[1]; - if (empty($listofinsertedrowid[$cursor])) - { - if (!$silent) print ''; - if (!$silent) print '
'.$langs->trans("FileIsNotCorrect")."
"; - if (!$silent) print ''; - $error++; - break; - } - $from = '__'.$cursor.'__'; - $to = $listofinsertedrowid[$cursor]; - $newsql = str_replace($from, $to, $newsql); - $sqlmodified++; - } + // Replace __x__ with rowid of insert nb x + while (preg_match('/__([0-9]+)__/', $newsql, $reg)) + { + $cursor = $reg[1]; + if (empty($listofinsertedrowid[$cursor])) + { + if (!$silent) print ''; + if (!$silent) print '
'.$langs->trans("FileIsNotCorrect")."
"; + if (!$silent) print ''; + $error++; + break; + } + $from = '__'.$cursor.'__'; + $to = $listofinsertedrowid[$cursor]; + $newsql = str_replace($from, $to, $newsql); + $sqlmodified++; + } - if ($sqlmodified) dol_syslog('Admin.lib::run_sql New Request '.($i + 1), LOG_DEBUG); + if ($sqlmodified) dol_syslog('Admin.lib::run_sql New Request '.($i + 1), LOG_DEBUG); - $result = $db->query($newsql, $usesavepoint); - if ($result) - { - if (!$silent) print ''."\n"; + $result = $db->query($newsql, $usesavepoint); + if ($result) + { + if (!$silent) print ''."\n"; - if (preg_replace('/insert into ([^\s]+)/i', $newsql, $reg)) - { - $cursorinsert++; + if (preg_replace('/insert into ([^\s]+)/i', $newsql, $reg)) + { + $cursorinsert++; - // It's an insert - $table = preg_replace('/([^a-zA-Z_]+)/i', '', $reg[1]); - $insertedrowid = $db->last_insert_id($table); - $listofinsertedrowid[$cursorinsert] = $insertedrowid; - dol_syslog('Admin.lib::run_sql Insert nb '.$cursorinsert.', done in table '.$table.', rowid is '.$listofinsertedrowid[$cursorinsert], LOG_DEBUG); - } - // print 'OK'; - } else { - $errno = $db->errno(); - if (!$silent) print ''."\n"; + // It's an insert + $table = preg_replace('/([^a-zA-Z_]+)/i', '', $reg[1]); + $insertedrowid = $db->last_insert_id($table); + $listofinsertedrowid[$cursorinsert] = $insertedrowid; + dol_syslog('Admin.lib::run_sql Insert nb '.$cursorinsert.', done in table '.$table.', rowid is '.$listofinsertedrowid[$cursorinsert], LOG_DEBUG); + } + // print 'OK'; + } else { + $errno = $db->errno(); + if (!$silent) print ''."\n"; // Define list of errors we accept (array $okerrors) - $okerrors = array( // By default + $okerrors = array( // By default 'DB_ERROR_TABLE_ALREADY_EXISTS', 'DB_ERROR_COLUMN_ALREADY_EXISTS', 'DB_ERROR_KEY_NAME_ALREADY_EXISTS', @@ -383,32 +383,32 @@ function run_sql($sqlfile, $silent = 1, $entity = '', $usesavepoint = 1, $handle 'DB_ERROR_CANNOT_CREATE', // Qd contrainte deja existante 'DB_ERROR_CANT_DROP_PRIMARY_KEY', 'DB_ERROR_PRIMARY_KEY_ALREADY_EXISTS', - 'DB_ERROR_22P02' + 'DB_ERROR_22P02' ); - if ($okerror == 'none') $okerrors = array(); + if ($okerror == 'none') $okerrors = array(); - // Is it an error we accept + // Is it an error we accept if (!in_array($errno, $okerrors)) { - if (!$silent) print ''; - if (!$silent) print '
'.$langs->trans("Error")." ".$db->errno().": ".$newsql."
".$db->error()."
"; - if (!$silent) print ''."\n"; - dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."
".$db->error(), LOG_ERR); - $error++; + if (!$silent) print ''; + if (!$silent) print '
'.$langs->trans("Error")." ".$db->errno().": ".$newsql."
".$db->error()."
"; + if (!$silent) print ''."\n"; + dol_syslog('Admin.lib::run_sql Request '.($i + 1)." Error ".$db->errno()." ".$newsql."
".$db->error(), LOG_ERR); + $error++; } - } + } - if (!$silent) print ''."\n"; - } - } + if (!$silent) print ''."\n"; + } + } - if ($error == 0) - { - if (!$silent) { - print ''.$langs->trans("ProcessMigrateScript").''; - print ''.$langs->trans("OK"); - //if (! empty($conf->use_javascript_ajax)) { - print ''; - print ' - '.$langs->trans("ShowHideDetails").''; - //} - print ''."\n"; - } - $ok = 1; - } else { - if (!$silent) { - print ''.$langs->trans("ProcessMigrateScript").''; - print ''.$langs->trans("KO").''; - print ''."\n"; - } - $ok = 0; - } + print ' - '.$langs->trans("ShowHideDetails").''; + //} + print ''."\n"; + } + $ok = 1; + } else { + if (!$silent) { + print ''.$langs->trans("ProcessMigrateScript").''; + print ''.$langs->trans("KO").''; + print ''."\n"; + } + $ok = 0; + } - return $ok; + return $ok; } diff --git a/htdocs/core/lib/contact.lib.php b/htdocs/core/lib/contact.lib.php index f0b7a2c203f..7f7ea22e254 100644 --- a/htdocs/core/lib/contact.lib.php +++ b/htdocs/core/lib/contact.lib.php @@ -59,7 +59,7 @@ function contact_prepare_head(Contact $object) $tab++; // Related items - if (! empty($conf->commande->enabled) || ! empty($conf->propal->enabled) || ! empty($conf->facture->enabled) || ! empty($conf->ficheinter->enabled) || !empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) + if (!empty($conf->commande->enabled) || !empty($conf->propal->enabled) || !empty($conf->facture->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) { $head[$tab][0] = DOL_URL_ROOT.'/contact/consumption.php?id='.$object->id; $head[$tab][1] = $langs->trans("Referers"); diff --git a/htdocs/core/lib/fourn.lib.php b/htdocs/core/lib/fourn.lib.php index 531152582ec..7ebe1d290b7 100644 --- a/htdocs/core/lib/fourn.lib.php +++ b/htdocs/core/lib/fourn.lib.php @@ -45,8 +45,8 @@ function facturefourn_prepare_head($object) if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { - $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); - $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/contact.php?facid='.$object->id; + $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/contact.php?facid='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; $head[$h][2] = 'contact'; @@ -75,29 +75,29 @@ function facturefourn_prepare_head($object) $h++; } - // Show more tabs from modules - // Entries must be declared in modules descriptor with line - // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab - // $this->tabs = array('entity:-tabname); to remove a tab - complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice'); + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + // $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab + // $this->tabs = array('entity:-tabname); to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_invoice'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { - $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) + { + $nbNote = 0; + if (!empty($object->note_private)) $nbNote++; if (!empty($object->note_public)) $nbNote++; - $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id; - $head[$h][1] = $langs->trans('Notes'); + $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/note.php?facid='.$object->id; + $head[$h][1] = $langs->trans('Notes'); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; - $head[$h][2] = 'note'; - $h++; - } + $head[$h][2] = 'note'; + $h++; + } require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$object->ref; $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); + $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$object->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 50e86f7847d..5fc4fbd070d 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -1129,7 +1129,7 @@ function dol_strtoupper($string, $encoding = "UTF-8") function dol_ucfirst($string, $encoding = "UTF-8") { if (function_exists('mb_substr')) { - return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding) . mb_substr($string, 1, null, $encoding); + return mb_strtoupper(mb_substr($string, 0, 1, $encoding), $encoding).mb_substr($string, 1, null, $encoding); } else { return ucfirst($string); } diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index fda2cd01853..8da3a978b80 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -1440,7 +1440,7 @@ function print_left_eldy_menu($db, $menu_array_before, $menu_array_after, &$tabM } // Intracomm report - if (! empty($conf->intracommreport->enabled)) + if (!empty($conf->intracommreport->enabled)) { $newmenu->add("/intracommreport/list.php?leftmenu=intracommreport", $langs->trans("MenuIntracommReport"), 0, $user->rights->intracommreport->read, '', $mainmenu, 'intracommreport', 1); if ($usemenuhider || empty($leftmenu) || preg_match('/intracommreport/', $leftmenu)) { diff --git a/htdocs/core/modules/delivery/doc/pdf_storm.modules.php b/htdocs/core/modules/delivery/doc/pdf_storm.modules.php index 563f5367d95..08c354562c8 100644 --- a/htdocs/core/modules/delivery/doc/pdf_storm.modules.php +++ b/htdocs/core/modules/delivery/doc/pdf_storm.modules.php @@ -422,8 +422,8 @@ class pdf_storm extends ModelePDFDeliveryOrder $pdf->SetTextColor(0, 0, 0); // Define size of image if we need it - $imglinesize=array(); - if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]); + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); $pdf->setTopMargin($tab_top_newpage); diff --git a/htdocs/core/modules/modIntracommreport.class.php b/htdocs/core/modules/modIntracommreport.class.php index d5813262ae8..668cf7af875 100644 --- a/htdocs/core/modules/modIntracommreport.class.php +++ b/htdocs/core/modules/modIntracommreport.class.php @@ -52,7 +52,7 @@ class modIntracommreport extends DolibarrModules // Possible values for version are: 'development', 'experimental', 'dolibarr' or 'dolibarr_deprecated' or version $this->version = 'development'; - $this->const_name = 'MAIN_MODULE_' . strtoupper($this->name); + $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); $this->picto = 'intracommreport'; // Data directories to create when module is enabled @@ -86,12 +86,12 @@ class modIntracommreport extends DolibarrModules $this->boxes = array(); // Dictionaries - if (! isset($conf->intracommreport->enabled)) + if (!isset($conf->intracommreport->enabled)) { - $conf->intracommreport=new stdClass(); - $conf->intracommreport->enabled=0; + $conf->intracommreport = new stdClass(); + $conf->intracommreport->enabled = 0; } - $this->dictionaries=array(); + $this->dictionaries = array(); // Permissions $this->rights = array(); diff --git a/htdocs/core/photos_resize.php b/htdocs/core/photos_resize.php index 19798f9df2d..3ceef18d8ae 100644 --- a/htdocs/core/photos_resize.php +++ b/htdocs/core/photos_resize.php @@ -257,7 +257,7 @@ if (empty($backtourl)) elseif (in_array($modulepart, array('mrp'))) $backtourl = DOL_URL_ROOT."/mrp/mo_document.php?id=".$id.'&file='.urldecode($file); elseif (in_array($modulepart, array('medias'))) { $section_dir = dirname($file); - if (! preg_match('/\/$/', $section_dir)) $section_dir.='/'; + if (!preg_match('/\/$/', $section_dir)) $section_dir .= '/'; $backtourl = DOL_URL_ROOT."/website/index.php?action=file_manager&website=".$website.'§ion_dir='.urlencode($section_dir); } // Generic case that should work for everybody else diff --git a/htdocs/dav/fileserver.php b/htdocs/dav/fileserver.php index bd6df769553..c4939bd4069 100644 --- a/htdocs/dav/fileserver.php +++ b/htdocs/dav/fileserver.php @@ -82,7 +82,7 @@ $tmpDir = $conf->dav->multidir_output[$entity]; // We need root dir, not a dir t // Authentication callback function -$authBackend = new \Sabre\DAV\Auth\Backend\BasicCallBack(function ($username, $password) { +$authBackend = new \Sabre\DAV\Auth\Backend\BasicCallBack(function($username, $password) { global $user; global $conf; global $dolibarr_main_authentication, $dolibarr_auto_user; diff --git a/htdocs/debugbar/class/autoloader.php b/htdocs/debugbar/class/autoloader.php index 91606babb84..721febdd13c 100644 --- a/htdocs/debugbar/class/autoloader.php +++ b/htdocs/debugbar/class/autoloader.php @@ -4,7 +4,7 @@ * Simple autoloader, so we don't need Composer just for this. */ -spl_autoload_register(function ($class) { +spl_autoload_register(function($class) { if (preg_match('/^DebugBar/', $class)) { $file = DOL_DOCUMENT_ROOT.'/includes/maximebf/debugbar/src/'.str_replace('\\', DIRECTORY_SEPARATOR, $class).'.php'; //var_dump($class.' - '.file_exists($file).' - '.$file); diff --git a/htdocs/don/class/api_donations.class.php b/htdocs/don/class/api_donations.class.php index e5a9a597a47..18a8563fd89 100644 --- a/htdocs/don/class/api_donations.class.php +++ b/htdocs/don/class/api_donations.class.php @@ -304,62 +304,62 @@ class Donations extends DolibarrApi $result = $this->don->valid(DolibarrApiAccess::$user, $idwarehouse, $notrigger); if ($result == 0) { - throw new RestException(304, 'Error nothing done. May be object is already validated'); + throw new RestException(304, 'Error nothing done. May be object is already validated'); } if ($result < 0) { - throw new RestException(500, 'Error when validating Order: '.$this->don->error); + throw new RestException(500, 'Error when validating Order: '.$this->don->error); + } + $result = $this->don->fetch($id); + if (!$result) { + throw new RestException(404, 'Order not found'); } - $result = $this->don->fetch($id); - if (!$result) { - throw new RestException(404, 'Order not found'); - } - if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('don', $this->don->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $this->don->fetchObjectLinked(); + $this->don->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->don); - } + return $this->_cleanObjectDatas($this->don); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->note); - unset($object->address); - unset($object->barcode_type); - unset($object->barcode_type_code); - unset($object->barcode_type_label); - unset($object->barcode_type_coder); + unset($object->note); + unset($object->address); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - private function _validate($data) - { - $don = array(); - foreach (Orders::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, $field." field missing"); - $don[$field] = $data[$field]; - } - return $don; - } + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + private function _validate($data) + { + $don = array(); + foreach (Orders::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, $field." field missing"); + $don[$field] = $data[$field]; + } + return $don; + } } diff --git a/htdocs/expedition/class/api_shipments.class.php b/htdocs/expedition/class/api_shipments.class.php index 7b4b424ae4a..22acaeaa26b 100644 --- a/htdocs/expedition/class/api_shipments.class.php +++ b/htdocs/expedition/class/api_shipments.class.php @@ -606,60 +606,60 @@ class Shipments extends DolibarrApi } */ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->thirdparty); // id already returned + unset($object->thirdparty); // id already returned - unset($object->note); - unset($object->address); - unset($object->barcode_type); - unset($object->barcode_type_code); - unset($object->barcode_type_label); - unset($object->barcode_type_coder); + unset($object->note); + unset($object->address); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); - if (!empty($object->lines) && is_array($object->lines)) - { - foreach ($object->lines as $line) - { - unset($line->tva_tx); - unset($line->vat_src_code); - unset($line->total_ht); - unset($line->total_ttc); - unset($line->total_tva); - unset($line->total_localtax1); - unset($line->total_localtax2); - unset($line->remise_percent); - } - } + if (!empty($object->lines) && is_array($object->lines)) + { + foreach ($object->lines as $line) + { + unset($line->tva_tx); + unset($line->vat_src_code); + unset($line->total_ht); + unset($line->total_ttc); + unset($line->total_tva); + unset($line->total_localtax1); + unset($line->total_localtax2); + unset($line->remise_percent); + } + } - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - private function _validate($data) - { - $shipment = array(); - foreach (Shipments::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $shipment[$field] = $data[$field]; - } - return $shipment; - } + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + private function _validate($data) + { + $shipment = array(); + foreach (Shipments::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $shipment[$field] = $data[$field]; + } + return $shipment; + } } diff --git a/htdocs/expensereport/class/api_expensereports.class.php b/htdocs/expensereport/class/api_expensereports.class.php index 78c74a79bd9..aa892e50fc0 100644 --- a/htdocs/expensereport/class/api_expensereports.class.php +++ b/htdocs/expensereport/class/api_expensereports.class.php @@ -30,171 +30,171 @@ class ExpenseReports extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'fk_user_author' - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'fk_user_author' + ); - /** - * @var ExpenseReport $expensereport {@type ExpenseReport} - */ - public $expensereport; + /** + * @var ExpenseReport $expensereport {@type ExpenseReport} + */ + public $expensereport; - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - $this->expensereport = new ExpenseReport($this->db); - } + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + $this->expensereport = new ExpenseReport($this->db); + } - /** - * Get properties of a Expense Report object - * - * Return an array with Expense Report informations - * - * @param int $id ID of Expense Report - * @return array|mixed Data without useless information - * - * @throws RestException - */ - public function get($id) - { - if (!DolibarrApiAccess::$user->rights->expensereport->lire) { - throw new RestException(401); - } + /** + * Get properties of a Expense Report object + * + * Return an array with Expense Report informations + * + * @param int $id ID of Expense Report + * @return array|mixed Data without useless information + * + * @throws RestException + */ + public function get($id) + { + if (!DolibarrApiAccess::$user->rights->expensereport->lire) { + throw new RestException(401); + } - $result = $this->expensereport->fetch($id); - if (!$result) { - throw new RestException(404, 'Expense report not found'); - } + $result = $this->expensereport->fetch($id); + if (!$result) { + throw new RestException(404, 'Expense report not found'); + } - if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('expensereport', $this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $this->expensereport->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->expensereport); - } + $this->expensereport->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->expensereport); + } - /** - * List Expense Reports - * - * Get a list of Expense Reports - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $user_ids User ids filter field. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" - * @return array Array of Expense Report objects - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '') - { - global $db, $conf; + /** + * List Expense Reports + * + * Get a list of Expense Reports + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $user_ids User ids filter field. Example: '1' or '1,2,3' {@pattern /^[0-9,]*$/i} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" + * @return array Array of Expense Report objects + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '') + { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - // case of external user, $societe param is ignored and replaced by user's socid - //$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $societe; + // case of external user, $societe param is ignored and replaced by user's socid + //$socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $societe; - $sql = "SELECT t.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t"; - $sql .= ' WHERE t.entity IN ('.getEntity('expensereport').')'; - if ($user_ids) $sql .= " AND t.fk_user_author IN (".$user_ids.")"; + $sql = "SELECT t.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t"; + $sql .= ' WHERE t.entity IN ('.getEntity('expensereport').')'; + if ($user_ids) $sql .= " AND t.fk_user_author IN (".$user_ids.")"; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; - $sql .= $this->db->plimit($limit + 1, $offset); - } + $sql .= $this->db->plimit($limit + 1, $offset); + } - $result = $this->db->query($sql); + $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); + if ($result) + { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { - $obj = $this->db->fetch_object($result); - $expensereport_static = new ExpenseReport($this->db); - if ($expensereport_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($expensereport_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve Expense Report list : '.$this->db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No Expense Report found'); - } - return $obj_ret; - } + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + $expensereport_static = new ExpenseReport($this->db); + if ($expensereport_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($expensereport_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve Expense Report list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No Expense Report found'); + } + return $obj_ret; + } - /** - * Create Expense Report object - * - * @param array $request_data Request data - * @return int ID of Expense Report - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401, "Insuffisant rights"); - } - // Check mandatory fields - $result = $this->_validate($request_data); + /** + * Create Expense Report object + * + * @param array $request_data Request data + * @return int ID of Expense Report + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validate($request_data); - foreach ($request_data as $field => $value) { - $this->expensereport->$field = $value; - } - /*if (isset($request_data["lines"])) { + foreach ($request_data as $field => $value) { + $this->expensereport->$field = $value; + } + /*if (isset($request_data["lines"])) { $lines = array(); foreach ($request_data["lines"] as $line) { array_push($lines, (object) $line); } $this->expensereport->lines = $lines; }*/ - if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors)); - } + if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors)); + } - return $this->expensereport->id; - } + return $this->expensereport->id; + } - /** - * Get lines of an Expense Report - * - * @param int $id Id of Expense Report - * - * @url GET {id}/lines - * - * @return int - */ - /* + /** + * Get lines of an Expense Report + * + * @param int $id Id of Expense Report + * + * @url GET {id}/lines + * + * @return int + */ + /* public function getLines($id) { if(! DolibarrApiAccess::$user->rights->expensereport->lire) { @@ -490,75 +490,75 @@ class ExpenseReports extends DolibarrApi ); }*/ - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->fk_statut); - unset($object->statut); - unset($object->user); - unset($object->thirdparty); + unset($object->fk_statut); + unset($object->statut); + unset($object->user); + unset($object->thirdparty); - unset($object->cond_reglement); - unset($object->shipping_method_id); + unset($object->cond_reglement); + unset($object->shipping_method_id); - unset($object->barcode_type); - unset($object->barcode_type_code); - unset($object->barcode_type_label); - unset($object->barcode_type_coder); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); - unset($object->code_paiement); - unset($object->code_statut); - unset($object->fk_c_paiement); - unset($object->fk_incoterms); - unset($object->label_incoterms); - unset($object->location_incoterms); - unset($object->mode_reglement_id); - unset($object->cond_reglement_id); + unset($object->code_paiement); + unset($object->code_statut); + unset($object->fk_c_paiement); + unset($object->fk_incoterms); + unset($object->label_incoterms); + unset($object->location_incoterms); + unset($object->mode_reglement_id); + unset($object->cond_reglement_id); - unset($object->name); - unset($object->lastname); - unset($object->firstname); - unset($object->civility_id); - unset($object->cond_reglement_id); - unset($object->contact); - unset($object->contact_id); + unset($object->name); + unset($object->lastname); + unset($object->firstname); + unset($object->civility_id); + unset($object->cond_reglement_id); + unset($object->contact); + unset($object->contact_id); - unset($object->state); - unset($object->state_id); - unset($object->state_code); - unset($object->country); - unset($object->country_id); - unset($object->country_code); + unset($object->state); + unset($object->state_id); + unset($object->state_code); + unset($object->country); + unset($object->country_id); + unset($object->country_code); - unset($object->note); // We already use note_public and note_pricate + unset($object->note); // We already use note_public and note_pricate - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - private function _validate($data) - { - $expensereport = array(); - foreach (ExpenseReports::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $expensereport[$field] = $data[$field]; - } - return $expensereport; - } + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + private function _validate($data) + { + $expensereport = array(); + foreach (ExpenseReports::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $expensereport[$field] = $data[$field]; + } + return $expensereport; + } } diff --git a/htdocs/fichinter/class/api_interventions.class.php b/htdocs/fichinter/class/api_interventions.class.php index d5282bffb01..7046a61e2d5 100644 --- a/htdocs/fichinter/class/api_interventions.class.php +++ b/htdocs/fichinter/class/api_interventions.class.php @@ -239,218 +239,218 @@ class Interventions extends DolibarrApi } */ - /** - * Add a line to given intervention - * - * @param int $id Id of intervention to update - * @param array $request_data Request data - * - * @url POST {id}/lines - * - * @return int - */ - public function postLine($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->ficheinter->creer) { - throw new RestException(401, "Insuffisant rights"); - } - // Check mandatory fields - $result = $this->_validateLine($request_data); + /** + * Add a line to given intervention + * + * @param int $id Id of intervention to update + * @param array $request_data Request data + * + * @url POST {id}/lines + * + * @return int + */ + public function postLine($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->ficheinter->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validateLine($request_data); - foreach ($request_data as $field => $value) { - $this->fichinter->$field = $value; - } + foreach ($request_data as $field => $value) { + $this->fichinter->$field = $value; + } - if (!$result) { - throw new RestException(404, 'Intervention not found'); - } + if (!$result) { + throw new RestException(404, 'Intervention not found'); + } - if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $updateRes = $this->fichinter->addLine( - DolibarrApiAccess::$user, - $id, - $this->fichinter->description, - $this->fichinter->date, - $this->fichinter->duree - ); + $updateRes = $this->fichinter->addLine( + DolibarrApiAccess::$user, + $id, + $this->fichinter->description, + $this->fichinter->date, + $this->fichinter->duree + ); - if ($updateRes > 0) { - return $updateRes; - } else { - throw new RestException(400, $this->fichinter->error); - } - } + if ($updateRes > 0) { + return $updateRes; + } else { + throw new RestException(400, $this->fichinter->error); + } + } - /** - * Delete order - * - * @param int $id Order ID - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->ficheinter->supprimer) { - throw new RestException(401); - } - $result = $this->fichinter->fetch($id); - if (!$result) { - throw new RestException(404, 'Intervention not found'); - } + /** + * Delete order + * + * @param int $id Order ID + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->ficheinter->supprimer) { + throw new RestException(401); + } + $result = $this->fichinter->fetch($id); + if (!$result) { + throw new RestException(404, 'Intervention not found'); + } - if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if (!$this->fichinter->delete(DolibarrApiAccess::$user)) { - throw new RestException(500, 'Error when delete intervention : '.$this->fichinter->error); - } + if (!$this->fichinter->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete intervention : '.$this->fichinter->error); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Intervention deleted' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Intervention deleted' + ) + ); + } - /** - * Validate an intervention - * - * If you get a bad value for param notrigger check, provide this in body - * { - * "notrigger": 0 - * } - * - * @param int $id Intervention ID - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * - * @url POST {id}/validate - * - * @return array - */ - public function validate($id, $notrigger = 0) - { - if (!DolibarrApiAccess::$user->rights->ficheinter->creer) { - throw new RestException(401, "Insuffisant rights"); - } - $result = $this->fichinter->fetch($id); - if (!$result) { - throw new RestException(404, 'Intervention not found'); - } + /** + * Validate an intervention + * + * If you get a bad value for param notrigger check, provide this in body + * { + * "notrigger": 0 + * } + * + * @param int $id Intervention ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/validate + * + * @return array + */ + public function validate($id, $notrigger = 0) + { + if (!DolibarrApiAccess::$user->rights->ficheinter->creer) { + throw new RestException(401, "Insuffisant rights"); + } + $result = $this->fichinter->fetch($id); + if (!$result) { + throw new RestException(404, 'Intervention not found'); + } - if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $result = $this->fichinter->setValid(DolibarrApiAccess::$user, $notrigger); - if ($result == 0) { - throw new RestException(304, 'Error nothing done. May be object is already validated'); - } - if ($result < 0) { - throw new RestException(500, 'Error when validating Intervention: '.$this->commande->error); - } + $result = $this->fichinter->setValid(DolibarrApiAccess::$user, $notrigger); + if ($result == 0) { + throw new RestException(304, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error when validating Intervention: '.$this->commande->error); + } - $this->fichinter->fetchObjectLinked(); + $this->fichinter->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->fichinter); - } + return $this->_cleanObjectDatas($this->fichinter); + } - /** - * Close an intervention - * - * @param int $id Intervention ID - * - * @url POST {id}/close - * - * @return array - */ - public function closeFichinter($id) - { - if (!DolibarrApiAccess::$user->rights->ficheinter->creer) - { - throw new RestException(401, "Insuffisant rights"); - } - $result = $this->fichinter->fetch($id); - if (!$result) { - throw new RestException(404, 'Intervention not found'); - } + /** + * Close an intervention + * + * @param int $id Intervention ID + * + * @url POST {id}/close + * + * @return array + */ + public function closeFichinter($id) + { + if (!DolibarrApiAccess::$user->rights->ficheinter->creer) + { + throw new RestException(401, "Insuffisant rights"); + } + $result = $this->fichinter->fetch($id); + if (!$result) { + throw new RestException(404, 'Intervention not found'); + } - if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('fichinter', $this->fichinter->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $result = $this->fichinter->setStatut(3); + $result = $this->fichinter->setStatut(3); - if ($result == 0) { - throw new RestException(304, 'Error nothing done. May be object is already closed'); - } - if ($result < 0) { - throw new RestException(500, 'Error when closing Intervention: '.$this->fichinter->error); - } + if ($result == 0) { + throw new RestException(304, 'Error nothing done. May be object is already closed'); + } + if ($result < 0) { + throw new RestException(500, 'Error when closing Intervention: '.$this->fichinter->error); + } - $this->fichinter->fetchObjectLinked(); + $this->fichinter->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->fichinter); - } + return $this->_cleanObjectDatas($this->fichinter); + } - /** - * Validate fields before create or update object - * - * @param array $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $fichinter = array(); - foreach (Interventions::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $fichinter[$field] = $data[$field]; - } - return $fichinter; - } + /** + * Validate fields before create or update object + * + * @param array $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $fichinter = array(); + foreach (Interventions::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $fichinter[$field] = $data[$field]; + } + return $fichinter; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->statuts_short); - unset($object->statuts_logo); - unset($object->statuts); + unset($object->statuts_short); + unset($object->statuts_logo); + unset($object->statuts); - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validateLine($data) - { - $fichinter = array(); - foreach (Interventions::$FIELDSLINE as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $fichinter[$field] = $data[$field]; - } - return $fichinter; - } + /** + * Validate fields before create or update object + * + * @param array $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validateLine($data) + { + $fichinter = array(); + foreach (Interventions::$FIELDSLINE as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $fichinter[$field] = $data[$field]; + } + return $fichinter; + } } diff --git a/htdocs/fourn/class/api_supplier_invoices.class.php b/htdocs/fourn/class/api_supplier_invoices.class.php index 36bcbd76aa7..247434be7a8 100644 --- a/htdocs/fourn/class/api_supplier_invoices.class.php +++ b/htdocs/fourn/class/api_supplier_invoices.class.php @@ -677,8 +677,8 @@ class SupplierInvoices extends DolibarrApi /** * Clean sensible object datas * - * @param Object $object Object to clean - * @return Object Object with cleaned properties + * @param Object $object Object to clean + * @return Object Object with cleaned properties */ protected function _cleanObjectDatas($object) { diff --git a/htdocs/fourn/class/api_supplier_orders.class.php b/htdocs/fourn/class/api_supplier_orders.class.php index 386d67ff7c7..254e577f2f2 100644 --- a/htdocs/fourn/class/api_supplier_orders.class.php +++ b/htdocs/fourn/class/api_supplier_orders.class.php @@ -339,8 +339,8 @@ class SupplierOrders extends DolibarrApi /** * Clean sensible object datas * - * @param Object $object Object to clean - * @return Object Object with cleaned properties + * @param Object $object Object to clean + * @return Object Object with cleaned properties */ protected function _cleanObjectDatas($object) { diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index c26966bc6e8..264e015298d 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -626,13 +626,13 @@ class ProductFournisseur extends Product $prodfourn->fourn_remise_percent = $record["remise_percent"]; $prodfourn->fourn_remise = $record["remise"]; $prodfourn->fourn_unitprice = $record["unitprice"]; - $prodfourn->fourn_charges = $record["charges"]; // deprecated + $prodfourn->fourn_charges = $record["charges"]; // deprecated $prodfourn->fourn_tva_tx = $record["tva_tx"]; - $prodfourn->fourn_id = $record["fourn_id"]; + $prodfourn->fourn_id = $record["fourn_id"]; $prodfourn->fourn_name = $record["supplier_name"]; $prodfourn->fk_availability = $record["fk_availability"]; - $prodfourn->delivery_time_days = $record["delivery_time_days"]; - $prodfourn->id = $prodid; + $prodfourn->delivery_time_days = $record["delivery_time_days"]; + $prodfourn->id = $prodid; $prodfourn->fourn_tva_npr = $record["info_bits"]; $prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"]; $prodfourn->supplier_reputation = $record["supplier_reputation"]; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index a632320a87e..af963952765 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -317,39 +317,39 @@ if (empty($reshook)) // payments conditions if ($action == 'setconditions' && $usercancreate) { - $object->fetch($id); - $object->cond_reglement_code = 0; // To clean property - $object->cond_reglement_id = 0; // To clean property + $object->fetch($id); + $object->cond_reglement_code = 0; // To clean property + $object->cond_reglement_id = 0; // To clean property - $error = 0; + $error = 0; - $db->begin(); + $db->begin(); - if (!$error) { - $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); - if ($result < 0) { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } - } + if (!$error) { + $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); + if ($result < 0) { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } + } - if (!$error) { - $old_date_echeance = $object->date_echeance; - $new_date_echeance = $object->calculate_date_lim_reglement(); - if ($new_date_echeance > $old_date_echeance) $object->date_echeance = $new_date_echeance; - if ($object->date_echeance < $object->date) $object->date_echeance = $object->date; - $result = $object->update($user); - if ($result < 0) { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } - } + if (!$error) { + $old_date_echeance = $object->date_echeance; + $new_date_echeance = $object->calculate_date_lim_reglement(); + if ($new_date_echeance > $old_date_echeance) $object->date_echeance = $new_date_echeance; + if ($object->date_echeance < $object->date) $object->date_echeance = $object->date; + $result = $object->update($user); + if ($result < 0) { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } + } - if ($error) { - $db->rollback(); - } else { - $db->commit(); - } + if ($error) { + $db->rollback(); + } else { + $db->commit(); + } } // Set incoterm @@ -379,11 +379,11 @@ if (empty($reshook)) $result = $object->setBankAccount(GETPOST('fk_account', 'int')); } - // transport mode - if ($action == 'settransportmode' && $user->rights->fournisseur->facture->creer) - { - $result = $object->setTransportMode(GETPOST('transport_mode_id', 'int')); - } + // transport mode + if ($action == 'settransportmode' && $user->rights->fournisseur->facture->creer) + { + $result = $object->setTransportMode(GETPOST('transport_mode_id', 'int')); + } // Set label elseif ($action == 'setlabel' && $usercancreate) @@ -2096,14 +2096,14 @@ if ($action == 'create') print ''; } - // Intracomm report - if (!empty($conf->intracommreport->enabled)) - { - $langs->loadLangs(array("intracommreport")); - print ''.$langs->trans('IntracommReportTransportMode').''; - $form->selectModeTransport(isset($_POST['transport_mode_id']) ? $_POST['transport_mode_id'] : $transport_mode_id, 'transport_mode_id'); - print ''; - } + // Intracomm report + if (!empty($conf->intracommreport->enabled)) + { + $langs->loadLangs(array("intracommreport")); + print ''.$langs->trans('IntracommReportTransportMode').''; + $form->selectModeTransport(isset($_POST['transport_mode_id']) ? $_POST['transport_mode_id'] : $transport_mode_id, 'transport_mode_id'); + print ''; + } // Public note print ''.$langs->trans('NotePublic').''; diff --git a/htdocs/holiday/class/holiday.class.php b/htdocs/holiday/class/holiday.class.php index d82c2b30037..acfa9cca3d7 100644 --- a/htdocs/holiday/class/holiday.class.php +++ b/htdocs/holiday/class/holiday.class.php @@ -2115,8 +2115,8 @@ class Holiday extends CommonObject if (empty($user->rights->expensereport->read_all)) { $userchildids = $user->getAllChildIds(1); - $sql.= " AND (h.fk_user IN (".join(',', $userchildids).")"; - $sql.= " OR h.fk_validator IN (".join(',', $userchildids)."))"; + $sql .= " AND (h.fk_user IN (".join(',', $userchildids).")"; + $sql .= " OR h.fk_validator IN (".join(',', $userchildids)."))"; } $resql = $this->db->query($sql); diff --git a/htdocs/install/upgrade.php b/htdocs/install/upgrade.php index aeca1b291e1..a7addd98547 100644 --- a/htdocs/install/upgrade.php +++ b/htdocs/install/upgrade.php @@ -104,106 +104,106 @@ $actiondone = 0; // Action to launch the migrate script if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ09'))) { - $actiondone = 1; + $actiondone = 1; - print '

Database '.$langs->trans("DatabaseMigration").'

'; + print '

Database '.$langs->trans("DatabaseMigration").'

'; - print ''; - $error = 0; + print '
'; + $error = 0; - // If password is encoded, we decode it - if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) - { - require_once $dolibarr_main_document_root.'/core/lib/security.lib.php'; - if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) - { - $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); - $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass); - $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted - } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); - } + // If password is encoded, we decode it + if (preg_match('/crypted:/i', $dolibarr_main_db_pass) || !empty($dolibarr_main_db_encrypted_pass)) + { + require_once $dolibarr_main_document_root.'/core/lib/security.lib.php'; + if (preg_match('/crypted:/i', $dolibarr_main_db_pass)) + { + $dolibarr_main_db_pass = preg_replace('/crypted:/i', '', $dolibarr_main_db_pass); + $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_pass); + $dolibarr_main_db_encrypted_pass = $dolibarr_main_db_pass; // We need to set this as it is used to know the password was initially crypted + } else $dolibarr_main_db_pass = dol_decode($dolibarr_main_db_encrypted_pass); + } - // $conf is already instancied inside inc.php - $conf->db->type = $dolibarr_main_db_type; - $conf->db->host = $dolibarr_main_db_host; - $conf->db->port = $dolibarr_main_db_port; - $conf->db->name = $dolibarr_main_db_name; - $conf->db->user = $dolibarr_main_db_user; - $conf->db->pass = $dolibarr_main_db_pass; + // $conf is already instancied inside inc.php + $conf->db->type = $dolibarr_main_db_type; + $conf->db->host = $dolibarr_main_db_host; + $conf->db->port = $dolibarr_main_db_port; + $conf->db->name = $dolibarr_main_db_name; + $conf->db->user = $dolibarr_main_db_user; + $conf->db->pass = $dolibarr_main_db_pass; - // Load type and crypt key - if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0; - $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; - if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = ''; - $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; + // Load type and crypt key + if (empty($dolibarr_main_db_encryption)) $dolibarr_main_db_encryption = 0; + $conf->db->dolibarr_main_db_encryption = $dolibarr_main_db_encryption; + if (empty($dolibarr_main_db_cryptkey)) $dolibarr_main_db_cryptkey = ''; + $conf->db->dolibarr_main_db_cryptkey = $dolibarr_main_db_cryptkey; - $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); + $db = getDoliDBInstance($conf->db->type, $conf->db->host, $conf->db->user, $conf->db->pass, $conf->db->name, $conf->db->port); - // Create the global $hookmanager object - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($db); + // Create the global $hookmanager object + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager = new HookManager($db); - if ($db->connected) - { - print ''."\n"; - dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerConnection").": $dolibarr_main_db_host ".$langs->transnoentities("OK")); - $ok = 1; - } else { - print "\n"; - dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name)); - $ok = 0; - } + if ($db->connected) + { + print ''."\n"; + dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerConnection").": $dolibarr_main_db_host ".$langs->transnoentities("OK")); + $ok = 1; + } else { + print "\n"; + dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name)); + $ok = 0; + } - if ($ok) - { - if ($db->database_selected) - { - print '\n"; - dolibarr_install_syslog("upgrade: Database connection successful: ".$dolibarr_main_db_name); - $ok = 1; - } else { - print "\n"; - dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name)); - $ok = 0; - } - } + if ($ok) + { + if ($db->database_selected) + { + print '\n"; + dolibarr_install_syslog("upgrade: Database connection successful: ".$dolibarr_main_db_name); + $ok = 1; + } else { + print "\n"; + dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name)); + $ok = 0; + } + } - // Affiche version - if ($ok) - { - $version = $db->getVersion(); - $versionarray = $db->getVersionArray(); - print ''; - print ''; - dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerVersion").": ".$version); - if ($db->type == 'mysqli' && function_exists('mysqli_get_charset')) - { - $tmparray = $db->db->get_charset(); - print ''; - print ''; - dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCharset").": ".$tmparray->charset); - print ''; - print ''; - dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCollation").": ".$tmparray->collation); - } + // Affiche version + if ($ok) + { + $version = $db->getVersion(); + $versionarray = $db->getVersionArray(); + print ''; + print ''; + dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ServerVersion").": ".$version); + if ($db->type == 'mysqli' && function_exists('mysqli_get_charset')) + { + $tmparray = $db->db->get_charset(); + print ''; + print ''; + dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCharset").": ".$tmparray->charset); + print ''; + print ''; + dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ClientCollation").": ".$tmparray->collation); + } - // Test database version requirement - $versionmindb = explode('.', $db::VERSIONMIN); - //print join('.',$versionarray).' - '.join('.',$versionmindb); - if (count($versionmindb) && count($versionarray) - && versioncompare($versionarray, $versionmindb) < 0) - { - // Warning: database version too low. - print "\n"; - dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb))); - $ok = 0; - } + // Test database version requirement + $versionmindb = explode('.', $db::VERSIONMIN); + //print join('.',$versionarray).' - '.join('.',$versionmindb); + if (count($versionmindb) && count($versionarray) + && versioncompare($versionarray, $versionmindb) < 0) + { + // Warning: database version too low. + print "\n"; + dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb))); + $ok = 0; + } - // Test database version is not forbidden for migration - if (empty($ignoredbversion)) - { + // Test database version is not forbidden for migration + if (empty($ignoredbversion)) + { $dbversion_disallowed = array( array('type'=>'mysql', 'version'=>array(5, 5, 40)), array('type'=>'mysqli', 'version'=>array(5, 5, 40)) //, @@ -217,196 +217,196 @@ if (!GETPOST('action', 'aZ09') || preg_match('/upgrade/i', GETPOST('action', 'aZ } foreach ($dbversion_disallowed as $dbversion_totest) { - //print $db->type.' - '.join('.',$versionarray).' - '.versioncompare($dbversion_totest['version'],$versionarray)."
\n"; - if ($dbversion_totest['type'] == $db->type - && (versioncompare($dbversion_totest['version'], $versionarray) == 0 || versioncompare($dbversion_totest['version'], $versionarray) <= -4 || versioncompare($dbversion_totest['version'], $versionarray) >= 4) - ) - { - // Warning: database version too low. - print '\n"; - dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion)); - $ok = 0; - break; - } + //print $db->type.' - '.join('.',$versionarray).' - '.versioncompare($dbversion_totest['version'],$versionarray)."
\n"; + if ($dbversion_totest['type'] == $db->type + && (versioncompare($dbversion_totest['version'], $versionarray) == 0 || versioncompare($dbversion_totest['version'], $versionarray) <= -4 || versioncompare($dbversion_totest['version'], $versionarray) >= 4) + ) + { + // Warning: database version too low. + print '\n"; + dolibarr_install_syslog("upgrade: ".$langs->transnoentities("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion)); + $ok = 0; + break; + } } - } - } + } + } - // Force l'affichage de la progression - if ($ok) - { - print ''; - flush(); - } + // Force l'affichage de la progression + if ($ok) + { + print ''; + flush(); + } /* * Remove deprecated indexes and constraints for Mysql */ - if ($ok && preg_match('/mysql/', $db->type)) - { - $versioncommande = array(4, 0, 0); - if (count($versioncommande) && count($versionarray) - && versioncompare($versioncommande, $versionarray) <= 0) // Si mysql >= 4.0 - { - dolibarr_install_syslog("Clean database from bad named constraints"); + if ($ok && preg_match('/mysql/', $db->type)) + { + $versioncommande = array(4, 0, 0); + if (count($versioncommande) && count($versionarray) + && versioncompare($versioncommande, $versionarray) <= 0) // Si mysql >= 4.0 + { + dolibarr_install_syslog("Clean database from bad named constraints"); - // Suppression vieilles contraintes sans noms et en doubles - // Les contraintes indesirables ont un nom qui commence par 0_ ou se termine par ibfk_999 - $listtables = array( - MAIN_DB_PREFIX.'adherent_options', - MAIN_DB_PREFIX.'bank_class', - MAIN_DB_PREFIX.'c_ecotaxe', - MAIN_DB_PREFIX.'c_methode_commande_fournisseur', // table renamed - MAIN_DB_PREFIX.'c_input_method' - ); + // Suppression vieilles contraintes sans noms et en doubles + // Les contraintes indesirables ont un nom qui commence par 0_ ou se termine par ibfk_999 + $listtables = array( + MAIN_DB_PREFIX.'adherent_options', + MAIN_DB_PREFIX.'bank_class', + MAIN_DB_PREFIX.'c_ecotaxe', + MAIN_DB_PREFIX.'c_methode_commande_fournisseur', // table renamed + MAIN_DB_PREFIX.'c_input_method' + ); - $listtables = $db->DDLListTables($conf->db->name, ''); - foreach ($listtables as $val) - { - // Database prefix filter - if (preg_match('/^'.MAIN_DB_PREFIX.'/', $val)) - { - //print "x".$val."
"; - $sql = "SHOW CREATE TABLE ".$val; - $resql = $db->query($sql); - if ($resql) - { - $values = $db->fetch_array($resql); - $i = 0; - $createsql = $values[1]; - while (preg_match('/CONSTRAINT `(0_[0-9a-zA-Z]+|[_0-9a-zA-Z]+_ibfk_[0-9]+)`/i', $createsql, $reg) && $i < 100) - { - $sqldrop = "ALTER TABLE ".$val." DROP FOREIGN KEY ".$reg[1]; - $resqldrop = $db->query($sqldrop); - if ($resqldrop) - { - print '\n"; - } - $createsql = preg_replace('/CONSTRAINT `'.$reg[1].'`/i', 'XXX', $createsql); - $i++; - } - $db->free($resql); - } else { - if ($db->lasterrno() != 'DB_ERROR_NOSUCHTABLE') - { - print '\n"; - } - } - } - } - } - } + $listtables = $db->DDLListTables($conf->db->name, ''); + foreach ($listtables as $val) + { + // Database prefix filter + if (preg_match('/^'.MAIN_DB_PREFIX.'/', $val)) + { + //print "x".$val."
"; + $sql = "SHOW CREATE TABLE ".$val; + $resql = $db->query($sql); + if ($resql) + { + $values = $db->fetch_array($resql); + $i = 0; + $createsql = $values[1]; + while (preg_match('/CONSTRAINT `(0_[0-9a-zA-Z]+|[_0-9a-zA-Z]+_ibfk_[0-9]+)`/i', $createsql, $reg) && $i < 100) + { + $sqldrop = "ALTER TABLE ".$val." DROP FOREIGN KEY ".$reg[1]; + $resqldrop = $db->query($sqldrop); + if ($resqldrop) + { + print '\n"; + } + $createsql = preg_replace('/CONSTRAINT `'.$reg[1].'`/i', 'XXX', $createsql); + $i++; + } + $db->free($resql); + } else { + if ($db->lasterrno() != 'DB_ERROR_NOSUCHTABLE') + { + print '\n"; + } + } + } + } + } + } - /* + /* * Load sql files */ - if ($ok) - { - $dir = "mysql/migration/"; // We use mysql migration scripts whatever is database driver + if ($ok) + { + $dir = "mysql/migration/"; // We use mysql migration scripts whatever is database driver if (!empty($dirmodule)) $dir = dol_buildpath('/'.$dirmodule.'/sql/', 0); dolibarr_install_syslog("Scan sql files for migration files in ".$dir); // Clean last part to exclude minor version x.y.z -> x.y - $newversionfrom = preg_replace('/(\.[0-9]+)$/i', '.0', $versionfrom); - $newversionto = preg_replace('/(\.[0-9]+)$/i', '.0', $versionto); + $newversionfrom = preg_replace('/(\.[0-9]+)$/i', '.0', $versionfrom); + $newversionto = preg_replace('/(\.[0-9]+)$/i', '.0', $versionto); - $filelist = array(); - $i = 0; - $ok = 0; - $from = '^'.$newversionfrom; - $to = $newversionto.'\.sql$'; + $filelist = array(); + $i = 0; + $ok = 0; + $from = '^'.$newversionfrom; + $to = $newversionto.'\.sql$'; - // Get files list - $filesindir = array(); - $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/\.sql$/i', $file)) $filesindir[] = $file; - } - sort($filesindir); - } else { - print '
'.$langs->trans("ErrorCanNotReadDir", $dir).'
'; - } + // Get files list + $filesindir = array(); + $handle = opendir($dir); + if (is_resource($handle)) + { + while (($file = readdir($handle)) !== false) + { + if (preg_match('/\.sql$/i', $file)) $filesindir[] = $file; + } + sort($filesindir); + } else { + print '
'.$langs->trans("ErrorCanNotReadDir", $dir).'
'; + } - // Define which file to run - foreach ($filesindir as $file) - { - if (preg_match('/'.$from.'/i', $file)) - { - $filelist[] = $file; - } elseif (preg_match('/'.$to.'/i', $file)) // First test may be false if we migrate from x.y.* to x.y.* - { - $filelist[] = $file; - } - } + // Define which file to run + foreach ($filesindir as $file) + { + if (preg_match('/'.$from.'/i', $file)) + { + $filelist[] = $file; + } elseif (preg_match('/'.$to.'/i', $file)) // First test may be false if we migrate from x.y.* to x.y.* + { + $filelist[] = $file; + } + } - if (count($filelist) == 0) - { - print '
'.$langs->trans("ErrorNoMigrationFilesFoundForParameters").'
'; - } else { + if (count($filelist) == 0) + { + print '
'.$langs->trans("ErrorNoMigrationFilesFoundForParameters").'
'; + } else { $listoffileprocessed = array(); // Protection to avoid to process twice the same file - // Loop on each migrate files - foreach ($filelist as $file) - { - if (in_array($dir.$file, $listoffileprocessed)) continue; + // Loop on each migrate files + foreach ($filelist as $file) + { + if (in_array($dir.$file, $listoffileprocessed)) continue; - print ''; - print ''."\n"; + print ''; + print ''."\n"; - // Run sql script - $ok = run_sql($dir.$file, 0, '', 1); - $listoffileprocessed[$dir.$file] = $dir.$file; + // Run sql script + $ok = run_sql($dir.$file, 0, '', 1); + $listoffileprocessed[$dir.$file] = $dir.$file; - // Scan if there is migration scripts that depends of Dolibarr version - // for modules htdocs/module/sql or htdocs/custom/module/sql (files called "dolibarr_x.y.z-a.b.c.sql") - $modulesfile = array(); - foreach ($conf->file->dol_document_root as $type => $dirroot) - { - $handlemodule = @opendir($dirroot); // $dirroot may be '..' - if (is_resource($handlemodule)) - { - while (($filemodule = readdir($handlemodule)) !== false) - { - if (!preg_match('/\./', $filemodule) && is_dir($dirroot.'/'.$filemodule.'/sql')) // We exclude filemodule that contains . (are not directories) and are not directories. - { - //print "Scan for ".$dirroot . '/' . $filemodule . '/sql/'.$file; - if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file)) - { - $modulesfile[$dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file] = '/'.$filemodule.'/sql/dolibarr_'.$file; - } - } - } - closedir($handlemodule); - } - } + // Scan if there is migration scripts that depends of Dolibarr version + // for modules htdocs/module/sql or htdocs/custom/module/sql (files called "dolibarr_x.y.z-a.b.c.sql") + $modulesfile = array(); + foreach ($conf->file->dol_document_root as $type => $dirroot) + { + $handlemodule = @opendir($dirroot); // $dirroot may be '..' + if (is_resource($handlemodule)) + { + while (($filemodule = readdir($handlemodule)) !== false) + { + if (!preg_match('/\./', $filemodule) && is_dir($dirroot.'/'.$filemodule.'/sql')) // We exclude filemodule that contains . (are not directories) and are not directories. + { + //print "Scan for ".$dirroot . '/' . $filemodule . '/sql/'.$file; + if (is_file($dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file)) + { + $modulesfile[$dirroot.'/'.$filemodule.'/sql/dolibarr_'.$file] = '/'.$filemodule.'/sql/dolibarr_'.$file; + } + } + } + closedir($handlemodule); + } + } - foreach ($modulesfile as $modulefilelong => $modulefileshort) - { - if (in_array($modulefilelong, $listoffileprocessed)) continue; + foreach ($modulesfile as $modulefilelong => $modulefileshort) + { + if (in_array($modulefilelong, $listoffileprocessed)) continue; - print ''; - print ''."\n"; + print ''; + print ''."\n"; - // Run sql script - $okmodule = run_sql($modulefilelong, 0, '', 1); // Note: Result of migration of external module should not decide if we continue migration of Dolibarr or not. - $listoffileprocessed[$modulefilelong] = $modulefilelong; - } - } + // Run sql script + $okmodule = run_sql($modulefilelong, 0, '', 1); // Note: Result of migration of external module should not decide if we continue migration of Dolibarr or not. + $listoffileprocessed[$modulefilelong] = $modulefilelong; + } + } } - } + } - print '
'; - print $langs->trans("ServerConnection")." : ".$dolibarr_main_db_host.''.$langs->trans("OK").'
".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).''.$langs->transnoentities("Error")."
'; + print $langs->trans("ServerConnection")." : ".$dolibarr_main_db_host.''.$langs->trans("OK").'
".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).''.$langs->transnoentities("Error")."
'; - print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name.''.$langs->trans("OK")."
".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).''.$langs->trans("Error")."
'; + print $langs->trans("DatabaseConnection")." : ".$dolibarr_main_db_name.''.$langs->trans("OK")."
".$langs->trans("ErrorFailedToConnectToDatabase", $dolibarr_main_db_name).''.$langs->trans("Error")."
'.$langs->trans("ServerVersion").''.$version.'
'.$langs->trans("ClientCharset").''.$tmparray->charset.'
'.$langs->trans("ClientSortingCharset").''.$tmparray->collation.'
'.$langs->trans("ServerVersion").''.$version.'
'.$langs->trans("ClientCharset").''.$tmparray->charset.'
'.$langs->trans("ClientSortingCharset").''.$tmparray->collation.'
".$langs->trans("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb))."".$langs->trans("Error")."
".$langs->trans("ErrorDatabaseVersionTooLow", join('.', $versionarray), join('.', $versionmindb))."".$langs->trans("Error")."
'.$langs->trans("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion)."
".$langs->trans("Error")."
'.$langs->trans("ErrorDatabaseVersionForbiddenForMigration", join('.', $versionarray), $listofforbiddenversion)."
".$langs->trans("Error")."
'.$langs->trans("PleaseBePatient").'
'.$langs->trans("PleaseBePatient").'
'.$sqldrop.";
'.$sql.' : '.$db->lasterror()."
'.$sqldrop.";
'.$sql.' : '.$db->lasterror()."

'.$langs->trans("ChoosedMigrateScript").''.$file.'

'.$langs->trans("ChoosedMigrateScript").''.$file.'

'.$langs->trans("ChoosedMigrateScript").' (external modules)'.$modulefileshort.'

'.$langs->trans("ChoosedMigrateScript").' (external modules)'.$modulefileshort.'
'; + print ''; - if ($db->connected) $db->close(); + if ($db->connected) $db->close(); } if (empty($actiondone)) { - print '
'.$langs->trans("ErrorWrongParameters").'
'; + print '
'.$langs->trans("ErrorWrongParameters").'
'; } $ret = 0; diff --git a/htdocs/intracommreport/admin/intracommreport.php b/htdocs/intracommreport/admin/intracommreport.php index fed49f01868..c9968c14215 100644 --- a/htdocs/intracommreport/admin/intracommreport.php +++ b/htdocs/intracommreport/admin/intracommreport.php @@ -28,31 +28,31 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/intracommreport.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; // Load translation files required by the page -$langs->loadLangs(array("admin","intracommreport")); +$langs->loadLangs(array("admin", "intracommreport")); -if (! $user->admin) accessforbidden(); +if (!$user->admin) accessforbidden(); $action = GETPOST('action', 'aZ09'); // Parameters INTRACOMMREPORT_* and others -$list_DEB = array ( +$list_DEB = array( 'INTRACOMMREPORT_NUM_AGREMENT', ); -$list_DES = array ( +$list_DES = array( 'INTRACOMMREPORT_NUM_DECLARATION', ); if ($action == 'update') { $error = 0; - if (! $error) + if (!$error) { foreach ($list_DEB as $constname) { $constvalue = GETPOST($constname, 'alpha'); - if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { $error++; } } @@ -61,7 +61,7 @@ if ($action == 'update') { { $constvalue = GETPOST($constname, 'alpha'); - if (! dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { $error++; } } @@ -77,7 +77,7 @@ if ($action == 'update') { } } - if (! $error) { + if (!$error) { setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } } @@ -119,7 +119,7 @@ foreach ($list_DEB as $key) print ''.$label.''; // Value print ''; - print ''; + print ''; print ''; print ''; @@ -185,7 +185,7 @@ foreach ($list_DES as $key) print ''.$label.''; // Value print ''; - print ''; + print ''; print ''; print ''; diff --git a/htdocs/intracommreport/card.php b/htdocs/intracommreport/card.php index 3655ce9d523..25099a9bd54 100644 --- a/htdocs/intracommreport/card.php +++ b/htdocs/intracommreport/card.php @@ -45,10 +45,10 @@ $backtopage = GETPOST('backtopage', 'alpha'); if ($user->rights->intracommreport->delete && $action == 'confirm_delete' && $confirm == 'yes') { - $result=$object->delete($id, $user); + $result = $object->delete($id, $user); if ($result > 0) { - if (! empty($backtopage)) + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; @@ -59,12 +59,12 @@ if ($user->rights->intracommreport->delete && $action == 'confirm_delete' && $co } } else { - $errmesg=$object->error; + $errmesg = $object->error; } } if ($action == 'add' && $user->rights->intracommreport->write) { - $object->label = trim($label); + $object->label = trim($label); $object->type = trim($type); $object->type_declaration = (int) $statut; $object->subscription = (int) $subscription; @@ -90,9 +90,9 @@ if ($action == 'add' && $user->rights->intracommreport->write) { } } - if (! $error) + if (!$error) { - $id=$object->create($user); + $id = $object->create($user); if ($id > 0) { header("Location: ".$_SERVER["PHP_SELF"]); @@ -134,7 +134,7 @@ if ($action == 'create') $declaration["deb"] = $langs->trans("DEB"); $declaration["des"] = $langs->trans("DES"); print ''.$langs->trans("Declaration")."\n"; - print $form->selectarray("declaration", $declaration, GETPOST('declaration', 'alpha')?GETPOST('declaration', 'alpha'):$object->declaration, 0); + print $form->selectarray("declaration", $declaration, GETPOST('declaration', 'alpha') ?GETPOST('declaration', 'alpha') : $object->declaration, 0); print "\n"; // Analysis period @@ -152,7 +152,7 @@ if ($action == 'create') $typeOfDeclaration["introduction"] = $langs->trans("Introduction"); $typeOfDeclaration["expedition"] = $langs->trans("Expedition"); print ''.$langs->trans("TypeOfDeclaration")."\n"; - print $form->selectarray("type_declaration", $typeOfDeclaration, GETPOST('type_declaration', 'alpha')?GETPOST('type_declaration', 'alpha'):$object->type_declaration, 0); + print $form->selectarray("type_declaration", $typeOfDeclaration, GETPOST('type_declaration', 'alpha') ?GETPOST('type_declaration', 'alpha') : $object->type_declaration, 0); print "\n"; print ''; @@ -160,7 +160,7 @@ if ($action == 'create') print dol_get_fiche_end(); print '
'; - print '     '; + print '     '; print '
'; print ''; @@ -195,11 +195,11 @@ if ($id > 0 && $action != 'edit') { 'value' => ($backtopage != '1' ? $backtopage : $_SERVER["HTTP_REFERER"]) ); } - print $form->formconfirm("card.php?rowid=" . $id, $langs->trans("DeleteReport"), + print $form->formconfirm("card.php?rowid=".$id, $langs->trans("DeleteReport"), $langs->trans("ConfirmDeleteReport"), "confirm_delete", $formquestion, 'no', 1); } - $linkback = '' . $langs->trans("BackToList") . ''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'rowid', $linkback); @@ -210,14 +210,14 @@ if ($id > 0 && $action != 'edit') { print ''; // Type - print '\n"; + print '\n"; // Analysis Period - print ''; + print ''; print ''; // Type of Declaration - print ''; + print ''; print ''; print "
' . $langs->trans("Type") . '' . $object->declaration . "
'.$langs->trans("Type").''.$object->declaration."
' . $langs->trans("AnalysisPeriod") . '' . $object->period . '
'.$langs->trans("AnalysisPeriod").''.$object->period.'
' . $langs->trans("TypeOfDeclaration") . '' . $object->type_declaration . '
'.$langs->trans("TypeOfDeclaration").''.$object->type_declaration.'
\n"; diff --git a/htdocs/intracommreport/class/intracommreport.class.php b/htdocs/intracommreport/class/intracommreport.class.php index 3b0c47f9749..dc12427ec33 100644 --- a/htdocs/intracommreport/class/intracommreport.class.php +++ b/htdocs/intracommreport/class/intracommreport.class.php @@ -32,17 +32,17 @@ class IntracommReport extends CommonObject /** * @var string ID to identify managed object */ - public $element='intracommreport'; + public $element = 'intracommreport'; /** * @var string Name of table without prefix where object is stored */ - public $table_element='intracommreport'; + public $table_element = 'intracommreport'; /** * @var int Field with ID of parent key if this field has a parent */ - public $fk_element='fk_intracommreport'; + public $fk_element = 'fk_intracommreport'; /** * @var string declaration number @@ -422,7 +422,7 @@ class IntracommReport extends CommonObject header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); - header('Content-Length: ' . filesize($fname)); + header('Content-Length: '.filesize($fname)); readfile($fname); exit; } diff --git a/htdocs/intracommreport/list.php b/htdocs/intracommreport/list.php index 3a33debc5f4..a8703b7407d 100644 --- a/htdocs/intracommreport/list.php +++ b/htdocs/intracommreport/list.php @@ -102,13 +102,13 @@ $fieldstosearchall = array( "i.note"=>"Note", ); -$isInEEC=isInEEC($mysoc); +$isInEEC = isInEEC($mysoc); // Definition of fields for lists -$arrayfields=array( +$arrayfields = array( 'i.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), 'i.label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), - 'i.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(! empty($conf->produit->enabled) && ! empty($conf->service->enabled))), + 'i.fk_product_type'=>array('label'=>$langs->trans("Type"), 'checked'=>0, 'enabled'=>(!empty($conf->produit->enabled) && !empty($conf->service->enabled))), ); /* // Extra fields @@ -145,19 +145,19 @@ if (empty($reshook)) // 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 { - $sall=""; - $search_ref=""; - $search_label=""; + $sall = ""; + $search_ref = ""; + $search_label = ""; //$search_type=''; // There is 2 types of list: a list of product and a list of services. No list with both. So when we clear search criteria, we must keep the filter on type. $show_childproducts = ''; - $search_array_options=array(); + $search_array_options = array(); } // Mass actions - $objectclass='Product'; - if ((string) $search_type == '1') { $objectlabel='Services'; } - if ((string) $search_type == '0') { $objectlabel='Products'; } + $objectclass = 'Product'; + if ((string) $search_type == '1') { $objectlabel = 'Services'; } + if ((string) $search_type == '0') { $objectlabel = 'Products'; } $permtoread = $user->rights->produit->lire; $permtodelete = $user->rights->produit->supprimer; @@ -181,22 +181,22 @@ if (! empty($extrafields->attributes[$object->table_element]['label'])) { } */ // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= ' FROM '.MAIN_DB_PREFIX.'intracommreport as i'; +$sql .= ' FROM '.MAIN_DB_PREFIX.'intracommreport as i'; // if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."intracommreport_extrafields as ef on (i.rowid = ef.fk_object)"; -$sql.= ' WHERE i.entity IN ('.getEntity('intracommreport').')'; +$sql .= ' WHERE i.entity IN ('.getEntity('intracommreport').')'; if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); // if the type is not 1, we show all products (type = 0,2,3) if (dol_strlen($search_type) && $search_type != '-1') { - if ($search_type == 1) $sql.= " AND i.type = 1"; - else $sql.= " AND i.type = 0"; + if ($search_type == 1) $sql .= " AND i.type = 1"; + else $sql .= " AND i.type = 0"; } /* @@ -253,40 +253,40 @@ if ($resql) { $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected = is_array($toselect) ? $toselect : array(); - $helpurl='EN:Module_IntracommReport|FR:Module_ProDouane'; + $helpurl = 'EN:Module_IntracommReport|FR:Module_ProDouane'; llxHeader('', $title, $helpurl, ''); // Displays product removal confirmation - if (GETPOST('delreport')) { + if (GETPOST('delreport')) { setEventMessages($langs->trans("IntracommReportDeleted", GETPOST('delreport')), null, 'mesgs'); } - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($sall) $param.="&sall=".urlencode($sall); - if ($search_ref) $param="&search_ref=".urlencode($search_ref); - if ($search_label) $param.="&search_label=".urlencode($search_label); + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($sall) $param .= "&sall=".urlencode($sall); + if ($search_ref) $param = "&search_ref=".urlencode($search_ref); + if ($search_label) $param .= "&search_label=".urlencode($search_label); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; // List of mass actions available - $arrayofmassactions = array( + $arrayofmassactions = array( 'generate_doc'=>$langs->trans("ReGeneratePDF"), //'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->intracommreport->delete) $arrayofmassactions['predelete']="".$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if ($user->rights->intracommreport->delete) $arrayofmassactions['predelete'] = "".$langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - $newcardbutton=''; + $newcardbutton = ''; if ($user->rights->intracommreport->write) { - $newcardbutton.= dolGetButtonTitle($langs->trans("NewDeclaration"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/intracommreport/card.php?action=create&type='.$type); + $newcardbutton .= dolGetButtonTitle($langs->trans("NewDeclaration"), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/intracommreport/card.php?action=create&type='.$type); } print '
'; @@ -302,22 +302,22 @@ if ($resql) print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'title_products.png', 0, $newcardbutton, '', $limit); - $topicmail="Information"; - $modelmail="product"; - $objecttmp=new IntracommReport($db); - $trackid='prod'.$object->id; + $topicmail = "Information"; + $modelmail = "product"; + $objecttmp = new IntracommReport($db); + $trackid = 'prod'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; if ($sall) { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter.=$hookmanager->resPrint; - else $moreforfilter=$hookmanager->resPrint; + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; + else $moreforfilter = $hookmanager->resPrint; if ($moreforfilter) { @@ -326,22 +326,22 @@ if ($resql) print ''; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); print '
'; - print ''."\n"; + print '
'."\n"; // Lines with input filters print ''; - if (! empty($arrayfields['i.ref']['checked'])) + if (!empty($arrayfields['i.ref']['checked'])) { print ''; } - if (! empty($arrayfields['i.label']['checked'])) + if (!empty($arrayfields['i.label']['checked'])) { print ''; } - if (! empty($arrayfields['i.fk_product_type']['checked'])) + if (!empty($arrayfields['i.fk_product_type']['checked'])) { print ''; } @@ -370,36 +370,36 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; */ // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (! empty($arrayfields['i.datec']['checked'])) + if (!empty($arrayfields['i.datec']['checked'])) { print ''; } // Date modification - if (! empty($arrayfields['i.tms']['checked'])) + if (!empty($arrayfields['i.tms']['checked'])) { print ''; } print ''; print ''; print ''; - if (! empty($arrayfields['i.ref']['checked'])) { + if (!empty($arrayfields['i.ref']['checked'])) { print_liste_field_titre($arrayfields['i.ref']['label'], $_SERVER["PHP_SELF"], "i.ref", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['i.label']['checked'])) { + if (!empty($arrayfields['i.label']['checked'])) { print_liste_field_titre($arrayfields['i.label']['label'], $_SERVER["PHP_SELF"], "i.label", "", $param, "", $sortfield, $sortorder); } - if (! empty($arrayfields['i.fk_product_type']['checked'])) { + if (!empty($arrayfields['i.fk_product_type']['checked'])) { print_liste_field_titre($arrayfields['i.fk_product_type']['label'], $_SERVER["PHP_SELF"], "i.fk_product_type", "", $param, "", $sortfield, $sortorder); } @@ -408,13 +408,13 @@ if ($resql) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; */ // Hook fields - $parameters=array('arrayfields'=>$arrayfields,'param'=>$param,'sortfield'=>$sortfield,'sortorder'=>$sortorder); - $reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); + $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (! empty($arrayfields['i.datec']['checked'])) { + if (!empty($arrayfields['i.datec']['checked'])) { print_liste_field_titre($arrayfields['i.datec']['label'], $_SERVER["PHP_SELF"], "i.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } - if (! empty($arrayfields['i.tms']['checked'])) { + if (!empty($arrayfields['i.tms']['checked'])) { print_liste_field_titre($arrayfields['i.tms']['label'], $_SERVER["PHP_SELF"], "i.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); } @@ -425,7 +425,7 @@ if ($resql) $intracommreport_static = new IntracommReport($db); $i = 0; - $totalarray=array(); + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); @@ -443,35 +443,35 @@ if ($resql) print ''; // Ref - if (! empty($arrayfields['i.ref']['checked'])) + if (!empty($arrayfields['i.ref']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Label - if (! empty($arrayfields['i.label']['checked'])) + if (!empty($arrayfields['i.label']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Type - if (! empty($arrayfields['i.fk_product_type']['checked'])) + if (!empty($arrayfields['i.fk_product_type']['checked'])) { print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Action print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print "\n"; $i++; diff --git a/htdocs/loan/class/loanschedule.class.php b/htdocs/loan/class/loanschedule.class.php index fccb87768c2..50339359a9d 100644 --- a/htdocs/loan/class/loanschedule.class.php +++ b/htdocs/loan/class/loanschedule.class.php @@ -203,28 +203,28 @@ class LoanSchedule extends CommonObject { global $langs; $sql = "SELECT"; - $sql.= " t.rowid,"; - $sql.= " t.fk_loan,"; - $sql.= " t.datec,"; - $sql.= " t.tms,"; - $sql.= " t.datep,"; - $sql.= " t.amount_capital,"; - $sql.= " t.amount_insurance,"; - $sql.= " t.amount_interest,"; - $sql.= " t.fk_typepayment,"; - $sql.= " t.num_payment,"; - $sql.= " t.note_private,"; - $sql.= " t.note_public,"; - $sql.= " t.fk_bank,"; - $sql.= " t.fk_payment_loan,"; - $sql.= " t.fk_user_creat,"; - $sql.= " t.fk_user_modif,"; - $sql.= " pt.code as type_code, pt.libelle as type_label,"; - $sql.= ' b.fk_account'; - $sql.= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; - $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id"; - $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; - $sql.= " WHERE t.rowid = ".$id; + $sql .= " t.rowid,"; + $sql .= " t.fk_loan,"; + $sql .= " t.datec,"; + $sql .= " t.tms,"; + $sql .= " t.datep,"; + $sql .= " t.amount_capital,"; + $sql .= " t.amount_insurance,"; + $sql .= " t.amount_interest,"; + $sql .= " t.fk_typepayment,"; + $sql .= " t.num_payment,"; + $sql .= " t.note_private,"; + $sql .= " t.note_public,"; + $sql .= " t.fk_bank,"; + $sql .= " t.fk_payment_loan,"; + $sql .= " t.fk_user_creat,"; + $sql .= " t.fk_user_modif,"; + $sql .= " pt.code as type_code, pt.libelle as type_label,"; + $sql .= ' b.fk_account'; + $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id"; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid'; + $sql .= " WHERE t.rowid = ".$id; dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); diff --git a/htdocs/loan/payment/payment.php b/htdocs/loan/payment/payment.php index b94bdf344eb..2638d336eb0 100644 --- a/htdocs/loan/payment/payment.php +++ b/htdocs/loan/payment/payment.php @@ -125,7 +125,7 @@ if ($action == 'add_payment') if (!empty($line)) $pay_amount_interest = $line->amount_interest; else $pay_amount_interest = price2num(GETPOST('amount_interest')); $remaindertopay = price2num(GETPOST('remaindertopay')); - $amount = $pay_amount_capital + $pay_amount_insurance + $pay_amount_interest; + $amount = $pay_amount_capital + $pay_amount_insurance + $pay_amount_interest; // This term is allready paid if (!empty($line) && !empty($line->fk_bank)) @@ -184,7 +184,7 @@ if ($action == 'add_payment') } // Update loan schedule with payment value - if (! $error && !empty($line)) + if (!$error && !empty($line)) { // If payment values are modified, recalculate schedule if (($line->amount_capital <> $pay_amount_capital) || ($line->amount_insurance <> $pay_amount_insurance) || ($line->amount_interest <> $pay_amount_interest)) @@ -195,14 +195,14 @@ if ($action == 'add_payment') // Update fk_bank for current line if ($k == $echance) { - $ls->lines[$k-1]->fk_bank = $payment->fk_bank; - $ls->lines[$k-1]->fk_payment_loan = $payment->id; + $ls->lines[$k - 1]->fk_bank = $payment->fk_bank; + $ls->lines[$k - 1]->fk_payment_loan = $payment->id; } - $ls->lines[$k-1]->amount_capital = $v['mens'] - $v['interet']; - $ls->lines[$k-1]->amount_interest = $v['interet']; - $ls->lines[$k-1]->tms = dol_now(); - $ls->lines[$k-1]->fk_user_modif = $user->id; - $result = $ls->lines[$k-1]->update($user, 0); + $ls->lines[$k - 1]->amount_capital = $v['mens'] - $v['interet']; + $ls->lines[$k - 1]->amount_interest = $v['interet']; + $ls->lines[$k - 1]->tms = dol_now(); + $ls->lines[$k - 1]->fk_user_modif = $user->id; + $result = $ls->lines[$k - 1]->update($user, 0); if ($result < 1) { setEventMessages(null, $ls->errors, 'errors'); @@ -300,7 +300,7 @@ if ($action == 'create') print '
'; print ''; print ''; print ''; @@ -357,10 +357,10 @@ if ($resql) print ''; - $array=array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); + $array = array('-1'=>' ', '0'=>$langs->trans('Product'), '1'=>$langs->trans('Service')); print $form->selectarray('search_type', $array, $search_type); print ''; print ''; print ''; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; print $intracommreport_static->getNomUrl(1); print "'.dol_trunc($obj->label, 80).''.$obj->fk_product_type.''; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; } print '
'.$langs->trans("Date").''; if (empty($datepaid)) - if (empty($ts_temppaid)) $datepayment = empty($conf->global->MAIN_AUTOFILL_DATE)?-1:dol_now(); + if (empty($ts_temppaid)) $datepayment = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : dol_now(); else $datepayment = $ts_temppaid; else $datepayment = $datepaid; print $form->selectDate($datepayment, '', '', '', '', "add_payment", 1, 1); @@ -367,7 +367,7 @@ if ($action == 'create') print ''; if ($sumpaid < $loan->capital) { - print $langs->trans("LoanCapital") .': '; + print $langs->trans("LoanCapital").': '; } else { print '-'; diff --git a/htdocs/loan/schedule.php b/htdocs/loan/schedule.php index a77f378219a..5e27a48fa02 100644 --- a/htdocs/loan/schedule.php +++ b/htdocs/loan/schedule.php @@ -114,7 +114,7 @@ if ($action == 'updateecheancier' && empty($pay_without_schedule)) { break; } - $echeances->lines[$i-1] = $new_echeance; + $echeances->lines[$i - 1] = $new_echeance; $i++; } if ($result > 0) $db->commit(); diff --git a/htdocs/margin/agentMargins.php b/htdocs/margin/agentMargins.php index b8069da7f8b..9c8ff72681b 100644 --- a/htdocs/margin/agentMargins.php +++ b/htdocs/margin/agentMargins.php @@ -61,7 +61,7 @@ $enddatemonth = GETPOST('enddatemonth', 'int'); $enddateyear = GETPOST('enddateyear', 'int'); if (!empty($startdatemonth)) - $startdate = dol_mktime(0, 0, 0, $startdatemonth, $startdateday, $startdateyear); + $startdate = dol_mktime(0, 0, 0, $startdatemonth, $startdateday, $startdateyear); if (!empty($enddatemonth)) $enddate = dol_mktime(23, 59, 59, $enddatemonth, $enddateday, $enddateyear); diff --git a/htdocs/margin/tabs/thirdpartyMargins.php b/htdocs/margin/tabs/thirdpartyMargins.php index edd1ca207e5..683bc433c29 100644 --- a/htdocs/margin/tabs/thirdpartyMargins.php +++ b/htdocs/margin/tabs/thirdpartyMargins.php @@ -76,190 +76,190 @@ llxHeader('', $title, $help_url); if ($socid > 0) { - $object = new Societe($db); - $object->fetch($socid); + $object = new Societe($db); + $object->fetch($socid); - /* + /* * Affichage onglets */ - $head = societe_prepare_head($object); + $head = societe_prepare_head($object); - print dol_get_fiche_head($head, 'margin', $langs->trans("ThirdParty"), -1, 'company'); + print dol_get_fiche_head($head, 'margin', $langs->trans("ThirdParty"), -1, 'company'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom'); + dol_banner_tab($object, 'socid', $linkback, ($user->socid ? 0 : 1), 'rowid', 'nom'); - print '
'; + print '
'; - print '
'; - print ''; + print '
'; + print '
'; - if ($object->client) - { - print ''; - } + if ($object->client) + { + print ''; + } - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) - { - print ''; - } + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $object->fournisseur && !empty($user->rights->fournisseur->lire)) + { + print ''; + } - // Total Margin - print ''; + // Total Margin + print ''; - // Margin Rate - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { - print ''; - } + // Margin Rate + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { + print ''; + } - // Mark Rate - if (!empty($conf->global->DISPLAY_MARK_RATES)) { - print ''; - } + // Mark Rate + if (!empty($conf->global->DISPLAY_MARK_RATES)) { + print ''; + } - print "
'; - print $langs->trans('CustomerCode').''; - print $object->code_client; - if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; - print '
'; + print $langs->trans('CustomerCode').''; + print $object->code_client; + if ($object->check_codeclient() <> 0) print ' ('.$langs->trans("WrongCustomerCode").')'; + print '
'; - print $langs->trans('SupplierCode').''; - print $object->code_fournisseur; - if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").')'; - print '
'; + print $langs->trans('SupplierCode').''; + print $object->code_fournisseur; + if ($object->check_codefournisseur() <> 0) print ' ('.$langs->trans("WrongSupplierCode").')'; + print '
'.$langs->trans("TotalMargin").''; - print ''; // set by jquery (see below) - print '
'.$langs->trans("TotalMargin").''; + print ''; // set by jquery (see below) + print '
'.$langs->trans("MarginRate").''; - print ''; // set by jquery (see below) - print '
'.$langs->trans("MarginRate").''; + print ''; // set by jquery (see below) + print '
'.$langs->trans("MarkRate").''; - print ''; // set by jquery (see below) - print '
'.$langs->trans("MarkRate").''; + print ''; // set by jquery (see below) + print '
"; + print "
"; - print '
'; - print '
'; + print ''; + print '
'; - print dol_get_fiche_end(); + print dol_get_fiche_end(); - print '
'; + print '
'; - $sql = "SELECT distinct s.nom, s.rowid as socid, s.code_client,"; - $sql .= " f.rowid as facid, f.ref, f.total as total_ht,"; - $sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,"; - $sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive - $sql .= " sum(d.qty * d.buy_price_ht * (d.situation_percent / 100)) as buying_price,"; // always positive - $sql .= " sum(abs(d.total_ht) - (d.buy_price_ht * d.qty * (d.situation_percent / 100))) as marge"; // always positive - $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - $sql .= ", ".MAIN_DB_PREFIX."facture as f"; - $sql .= ", ".MAIN_DB_PREFIX."facturedet as d"; - $sql .= " WHERE f.fk_soc = s.rowid"; - $sql .= " AND f.fk_statut > 0"; - $sql .= " AND f.entity IN (".getEntity('invoice').")"; - $sql .= " AND d.fk_facture = f.rowid"; - $sql .= " AND f.fk_soc = $socid"; - $sql .= " AND d.buy_price_ht IS NOT NULL"; - if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0"; - $sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type"; - $sql .= $db->order($sortfield, $sortorder); - // TODO: calculate total to display then restore pagination - //$sql.= $db->plimit($conf->liste_limit +1, $offset); + $sql = "SELECT distinct s.nom, s.rowid as socid, s.code_client,"; + $sql .= " f.rowid as facid, f.ref, f.total as total_ht,"; + $sql .= " f.datef, f.paye, f.fk_statut as statut, f.type,"; + $sql .= " sum(d.total_ht) as selling_price,"; // may be negative or positive + $sql .= " sum(d.qty * d.buy_price_ht * (d.situation_percent / 100)) as buying_price,"; // always positive + $sql .= " sum(abs(d.total_ht) - (d.buy_price_ht * d.qty * (d.situation_percent / 100))) as marge"; // always positive + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; + $sql .= ", ".MAIN_DB_PREFIX."facture as f"; + $sql .= ", ".MAIN_DB_PREFIX."facturedet as d"; + $sql .= " WHERE f.fk_soc = s.rowid"; + $sql .= " AND f.fk_statut > 0"; + $sql .= " AND f.entity IN (".getEntity('invoice').")"; + $sql .= " AND d.fk_facture = f.rowid"; + $sql .= " AND f.fk_soc = $socid"; + $sql .= " AND d.buy_price_ht IS NOT NULL"; + if (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1) $sql .= " AND d.buy_price_ht <> 0"; + $sql .= " GROUP BY s.nom, s.rowid, s.code_client, f.rowid, f.ref, f.total, f.datef, f.paye, f.fk_statut, f.type"; + $sql .= $db->order($sortfield, $sortorder); + // TODO: calculate total to display then restore pagination + //$sql.= $db->plimit($conf->liste_limit +1, $offset); - dol_syslog('margin:tabs:thirdpartyMargins.php', LOG_DEBUG); - $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); + dol_syslog('margin:tabs:thirdpartyMargins.php', LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); - print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&socid=".$object->id, $sortfield, $sortorder, '', $num, $num, ''); + print_barre_liste($langs->trans("MarginDetails"), $page, $_SERVER["PHP_SELF"], "&socid=".$object->id, $sortfield, $sortorder, '', $num, $num, ''); - $i = 0; - print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table - print ""; + $i = 0; + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table + print "
"; - print ''; - print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder); - print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'center '); - print_liste_field_titre("SoldAmount", $_SERVER["PHP_SELF"], "selling_price", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); - print_liste_field_titre("PurchasedAmount", $_SERVER["PHP_SELF"], "buying_price", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); - print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) - print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); - if (!empty($conf->global->DISPLAY_MARK_RATES)) - print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); - print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); - print "\n"; + print ''; + print_liste_field_titre("Invoice", $_SERVER["PHP_SELF"], "f.ref", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder); + print_liste_field_titre("DateInvoice", $_SERVER["PHP_SELF"], "f.datef", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'center '); + print_liste_field_titre("SoldAmount", $_SERVER["PHP_SELF"], "selling_price", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); + print_liste_field_titre("PurchasedAmount", $_SERVER["PHP_SELF"], "buying_price", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); + print_liste_field_titre("Margin", $_SERVER["PHP_SELF"], "marge", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + print_liste_field_titre("MarginRate", $_SERVER["PHP_SELF"], "", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); + if (!empty($conf->global->DISPLAY_MARK_RATES)) + print_liste_field_titre("MarkRate", $_SERVER["PHP_SELF"], "", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); + print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "f.paye,f.fk_statut", "", "&socid=".$_REQUEST["socid"], '', $sortfield, $sortorder, 'right '); + print "\n"; - $cumul_achat = 0; - $cumul_vente = 0; + $cumul_achat = 0; + $cumul_vente = 0; - if ($num > 0) - { - while ($i < $num /*&& $i < $conf->liste_limit*/) - { - $objp = $db->fetch_object($result); + if ($num > 0) + { + while ($i < $num /*&& $i < $conf->liste_limit*/) + { + $objp = $db->fetch_object($result); - $marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : ''; - $markRate = ($objp->selling_price != 0) ? (100 * $objp->marge / $objp->selling_price) : ''; + $marginRate = ($objp->buying_price != 0) ? (100 * $objp->marge / $objp->buying_price) : ''; + $markRate = ($objp->selling_price != 0) ? (100 * $objp->marge / $objp->selling_price) : ''; - $sign = ''; - if ($objp->type == Facture::TYPE_CREDIT_NOTE) { - $sign = '-'; - } + $sign = ''; + if ($objp->type == Facture::TYPE_CREDIT_NOTE) { + $sign = '-'; + } - print ''; - print '\n"; - print ""; - print "\n"; - print "\n"; - print "\n"; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) - print "\n"; - if (!empty($conf->global->DISPLAY_MARK_RATES)) - print "\n"; - print ''; - print "\n"; - $i++; - $cumul_vente += $objp->selling_price; - $cumul_achat += ($objp->type == 2 ? -1 : 1) * $objp->buying_price; - } - } + print ''; + print '\n"; + print ""; + print "\n"; + print "\n"; + print "\n"; + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + print "\n"; + if (!empty($conf->global->DISPLAY_MARK_RATES)) + print "\n"; + print ''; + print "\n"; + $i++; + $cumul_vente += $objp->selling_price; + $cumul_achat += ($objp->type == 2 ? -1 : 1) * $objp->buying_price; + } + } - // affichage totaux marges + // affichage totaux marges - $totalMargin = $cumul_vente - $cumul_achat; - if ($totalMargin < 0) - { - $marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : ''; - $markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : ''; - } else { - $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : ''; - $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : ''; - } + $totalMargin = $cumul_vente - $cumul_achat; + if ($totalMargin < 0) + { + $marginRate = ($cumul_achat != 0) ?-1 * (100 * $totalMargin / $cumul_achat) : ''; + $markRate = ($cumul_vente != 0) ?-1 * (100 * $totalMargin / $cumul_vente) : ''; + } else { + $marginRate = ($cumul_achat != 0) ? (100 * $totalMargin / $cumul_achat) : ''; + $markRate = ($cumul_vente != 0) ? (100 * $totalMargin / $cumul_vente) : ''; + } - // Total - print ''; - print '"; - print "\n"; - print "\n"; - print "\n"; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) - print "\n"; - if (!empty($conf->global->DISPLAY_MARK_RATES)) - print "\n"; - print ''; - print "\n"; - } else { - dol_print_error($db); - } - print "
'; - $invoicestatic->id = $objp->facid; - $invoicestatic->ref = $objp->ref; - print $invoicestatic->getNomUrl(1); - print ""; - print dol_print_date($db->jdate($objp->datef), 'day')."".price(price2num($objp->selling_price, 'MT'))."".price(price2num(($objp->type == 2 ? -1 : 1) * $objp->buying_price, 'MT'))."".$sign.price(price2num($objp->marge, 'MT'))."".(($marginRate === '') ? 'n/a' : $sign.price(price2num($marginRate, 'MT'))."%")."".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'
'; + $invoicestatic->id = $objp->facid; + $invoicestatic->ref = $objp->ref; + print $invoicestatic->getNomUrl(1); + print ""; + print dol_print_date($db->jdate($objp->datef), 'day')."".price(price2num($objp->selling_price, 'MT'))."".price(price2num(($objp->type == 2 ? -1 : 1) * $objp->buying_price, 'MT'))."".$sign.price(price2num($objp->marge, 'MT'))."".(($marginRate === '') ? 'n/a' : $sign.price(price2num($marginRate, 'MT'))."%")."".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."'.$invoicestatic->LibStatut($objp->paye, $objp->statut, 5).'
'.$langs->trans('TotalMargin')."".price(price2num($cumul_vente, 'MT'))."".price(price2num($cumul_achat, 'MT'))."".price(price2num($totalMargin, 'MT'))."".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")." 
"; - print '
'; + // Total + print ''; + print ''.$langs->trans('TotalMargin').""; + print "".price(price2num($cumul_vente, 'MT'))."\n"; + print "".price(price2num($cumul_achat, 'MT'))."\n"; + print "".price(price2num($totalMargin, 'MT'))."\n"; + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + print "".(($marginRate === '') ? 'n/a' : price(price2num($marginRate, 'MT'))."%")."\n"; + if (!empty($conf->global->DISPLAY_MARK_RATES)) + print "".(($markRate === '') ? 'n/a' : price(price2num($markRate, 'MT'))."%")."\n"; + print ' '; + print "\n"; + } else { + dol_print_error($db); + } + print ""; + print ''; - print '
'; - $db->free($result); + print '
'; + $db->free($result); } else { dol_print_error('', 'Parameter socid not defined'); } diff --git a/htdocs/modulebuilder/template/class/api_mymodule.class.php b/htdocs/modulebuilder/template/class/api_mymodule.class.php index da1b243979f..05ca7f27d16 100644 --- a/htdocs/modulebuilder/template/class/api_mymodule.class.php +++ b/htdocs/modulebuilder/template/class/api_mymodule.class.php @@ -290,8 +290,8 @@ class MyModuleApi extends DolibarrApi /** * Clean sensible object datas * - * @param Object $object Object to clean - * @return Object Object with cleaned properties + * @param Object $object Object to clean + * @return Object Object with cleaned properties */ protected function _cleanObjectDatas($object) { diff --git a/htdocs/mrp/class/api_mos.class.php b/htdocs/mrp/class/api_mos.class.php index 7eecaac860a..1d37e73adad 100644 --- a/htdocs/mrp/class/api_mos.class.php +++ b/htdocs/mrp/class/api_mos.class.php @@ -270,8 +270,8 @@ class Mos extends DolibarrApi /** * Clean sensible object datas * - * @param Object $object Object to clean - * @return Object Object with cleaned properties + * @param Object $object Object to clean + * @return Object Object with cleaned properties */ protected function _cleanObjectDatas($object) { diff --git a/htdocs/mrp/class/mo.class.php b/htdocs/mrp/class/mo.class.php index 9b2186dbc18..ee10229bfdc 100644 --- a/htdocs/mrp/class/mo.class.php +++ b/htdocs/mrp/class/mo.class.php @@ -103,7 +103,7 @@ class Mo extends CommonObject 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1', 'label'=>'ThirdParty', 'enabled'=>1, 'visible'=>-1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'css'=>'maxwidth300'), 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'enabled'=>1, 'visible'=>-1, 'position'=>51, 'notnull'=>-1, 'index'=>1,), 'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label'=>'WarehouseForProduction', 'enabled'=>1, 'visible'=>1, 'position'=>52, 'css'=>'maxwidth300'), - 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'notnull'=>-1,), + 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'notnull'=>-1,), 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62, 'notnull'=>-1,), 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>500, 'notnull'=>1,), 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'position'=>501, 'notnull'=>-1,), diff --git a/htdocs/mrp/index.php b/htdocs/mrp/index.php index b5f95dfc2c6..b84a77c2288 100644 --- a/htdocs/mrp/index.php +++ b/htdocs/mrp/index.php @@ -96,7 +96,7 @@ if ($conf->use_javascript_ajax) print '
'; print ''; - print '' . "\n"; + print ''."\n"; $listofstatus = array(0, 1, 2, 3, 9); foreach ($listofstatus as $status) { diff --git a/htdocs/multicurrency/multicurrency_rate.php b/htdocs/multicurrency/multicurrency_rate.php index f5b7458aec7..ad2b0e8ddf6 100644 --- a/htdocs/multicurrency/multicurrency_rate.php +++ b/htdocs/multicurrency/multicurrency_rate.php @@ -43,38 +43,38 @@ $action = GETPOST('action', 'alpha'); $massaction = GETPOST('massaction', 'alpha'); $show_files = GETPOST('show_files', 'int'); $confirm = GETPOST('confirm', 'alpha'); -$toselect = GETPOST('toselect', 'array'); -$id_rate_selected = GETPOST('id_rate', 'int'); -$sall = trim((GETPOST('search_all', 'alphanohtml')!='')?GETPOST('search_all', 'alphanohtml'):GETPOST('sall', 'alphanohtml')); -$search_date_sync = GETPOST('search_date_sync', 'alpha'); +$toselect = GETPOST('toselect', 'array'); +$id_rate_selected = GETPOST('id_rate', 'int'); +$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); +$search_date_sync = GETPOST('search_date_sync', 'alpha'); $search_rate = GETPOST('search_rate', 'alpha'); $search_code = GETPOST('search_code', 'alpha'); $multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $dateinput = dol_mktime(0, 0, 0, GETPOST('dateinputmonth', 'int'), GETPOST('dateinputday', 'int'), GETPOST('dateinputyear', 'int')); $rateinput = price2num(GETPOST('rateinput', 'alpha')); $optioncss = GETPOST('optioncss', 'alpha'); -$limit = GETPOST('limit', 'int')?GETPOST('limit', 'int') : $conf->liste_limit; +$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); -$page = (GETPOST("page", 'int')?GETPOST("page", 'int'):0); +$page = (GETPOST("page", 'int') ?GETPOST("page", 'int') : 0); if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (! $sortfield) $sortfield="cr.date_sync"; -if (! $sortorder) $sortorder="ASC"; +if (!$sortfield) $sortfield = "cr.date_sync"; +if (!$sortorder) $sortorder = "ASC"; // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks -$object=new CurrencyRate($db); +$object = new CurrencyRate($db); $extrafields = new ExtraFields($db); -$form=new Form($db); +$form = new Form($db); $hookmanager->initHooks(array('EditorRatelist', 'globallist')); -if (empty($action)) $action='list'; +if (empty($action)) $action = 'list'; // List of fields to search into when doing a "search in all" $fieldstosearchall = array( @@ -84,7 +84,7 @@ $fieldstosearchall = array( ); // Definition of fields for lists -$arrayfields=array( +$arrayfields = array( 'cr.date_sync'=>array('label'=>'Date', 'checked'=>1), 'cr.rate'=>array('label'=>'Rate', 'checked'=>1), 'm.code'=>array('label'=>'Code', 'checked'=>1), @@ -99,7 +99,7 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); /* * Actions */ -if ($action == "create"){ +if ($action == "create") { if (!empty($rateinput)) { $currencyRate_static = new CurrencyRate($db); $currency_static = new MultiCurrency($db); @@ -122,34 +122,34 @@ if ($action == "create"){ } } -if ($action == 'update'){ +if ($action == 'update') { $currencyRate = new CurrencyRate($db); $result = $currencyRate->fetch($id_rate_selected); - if ( $result > 0){ - $currency_static = new MultiCurrency($db); + if ($result > 0) { + $currency_static = new MultiCurrency($db); $fk_currency = $currency_static->getIdFromCode($db, $multicurrency_code); $currencyRate->date_sync = $dateinput; $currencyRate->fk_multicurrency = $fk_currency; $currencyRate->rate = $rateinput; $res = $currencyRate->update(); - if ($res){ + if ($res) { setEventMessages($langs->trans('successUpdateRate'), null); - }else { + } else { setEventMessages($currencyRate->error, $currencyRate->errors, "errors"); } - }else { + } else { setEventMessages($langs->trans('Error'), null, "warnings"); } } -if ($action == "deleteRate"){ +if ($action == "deleteRate") { $current_rate = new CurrencyRate($db); $current_rate->fetch(intval($id_rate_selected)); - if ($current_rate){ + if ($current_rate) { $current_currency = new MultiCurrency($db); $current_currency->fetch($current_rate->fk_multicurrency); - if ($current_currency){ + if ($current_currency) { $delayedhtmlcontent = $form->formconfirm( $_SERVER["PHP_SELF"].'?id_rate='.$id_rate_selected, $langs->trans('DeleteLineRate'), @@ -159,36 +159,36 @@ if ($action == "deleteRate"){ 0, 1 ); - }else { + } else { dol_syslog("Multicurrency::fetch", LOG_WARNING); } - }else { + } else { setEventMessage($langs->trans('NoCurrencyRateSelected'), "warnings"); } } -if ($action == "confirm_delete"){ +if ($action == "confirm_delete") { $current_rate = new CurrencyRate($db); $current_rate->fetch(intval($id_rate_selected)); - if ($current_rate){ - $result = $current_rate->delete(); - if ($result){ + if ($current_rate) { + $result = $current_rate->delete(); + if ($result) { setEventMessages($langs->trans('successRateDelete'), null); - }else { + } else { setEventMessages($current_rate->error, $current_rate->errors, 'errors'); } - }else { + } else { setEventMessages($langs->trans('NoCurrencyRateSelected'), null, "warnings"); dol_syslog($langs->trans('NoCurrencyRateSelected'), LOG_WARNING); } } -if (GETPOST('cancel', 'alpha')) { $action='list'; $massaction=''; } -if (! GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } -$parameters=array(); -$reshook=$hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +$parameters = array(); +$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 (empty($reshook)) { @@ -198,15 +198,15 @@ if (empty($reshook)) // 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 { - $sall=""; - $search_date_sync=""; - $search_rate=""; - $search_code=""; - $search_array_options=array(); + $sall = ""; + $search_date_sync = ""; + $search_rate = ""; + $search_code = ""; + $search_array_options = array(); } // Mass actions - $objectclass="CurrencyRate"; + $objectclass = "CurrencyRate"; $uploaddir = $conf->multicurrency->multidir_output; // define only because core/actions_massactions.inc.php want it $permtoread = $user->admin; $permtodelete = $user->admin; @@ -217,9 +217,9 @@ if (empty($reshook)) * View */ -$htmlother=new FormOther($db); +$htmlother = new FormOther($db); -$title=$langs->trans("CurrencyRate"); +$title = $langs->trans("CurrencyRate"); $page_name = "ListCurrencyRate"; llxHeader('', $title, $helpurl, ''); @@ -233,30 +233,30 @@ print dol_get_fiche_head($head, 'ratelist', $langs->trans("ModuleSetup"), -1, "m // ACTION -if ($action!= "updateRate" && $action!= "deleteRate" ) { +if ($action != "updateRate" && $action != "deleteRate") { print '
' . $langs->trans("Statistics") . ' - ' . $langs->trans("ManufacturingOrder") . '
'.$langs->trans("Statistics").' - '.$langs->trans("ManufacturingOrder").'
'; print ''; print ''."\n"; print '
'.$langs->trans("FormCreateRate").'
'; $form = new Form($db); - print ''; + print ''; print ''; - print ' '; + print ' '; print ' '; - print ''; - print ''; + print ''; + print ''; - print ' '; - print ' '; + print ' '; + print ' '; print ''; print '
' . $langs->trans('Date') . ''.$langs->trans('Date').''; print $form->selectDate($dateinput, 'dateinput'); print ' ' . $langs->trans('Currency') . '' . $form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ? GETPOST('multicurrency_code', 'alpha') : $multicurrency_code), 'multicurrency_code', 0, " code != '".$conf->currency."'", true) . ' '.$langs->trans('Currency').''.$form->selectMultiCurrency((GETPOSTISSET('multicurrency_code') ? GETPOST('multicurrency_code', 'alpha') : $multicurrency_code), 'multicurrency_code', 0, " code != '".$conf->currency."'", true).'' . $langs->trans('Rate') . ''.$langs->trans('Rate').''; print ''; - print ''; + print ''; print '
'; @@ -265,49 +265,49 @@ if ($action!= "updateRate" && $action!= "deleteRate" ) { print '
'; } -if ($action == "updateRate"){ +if ($action == "updateRate") { $current_rate = new CurrencyRate($db); $current_rate->fetch(intval($id_rate_selected)); if ($current_rate) { $curr = new MultiCurrency($db); - $resultcurrentCurrency = $curr->fetch($current_rate->fk_multicurrency); + $resultcurrentCurrency = $curr->fetch($current_rate->fk_multicurrency); - if ($resultcurrentCurrency){ + if ($resultcurrentCurrency) { $currency_code = $curr->code; - }else { + } else { $currency_code = ''; } print ''; print ''; - print '' . "\n"; + print ''."\n"; print '
' . $langs->trans("FormUpdateRate") . ''.$langs->trans("FormUpdateRate").'
'; $form = new Form($db); - print ''; + print ''; print ''; - print ' '; + print ' '; print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; print ''; print '
' . $langs->trans('Date') . ''.$langs->trans('Date').''; print $form->selectDate($current_rate->date_sync, 'dateinput'); print ' ' . $langs->trans('Currency') . '' . $form->selectMultiCurrency($currency_code, 'multicurrency_code', 0, " code != '".$conf->currency."'", true) . ' '.$langs->trans('Currency').''.$form->selectMultiCurrency($currency_code, 'multicurrency_code', 0, " code != '".$conf->currency."'", true).'' . $langs->trans('Rate') . ''.$langs->trans('Rate').''; print ''; print ''; - print ''; - print '' .$langs->trans('CancelUpdate') . ''; + print ''; + print ''.$langs->trans('CancelUpdate').''; print '
'; print ''; - }else { + } else { dol_syslog("currency_rate:list:update", LOG_WARNING); } } @@ -315,29 +315,29 @@ if ($action == "updateRate"){ $sql = 'SELECT cr.rowid, cr.date_sync, cr.rate, cr.entity, m.code, m.name '; // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= ' FROM '.MAIN_DB_PREFIX.'multicurrency_rate as cr '; -$sql .=" INNER JOIN ".MAIN_DB_PREFIX."multicurrency AS m ON cr.fk_multicurrency = m.rowid"; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= ' FROM '.MAIN_DB_PREFIX.'multicurrency_rate as cr '; +$sql .= " INNER JOIN ".MAIN_DB_PREFIX."multicurrency AS m ON cr.fk_multicurrency = m.rowid"; if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); if ($search_date_sync) $sql .= natural_search('cr.date_sync', $search_date_sync); if ($search_rate) $sql .= natural_search('cr.rate', $search_rate); if ($search_code) $sql .= natural_search('m.code', $search_code); -$sql.= " WHERE m.code <> '".$db->escape($conf->currency)."'"; +$sql .= " WHERE m.code <> '".$db->escape($conf->currency)."'"; // Add where from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; -$sql.= " GROUP BY cr.rowid, cr.date_sync, cr.rate, m.code, cr.entity, m.code, m.name"; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql .= " GROUP BY cr.rowid, cr.date_sync, cr.rate, m.code, cr.entity, m.code, m.name"; // Add fields from hooks -$parameters=array(); -$reshook=$hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook -$sql.=$hookmanager->resPrint; +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldSelect', $parameters); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; -$sql.= $db->order($sortfield, $sortorder); +$sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; @@ -345,41 +345,41 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $result = $db->query($sql); - if ($result){ + if ($result) { $nbtotalofrecords = $db->num_rows($result); if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 { $page = 0; $offset = 0; } - }else { + } else { setEventMessage($langs->trans('No_record_on_multicurrency_rate'), 'warnings'); } } -$sql.= $db->plimit($limit + 1, $offset); +$sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - $arrayofselected=is_array($toselect)?$toselect:array(); + $arrayofselected = is_array($toselect) ? $toselect : array(); - $param=''; - if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit); - if ($sall) $param.="&sall=".urlencode($sall); + $param = ''; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); + if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if ($sall) $param .= "&sall=".urlencode($sall); - if ($search_date_sync) $param="&search_date_sync=".urlencode($search_date_sync); - if ($search_rate) $param="&search_rate=".urlencode($search_rate); - if ($search_code != '') $param.="&search_code=".urlencode($search_code); + if ($search_date_sync) $param = "&search_date_sync=".urlencode($search_date_sync); + if ($search_rate) $param = "&search_rate=".urlencode($search_rate); + if ($search_code != '') $param .= "&search_code=".urlencode($search_code); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - if ($user->admin) $arrayofmassactions['predelete']=$langs->trans("Delete"); - if (in_array($massaction, array('presend','predelete'))) $arrayofmassactions=array(); - $massactionbutton=$form->selectMassAction('', $arrayofmassactions); + if ($user->admin) $arrayofmassactions['predelete'] = $langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print '
'; if ($optioncss != '') print ''; @@ -397,18 +397,18 @@ if ($resql) if ($sall) { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key]=$langs->trans($val); - print '
'.$langs->trans("FilterOnInto", $sall) . join(', ', $fieldstosearchall).'
'; + foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } // Filter on categories - $moreforfilter=''; + $moreforfilter = ''; - $parameters=array(); - $reshook=$hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter.=$hookmanager->resPrint; - else $moreforfilter=$hookmanager->resPrint; + $parameters = array(); + $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook + if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; + else $moreforfilter = $hookmanager->resPrint; if ($moreforfilter) { @@ -417,32 +417,32 @@ if ($resql) print '
'; } - $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage; - $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - if ($massactionbutton) $selectedfields.=$form->showCheckAddButtons('checkforselect', 1); + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); print '
'; - print ''."\n"; + print '
'."\n"; // Lines with input filters print ''; // date - if (! empty($arrayfields['cr.date_sync']['checked'])) + if (!empty($arrayfields['cr.date_sync']['checked'])) { print ''; } // code - if (! empty($arrayfields['m.code']['checked'])) + if (!empty($arrayfields['m.code']['checked'])) { print ''; } // rate - if (! empty($arrayfields['cr.rate']['checked'])) + if (!empty($arrayfields['cr.rate']['checked'])) { print ''; print ''; print ''; - if (! empty($arrayfields['cr.date_sync']['checked'])) print_liste_field_titre($arrayfields['cr.date_sync']['label'], $_SERVER["PHP_SELF"], "cr.date_sync", "", $param, "", $sortfield, $sortorder); - if (! empty($arrayfields['m.code']['checked'])) print_liste_field_titre($arrayfields['m.code']['label'], $_SERVER["PHP_SELF"], "m.code", "", $param, "", $sortfield, $sortorder); - if (! empty($arrayfields['cr.rate']['checked'])) print_liste_field_titre($arrayfields['cr.rate']['label'], $_SERVER["PHP_SELF"], "cr.rate", "", $param, "", $sortfield, $sortorder); + if (!empty($arrayfields['cr.date_sync']['checked'])) print_liste_field_titre($arrayfields['cr.date_sync']['label'], $_SERVER["PHP_SELF"], "cr.date_sync", "", $param, "", $sortfield, $sortorder); + if (!empty($arrayfields['m.code']['checked'])) print_liste_field_titre($arrayfields['m.code']['label'], $_SERVER["PHP_SELF"], "m.code", "", $param, "", $sortfield, $sortorder); + if (!empty($arrayfields['cr.rate']['checked'])) print_liste_field_titre($arrayfields['cr.rate']['label'], $_SERVER["PHP_SELF"], "cr.rate", "", $param, "", $sortfield, $sortorder); // Hook fields - $parameters=array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); - $reshook=$hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); + $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; $i = 0; - $totalarray=array(); + $totalarray = array(); while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); @@ -483,50 +483,50 @@ if ($resql) print ''; // date_sync - if (! empty($arrayfields['cr.date_sync']['checked'])) + if (!empty($arrayfields['cr.date_sync']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // code - if (! empty($arrayfields['m.code']['checked'])) + if (!empty($arrayfields['m.code']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // rate - if (! empty($arrayfields['cr.rate']['checked'])) + if (!empty($arrayfields['cr.rate']['checked'])) { print '\n"; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; } // Fields from hook - $parameters=array('arrayfields'=>$arrayfields, 'obj'=>$obj); - $reshook=$hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields, 'obj'=>$obj); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Action print ''; - if (! $i) $totalarray['nbfield']++; + if (!$i) $totalarray['nbfield']++; print "\n"; $i++; diff --git a/htdocs/product/admin/price_rules.php b/htdocs/product/admin/price_rules.php index 84510dfabad..000acb485d2 100644 --- a/htdocs/product/admin/price_rules.php +++ b/htdocs/product/admin/price_rules.php @@ -141,7 +141,7 @@ for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) { $price_options[$i] = $langs->trans('SellingPrice').' '.$i; } -$genPriceOptions = function ($level) use ($price_options) { +$genPriceOptions = function($level) use ($price_options) { $return = array(); diff --git a/htdocs/product/class/api_products.class.php b/htdocs/product/class/api_products.class.php index b5c08d96cc2..f7406692f8d 100644 --- a/htdocs/product/class/api_products.class.php +++ b/htdocs/product/class/api_products.class.php @@ -34,1820 +34,1820 @@ require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.cla */ class Products extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'ref', - 'label' - ); - - /** - * @var Product $product {@type Product} - */ - public $product; - - /** - * @var ProductFournisseur $productsupplier {@type ProductFournisseur} - */ - public $productsupplier; - - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - - $this->db = $db; - $this->product = new Product($this->db); - $this->productsupplier = new ProductFournisseur($this->db); - } - - /** - * Get properties of a product object by id - * - * Return an array with product information. - * - * @param int $id ID of product - * @param int $includestockdata Load also information about stock (slower) - * @param bool $includesubproducts Load information about subproducts - * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) - * @return array|mixed Data without useless information - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function get($id, $includestockdata = 0, $includesubproducts = false, $includeparentid = false) - { - return $this->_fetch($id, '', '', '', $includestockdata, $includesubproducts, $includeparentid); - } - - /** - * Get properties of a product object by ref - * - * Return an array with product information. - * - * @param string $ref Ref of element - * @param int $includestockdata Load also information about stock (slower) - * @param bool $includesubproducts Load information about subproducts - * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) - * - * @return array|mixed Data without useless information - * - * @url GET ref/{ref} - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function getByRef($ref, $includestockdata = 0, $includesubproducts = false, $includeparentid = false) - { - return $this->_fetch('', $ref, '', '', $includestockdata, $includesubproducts, $includeparentid); - } - - /** - * Get properties of a product object by ref_ext - * - * Return an array with product information. - * - * @param string $ref_ext Ref_ext of element - * @param int $includestockdata Load also information about stock (slower) - * @param bool $includesubproducts Load information about subproducts - * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) - * - * @return array|mixed Data without useless information - * - * @url GET ref_ext/{ref_ext} - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function getByRefExt($ref_ext, $includestockdata = 0, $includesubproducts = false, $includeparentid = false) - { - return $this->_fetch('', '', $ref_ext, '', $includestockdata, $includesubproducts, $includeparentid); - } - - /** - * Get properties of a product object by barcode - * - * Return an array with product information. - * - * @param string $barcode Barcode of element - * @param int $includestockdata Load also information about stock (slower) - * @param bool $includesubproducts Load information about subproducts - * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) - * - * @return array|mixed Data without useless information - * - * @url GET barcode/{barcode} - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function getByBarcode($barcode, $includestockdata = 0, $includesubproducts = false, $includeparentid = false) - { - return $this->_fetch('', '', '', $barcode, $includestockdata, $includesubproducts, $includeparentid); - } - - /** - * List products - * - * Get a list of products - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service) - * @param int $category Use this param to filter list by category - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)" - * @return array Array of product objects - */ - public function index($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '') - { - global $db, $conf; - - $obj_ret = array(); - - $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : ''; - - $sql = "SELECT t.rowid, t.ref, t.ref_ext"; - $sql .= " FROM ".MAIN_DB_PREFIX."product as t"; - if ($category > 0) { - $sql .= ", ".MAIN_DB_PREFIX."categorie_product as c"; - } - $sql .= ' WHERE t.entity IN ('.getEntity('product').')'; - // Select products of given category - if ($category > 0) { - $sql .= " AND c.fk_categorie = ".$this->db->escape($category); - $sql .= " AND c.fk_product = t.rowid "; - } - if ($mode == 1) { - // Show only products - $sql .= " AND t.fk_product_type = 0"; - } elseif ($mode == 2) { - // Show only services - $sql .= " AND t.fk_product_type = 1"; - } - // Add sql filters - if ($sqlfilters) { - if (!DolibarrApi::_checkFilters($sqlfilters)) { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - - $sql .= $this->db->plimit($limit + 1, $offset); - } - - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - $i = 0; - while ($i < $min) - { - $obj = $this->db->fetch_object($result); - $product_static = new Product($this->db); - if ($product_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($product_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No product found'); - } - return $obj_ret; - } - - /** - * Create product object - * - * @param array $request_data Request data - * @return int ID of product - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } - // Check mandatory fields - $result = $this->_validate($request_data); - - foreach ($request_data as $field => $value) { - $this->product->$field = $value; - } - if ($this->product->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating product", array_merge(array($this->product->error), $this->product->errors)); - } - - return $this->product->id; - } - - /** - * Update product. - * Price will be updated by this API only if option is set on "One price per product". See other APIs for other price modes. - * - * @param int $id Id of product to update - * @param array $request_data Datas - * @return int - * - * @throws RestException 401 - * @throws RestException 404 - */ - public function put($id, $request_data = null) - { - global $conf; - - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } - - $result = $this->product->fetch($id); - if (!$result) { - throw new RestException(404, 'Product not found'); - } - - if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $oldproduct = dol_clone($this->product, 0); - - foreach ($request_data as $field => $value) { - if ($field == 'id') { continue; - } - if ($field == 'stock_reel') { - throw new RestException(400, 'Stock reel cannot be updated here. Use the /stockmovements endpoint instead'); - } - $this->product->$field = $value; - } - - $updatetype = false; - if ($this->product->type != $oldproduct->type && ($this->product->isProduct() || $this->product->isService())) { - $updatetype = true; - } - - $result = $this->product->update($id, DolibarrApiAccess::$user, 1, 'update', $updatetype); - - // If price mode is 1 price per product - if ($result > 0 && !empty($conf->global->PRODUCT_PRICE_UNIQ)) { - // We update price only if it was changed - $pricemodified = false; - if ($this->product->price_base_type != $oldproduct->price_base_type) { $pricemodified = true; - } else { - if ($this->product->tva_tx != $oldproduct->tva_tx) { $pricemodified = true; - } - if ($this->product->tva_npr != $oldproduct->tva_npr) { $pricemodified = true; - } - if ($this->product->default_vat_code != $oldproduct->default_vat_code) { $pricemodified = true; - } - - if ($this->product->price_base_type == 'TTC') { - if ($this->product->price_ttc != $oldproduct->price_ttc) { $pricemodified = true; - } - if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) { $pricemodified = true; - } - } else { - if ($this->product->price != $oldproduct->price) { $pricemodified = true; - } - if ($this->product->price_min != $oldproduct->price_min) { $pricemodified = true; - } - } - } - - if ($pricemodified) { - $newvat = $this->product->tva_tx; - $newnpr = $this->product->tva_npr; - $newvatsrccode = $this->product->default_vat_code; - - $newprice = $this->product->price; - $newpricemin = $this->product->price_min; - if ($this->product->price_base_type == 'TTC') { - $newprice = $this->product->price_ttc; - $newpricemin = $this->product->price_min_ttc; - } - - $result = $this->product->updatePrice($newprice, $this->product->price_base_type, DolibarrApiAccess::$user, $newvat, $newpricemin, 0, $newnpr, 0, 0, array(), $newvatsrccode); - } - } - - if ($result <= 0) { - throw new RestException(500, "Error updating product", array_merge(array($this->product->error), $this->product->errors)); - } - - return $this->get($id); - } - - /** - * Delete product - * - * @param int $id Product ID - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->produit->supprimer) { - throw new RestException(401); - } - $result = $this->product->fetch($id); - if (!$result) { - throw new RestException(404, 'Product not found'); - } - - if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - // The Product::delete() method uses the global variable $user. - global $user; - $user = DolibarrApiAccess::$user; - - return $this->product->delete(DolibarrApiAccess::$user); - } - - /** - * Get the list of subproducts of the product. - * - * @param int $id Id of parent product/service - * @return array - * - * @throws RestException - * @throws RestException 401 - * @throws RestException 404 - * - * @url GET {id}/subproducts - */ - public function getSubproducts($id) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } - - if (!DolibarrApi::_checkAccessToResource('product', $id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $childsArbo = $this->product->getChildsArbo($id, 1); - - $keys = ['rowid', 'qty', 'fk_product_type', 'label', 'incdec']; - $childs = []; - foreach ($childsArbo as $values) { - $childs[] = array_combine($keys, $values); - } - - return $childs; - } - - /** - * Add subproduct. - * - * Link a product/service to a parent product/service - * - * @param int $id Id of parent product/service - * @param int $subproduct_id Id of child product/service - * @param int $qty Quantity - * @param int $incdec 1=Increase/decrease stock of child when parent stock increase/decrease - * @return int - * - * @throws RestException - * @throws RestException 401 - * @throws RestException 404 - * - * @url POST {id}/subproducts/add - */ - public function addSubproducts($id, $subproduct_id, $qty, $incdec = 1) - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } - - if (!DolibarrApi::_checkAccessToResource('product', $id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->product->add_sousproduit($id, $subproduct_id, $qty, $incdec); - if ($result <= 0) { - throw new RestException(500, "Error adding product child"); - } - return $result; - } - - /** - * Remove subproduct. - * Unlink a product/service from a parent product/service - * - * @param int $id Id of parent product/service - * @param int $subproduct_id Id of child product/service - * @return int - * - * @throws RestException 401 - * @throws RestException 404 - * - * @url DELETE {id}/subproducts/remove/{subproduct_id} - */ - public function delSubproducts($id, $subproduct_id) - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } - - if (!DolibarrApi::_checkAccessToResource('product', $id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->product->del_sousproduit($id, $subproduct_id); - if ($result <= 0) { - throw new RestException(500, "Error while removing product child"); - } - return $result; - } - - - /** - * Get categories for a product - * - * @param int $id ID of product - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * - * @return mixed - * - * @url GET {id}/categories - */ - public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) - { - if (!DolibarrApiAccess::$user->rights->categorie->lire) { - throw new RestException(401); - } - - $categories = new Categorie($this->db); - - $result = $categories->getListForItem($id, 'product', $sortfield, $sortorder, $limit, $page); - - if (empty($result)) { - throw new RestException(404, 'No category found'); - } - - if ($result < 0) { - throw new RestException(503, 'Error when retrieve category list : '.array_merge(array($categories->error), $categories->errors)); - } - - return $result; - } - - /** - * Get prices per segment for a product - * - * @param int $id ID of product - * - * @return mixed - * - * @url GET {id}/selling_multiprices/per_segment - */ - public function getCustomerPricesPerSegment($id) - { - global $conf; - - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } - - if (empty($conf->global->PRODUIT_MULTIPRICES)) { - throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup'); - } - - $result = $this->product->fetch($id); - if (!$result) { - throw new RestException(404, 'Product not found'); - } - - if ($result < 0) { - throw new RestException(503, 'Error when retrieve prices list : '.array_merge(array($this->product->error), $this->product->errors)); - } - - return array( - 'multiprices'=>$this->product->multiprices, - 'multiprices_inc_tax'=>$this->product->multiprices_ttc, - 'multiprices_min'=>$this->product->multiprices_min, - 'multiprices_min_inc_tax'=>$this->product->multiprices_min_ttc, - 'multiprices_vat'=>$this->product->multiprices_tva_tx, - 'multiprices_base_type'=>$this->product->multiprices_base_type, - //'multiprices_default_vat_code'=>$this->product->multiprices_default_vat_code - ); - } - - /** - * Get prices per customer for a product - * - * @param int $id ID of product - * @param string $thirdparty_id Thirdparty id to filter orders of (example '1') {@pattern /^[0-9,]*$/i} - * - * @return mixed - * - * @url GET {id}/selling_multiprices/per_customer - */ - public function getCustomerPricesPerCustomer($id, $thirdparty_id = '') - { - global $conf; - - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } - - if (empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { - throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup'); - } - - $result = $this->product->fetch($id); - if (!$result) { - throw new RestException(404, 'Product not found'); - } - - if ($result > 0) { - require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; - $prodcustprice = new Productcustomerprice($this->db); - $filter = array(); - $filter['t.fk_product'] .= $id; - if ($thirdparty_id) $filter['t.fk_soc'] .= $thirdparty_id; - $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); - } - - if (empty($prodcustprice->lines)) { - throw new RestException(404, 'Prices not found'); - } - - return $prodcustprice->lines; - } - - /** - * Get prices per quantity for a product - * - * @param int $id ID of product - * - * @return mixed - * - * @url GET {id}/selling_multiprices/per_quantity - */ - public function getCustomerPricesPerQuantity($id) - { - global $conf; - - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } - - if (empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { - throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup'); - } - - $result = $this->product->fetch($id); - if (!$result) { - throw new RestException(404, 'Product not found'); - } - - if ($result < 0) { - throw new RestException(503, 'Error when retrieve prices list : '.array_merge(array($this->product->error), $this->product->errors)); - } - - return array( - 'prices_by_qty'=>$this->product->prices_by_qty[0], // 1 if price by quantity was activated for the product - 'prices_by_qty_list'=>$this->product->prices_by_qty_list[0] - ); - } - - /** - * Add/Update purchase prices for a product. - * - * @param int $id ID of Product - * @param float $qty Min quantity for which price is valid - * @param float $buyprice Purchase price for the quantity min - * @param string $price_base_type HT or TTC - * @param int $fourn_id Supplier ID - * @param int $availability Product availability - * @param string $ref_fourn Supplier ref - * @param float $tva_tx New VAT Rate (For example 8.5. Should not be a string) - * @param string $charges costs affering to product - * @param float $remise_percent Discount regarding qty (percent) - * @param float $remise Discount regarding qty (amount) - * @param int $newnpr Set NPR or not - * @param int $delivery_time_days Delay in days for delivery (max). May be '' if not defined. - * @param string $supplier_reputation Reputation with this product to the defined supplier (empty, FAVORITE, DONOTORDER) - * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function). - * @param string $newdefaultvatcode Default vat code - * @param float $multicurrency_buyprice Purchase price for the quantity min in currency - * @param string $multicurrency_price_base_type HT or TTC in currency - * @param float $multicurrency_tx Rate currency - * @param string $multicurrency_code Currency code - * @param string $desc_fourn Custom description for product_fourn_price - * @param string $barcode Barcode - * @param int $fk_barcode_type Barcode type - * @return int - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url POST {id}/purchase_prices - */ - public function addPurchasePrice($id, $qty, $buyprice, $price_base_type, $fourn_id, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = null) - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } - - $result = $this->productsupplier->fetch($id); - if (!$result) { - throw new RestException(404, 'Product not found'); - } - - if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $result = $this->productsupplier->add_fournisseur(DolibarrApiAccess::$user, $fourn_id, $ref_fourn, $qty); - if ($result < 0) { - throw new RestException(500, "Error adding supplier to product : ".$this->db->lasterror()); - } - - $fourn = new Fournisseur($this->db); - $result = $fourn->fetch($fourn_id); - if ($result <= 0) { - throw new RestException(404, 'Supplier not found'); - } - - $result = $this->productsupplier->update_buyprice($qty, $buyprice, DolibarrApiAccess::$user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges, $remise_percent, $remise, $newnpr, $delivery_time_days, $supplier_reputation, $localtaxes_array, $newdefaultvatcode, $multicurrency_buyprice, $multicurrency_price_base_type, $multicurrency_tx, $multicurrency_code, $desc_fourn, $barcode, $fk_barcode_type); - - if ($result <= 0) { - throw new RestException(500, "Error updating buy price : ".$this->db->lasterror()); - } - return (int) $this->productsupplier->product_fourn_price_id; - } - - /** - * Delete purchase price for a product - * - * @param int $id Product ID - * @param int $priceid purchase price ID - * - * @url DELETE {id}/purchase_prices/{priceid} - * - * @return int - * - * @throws RestException 401 - * @throws RestException 404 - * - */ - public function deletePurchasePrice($id, $priceid) - { - if (!DolibarrApiAccess::$user->rights->produit->supprimer) { - throw new RestException(401); - } - $result = $this->productsupplier->fetch($id); - if (!$result) { - throw new RestException(404, 'Product not found'); - } - - if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $resultsupplier = 0; - if ($result > 0) { - $resultsupplier = $this->productsupplier->remove_product_fournisseur_price($priceid); - } - - return $resultsupplier; - } - - /** - * Get a list of all purchase prices of products - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service) - * @param int $category Use this param to filter list by category of product - * @param int $supplier Use this param to filter list by supplier - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)" - * @return array Array of product objects - * - * @url GET purchase_prices - */ - public function getSupplierProducts($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $supplier = 0, $sqlfilters = '') - { - global $db, $conf; - - $obj_ret = array(); - - $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : ''; - - $sql = "SELECT t.rowid, t.ref, t.ref_ext"; - $sql .= " FROM ".MAIN_DB_PREFIX."product as t"; - if ($category > 0) { - $sql .= ", ".MAIN_DB_PREFIX."categorie_product as c"; - } - $sql .= ", ".MAIN_DB_PREFIX."product_fournisseur_price as s"; - - $sql .= ' WHERE t.entity IN ('.getEntity('product').')'; - - if ($supplier > 0) { - $sql .= " AND s.fk_soc = ".$this->db->escape($supplier); - } - $sql .= " AND s.fk_product = t.rowid"; - // Select products of given category - if ($category > 0) { - $sql .= " AND c.fk_categorie = ".$this->db->escape($category); - $sql .= " AND c.fk_product = t.rowid"; - } - if ($mode == 1) { - // Show only products - $sql .= " AND t.fk_product_type = 0"; - } elseif ($mode == 2) { - // Show only services - $sql .= " AND t.fk_product_type = 1"; - } - // Add sql filters - if ($sqlfilters) { - if (!DolibarrApi::_checkFilters($sqlfilters)) { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; - $sql .= $this->db->plimit($limit + 1, $offset); - } - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - $i = 0; - while ($i < $min) - { - $obj = $this->db->fetch_object($result); - - $product_fourn = new ProductFournisseur($this->db); - $product_fourn_list = $product_fourn->list_product_fournisseur_price($obj->rowid, '', '', 0, 0); - foreach ($product_fourn_list as $tmpobj) { - $this->_cleanObjectDatas($tmpobj); - } - - //var_dump($product_fourn_list->db);exit; - $obj_ret[$obj->rowid] = $product_fourn_list; - - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No product found'); - } - return $obj_ret; - } - - /** - * Get purchase prices for a product - * - * Return an array with product information. - * TODO implement getting a product by ref or by $ref_ext - * - * @param int $id ID of product - * @param string $ref Ref of element - * @param string $ref_ext Ref ext of element - * @param string $barcode Barcode of element - * @return array|mixed Data without useless information - * - * @url GET {id}/purchase_prices - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - * - */ - public function getPurchasePrices($id, $ref = '', $ref_ext = '', $barcode = '') - { - if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) { - throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode'); - } - - $id = (empty($id) ? 0 : $id); - - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(403); - } - - $result = $this->product->fetch($id, $ref, $ref_ext, $barcode); - if (!$result) { - throw new RestException(404, 'Product not found'); - } - - if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - - $product_fourn_list = array(); - - if ($result) { - $product_fourn = new ProductFournisseur($this->db); - $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->product->id, '', '', 0, 0); - } - - foreach ($product_fourn_list as $tmpobj) { - $this->_cleanObjectDatas($tmpobj); - } - - return $this->_cleanObjectDatas($product_fourn_list); - } - - /** - * Get attributes. + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'ref', + 'label' + ); + + /** + * @var Product $product {@type Product} + */ + public $product; + + /** + * @var ProductFournisseur $productsupplier {@type ProductFournisseur} + */ + public $productsupplier; + + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + + $this->db = $db; + $this->product = new Product($this->db); + $this->productsupplier = new ProductFournisseur($this->db); + } + + /** + * Get properties of a product object by id * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:color)" - * @return array - * - * @throws RestException - * - * @url GET attributes - */ - public function getAttributes($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + * Return an array with product information. + * + * @param int $id ID of product + * @param int $includestockdata Load also information about stock (slower) + * @param bool $includesubproducts Load information about subproducts + * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) + * @return array|mixed Data without useless information + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function get($id, $includestockdata = 0, $includesubproducts = false, $includeparentid = false) + { + return $this->_fetch($id, '', '', '', $includestockdata, $includesubproducts, $includeparentid); + } - $sql = "SELECT t.rowid, t.ref, t.ref_ext, t.label, t.rang, t.entity"; - $sql .= " FROM ".MAIN_DB_PREFIX."product_attribute as t"; - $sql .= ' WHERE t.entity IN ('.getEntity('product').')'; + /** + * Get properties of a product object by ref + * + * Return an array with product information. + * + * @param string $ref Ref of element + * @param int $includestockdata Load also information about stock (slower) + * @param bool $includesubproducts Load information about subproducts + * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) + * + * @return array|mixed Data without useless information + * + * @url GET ref/{ref} + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function getByRef($ref, $includestockdata = 0, $includesubproducts = false, $includeparentid = false) + { + return $this->_fetch('', $ref, '', '', $includestockdata, $includesubproducts, $includeparentid); + } - // Add sql filters - if ($sqlfilters) { - if (!DolibarrApi::_checkFilters($sqlfilters)) { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + /** + * Get properties of a product object by ref_ext + * + * Return an array with product information. + * + * @param string $ref_ext Ref_ext of element + * @param int $includestockdata Load also information about stock (slower) + * @param bool $includesubproducts Load information about subproducts + * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) + * + * @return array|mixed Data without useless information + * + * @url GET ref_ext/{ref_ext} + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function getByRefExt($ref_ext, $includestockdata = 0, $includesubproducts = false, $includeparentid = false) + { + return $this->_fetch('', '', $ref_ext, '', $includestockdata, $includesubproducts, $includeparentid); + } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; + /** + * Get properties of a product object by barcode + * + * Return an array with product information. + * + * @param string $barcode Barcode of element + * @param int $includestockdata Load also information about stock (slower) + * @param bool $includesubproducts Load information about subproducts + * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) + * + * @return array|mixed Data without useless information + * + * @url GET barcode/{barcode} + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function getByBarcode($barcode, $includestockdata = 0, $includesubproducts = false, $includeparentid = false) + { + return $this->_fetch('', '', '', $barcode, $includestockdata, $includesubproducts, $includeparentid); + } - $sql .= $this->db->plimit($limit, $offset); - } + /** + * List products + * + * Get a list of products + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service) + * @param int $category Use this param to filter list by category + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)" + * @return array Array of product objects + */ + public function index($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $sqlfilters = '') + { + global $db, $conf; - $result = $this->db->query($sql); + $obj_ret = array(); - if (!$result) { - throw new RestException(503, 'Error when retrieve product attribute list : '.$this->db->lasterror()); - } + $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : ''; - $return = []; - while ($result = $this->db->fetch_object($query)) { - $tmp = new ProductAttribute($this->db); - $tmp->id = $result->rowid; - $tmp->ref = $result->ref; - $tmp->ref_ext = $result->ref_ext; - $tmp->label = $result->label; - $tmp->rang = $result->rang; - $tmp->entity = $result->entity; + $sql = "SELECT t.rowid, t.ref, t.ref_ext"; + $sql .= " FROM ".MAIN_DB_PREFIX."product as t"; + if ($category > 0) { + $sql .= ", ".MAIN_DB_PREFIX."categorie_product as c"; + } + $sql .= ' WHERE t.entity IN ('.getEntity('product').')'; + // Select products of given category + if ($category > 0) { + $sql .= " AND c.fk_categorie = ".$this->db->escape($category); + $sql .= " AND c.fk_product = t.rowid "; + } + if ($mode == 1) { + // Show only products + $sql .= " AND t.fk_product_type = 0"; + } elseif ($mode == 2) { + // Show only services + $sql .= " AND t.fk_product_type = 1"; + } + // Add sql filters + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $return[] = $this->_cleanObjectDatas($tmp); - } + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; - if (!count($return)) { - throw new RestException(404, 'No product attribute found'); - } + $sql .= $this->db->plimit($limit + 1, $offset); + } - return $return; - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + $i = 0; + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + $product_static = new Product($this->db); + if ($product_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($product_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No product found'); + } + return $obj_ret; + } - /** - * Get attribute by ID. - * - * @param int $id ID of Attribute - * @return array - * - * @throws RestException - * @throws RestException 401 - * @throws RestException 404 - * - * @url GET attributes/{id} - */ - public function getAttributeById($id) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + /** + * Create product object + * + * @param array $request_data Request data + * @return int ID of product + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validate($request_data); - $prodattr = new ProductAttribute($this->db); - $result = $prodattr->fetch((int) $id); + foreach ($request_data as $field => $value) { + $this->product->$field = $value; + } + if ($this->product->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating product", array_merge(array($this->product->error), $this->product->errors)); + } - if ($result < 0) { - throw new RestException(404, "Product attribute not found"); - } + return $this->product->id; + } - $fields = ["id", "ref", "ref_ext", "label", "rang", "entity"]; + /** + * Update product. + * Price will be updated by this API only if option is set on "One price per product". See other APIs for other price modes. + * + * @param int $id Id of product to update + * @param array $request_data Datas + * @return int + * + * @throws RestException 401 + * @throws RestException 404 + */ + public function put($id, $request_data = null) + { + global $conf; - foreach ($prodattr as $field => $value) { - if (!in_array($field, $fields)) { - unset($prodattr->{$field}); - } - } + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."product_attribute_combination2val as pac2v"; - $sql .= " JOIN ".MAIN_DB_PREFIX."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid"; - $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $prodattr->id)." AND pac.entity IN (".getEntity('product').")"; + $result = $this->product->fetch($id); + if (!$result) { + throw new RestException(404, 'Product not found'); + } + + if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $oldproduct = dol_clone($this->product, 0); + + foreach ($request_data as $field => $value) { + if ($field == 'id') { continue; + } + if ($field == 'stock_reel') { + throw new RestException(400, 'Stock reel cannot be updated here. Use the /stockmovements endpoint instead'); + } + $this->product->$field = $value; + } + + $updatetype = false; + if ($this->product->type != $oldproduct->type && ($this->product->isProduct() || $this->product->isService())) { + $updatetype = true; + } + + $result = $this->product->update($id, DolibarrApiAccess::$user, 1, 'update', $updatetype); + + // If price mode is 1 price per product + if ($result > 0 && !empty($conf->global->PRODUCT_PRICE_UNIQ)) { + // We update price only if it was changed + $pricemodified = false; + if ($this->product->price_base_type != $oldproduct->price_base_type) { $pricemodified = true; + } else { + if ($this->product->tva_tx != $oldproduct->tva_tx) { $pricemodified = true; + } + if ($this->product->tva_npr != $oldproduct->tva_npr) { $pricemodified = true; + } + if ($this->product->default_vat_code != $oldproduct->default_vat_code) { $pricemodified = true; + } + + if ($this->product->price_base_type == 'TTC') { + if ($this->product->price_ttc != $oldproduct->price_ttc) { $pricemodified = true; + } + if ($this->product->price_min_ttc != $oldproduct->price_min_ttc) { $pricemodified = true; + } + } else { + if ($this->product->price != $oldproduct->price) { $pricemodified = true; + } + if ($this->product->price_min != $oldproduct->price_min) { $pricemodified = true; + } + } + } + + if ($pricemodified) { + $newvat = $this->product->tva_tx; + $newnpr = $this->product->tva_npr; + $newvatsrccode = $this->product->default_vat_code; + + $newprice = $this->product->price; + $newpricemin = $this->product->price_min; + if ($this->product->price_base_type == 'TTC') { + $newprice = $this->product->price_ttc; + $newpricemin = $this->product->price_min_ttc; + } + + $result = $this->product->updatePrice($newprice, $this->product->price_base_type, DolibarrApiAccess::$user, $newvat, $newpricemin, 0, $newnpr, 0, 0, array(), $newvatsrccode); + } + } + + if ($result <= 0) { + throw new RestException(500, "Error updating product", array_merge(array($this->product->error), $this->product->errors)); + } + + return $this->get($id); + } + + /** + * Delete product + * + * @param int $id Product ID + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->produit->supprimer) { + throw new RestException(401); + } + $result = $this->product->fetch($id); + if (!$result) { + throw new RestException(404, 'Product not found'); + } + + if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + // The Product::delete() method uses the global variable $user. + global $user; + $user = DolibarrApiAccess::$user; + + return $this->product->delete(DolibarrApiAccess::$user); + } + + /** + * Get the list of subproducts of the product. + * + * @param int $id Id of parent product/service + * @return array + * + * @throws RestException + * @throws RestException 401 + * @throws RestException 404 + * + * @url GET {id}/subproducts + */ + public function getSubproducts($id) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } + + if (!DolibarrApi::_checkAccessToResource('product', $id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $childsArbo = $this->product->getChildsArbo($id, 1); + + $keys = ['rowid', 'qty', 'fk_product_type', 'label', 'incdec']; + $childs = []; + foreach ($childsArbo as $values) { + $childs[] = array_combine($keys, $values); + } + + return $childs; + } + + /** + * Add subproduct. + * + * Link a product/service to a parent product/service + * + * @param int $id Id of parent product/service + * @param int $subproduct_id Id of child product/service + * @param int $qty Quantity + * @param int $incdec 1=Increase/decrease stock of child when parent stock increase/decrease + * @return int + * + * @throws RestException + * @throws RestException 401 + * @throws RestException 404 + * + * @url POST {id}/subproducts/add + */ + public function addSubproducts($id, $subproduct_id, $qty, $incdec = 1) + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } + + if (!DolibarrApi::_checkAccessToResource('product', $id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->product->add_sousproduit($id, $subproduct_id, $qty, $incdec); + if ($result <= 0) { + throw new RestException(500, "Error adding product child"); + } + return $result; + } + + /** + * Remove subproduct. + * Unlink a product/service from a parent product/service + * + * @param int $id Id of parent product/service + * @param int $subproduct_id Id of child product/service + * @return int + * + * @throws RestException 401 + * @throws RestException 404 + * + * @url DELETE {id}/subproducts/remove/{subproduct_id} + */ + public function delSubproducts($id, $subproduct_id) + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } + + if (!DolibarrApi::_checkAccessToResource('product', $id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->product->del_sousproduit($id, $subproduct_id); + if ($result <= 0) { + throw new RestException(500, "Error while removing product child"); + } + return $result; + } + + + /** + * Get categories for a product + * + * @param int $id ID of product + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * + * @return mixed + * + * @url GET {id}/categories + */ + public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0) + { + if (!DolibarrApiAccess::$user->rights->categorie->lire) { + throw new RestException(401); + } + + $categories = new Categorie($this->db); + + $result = $categories->getListForItem($id, 'product', $sortfield, $sortorder, $limit, $page); + + if (empty($result)) { + throw new RestException(404, 'No category found'); + } + + if ($result < 0) { + throw new RestException(503, 'Error when retrieve category list : '.array_merge(array($categories->error), $categories->errors)); + } + + return $result; + } + + /** + * Get prices per segment for a product + * + * @param int $id ID of product + * + * @return mixed + * + * @url GET {id}/selling_multiprices/per_segment + */ + public function getCustomerPricesPerSegment($id) + { + global $conf; + + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } + + if (empty($conf->global->PRODUIT_MULTIPRICES)) { + throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup'); + } + + $result = $this->product->fetch($id); + if (!$result) { + throw new RestException(404, 'Product not found'); + } + + if ($result < 0) { + throw new RestException(503, 'Error when retrieve prices list : '.array_merge(array($this->product->error), $this->product->errors)); + } + + return array( + 'multiprices'=>$this->product->multiprices, + 'multiprices_inc_tax'=>$this->product->multiprices_ttc, + 'multiprices_min'=>$this->product->multiprices_min, + 'multiprices_min_inc_tax'=>$this->product->multiprices_min_ttc, + 'multiprices_vat'=>$this->product->multiprices_tva_tx, + 'multiprices_base_type'=>$this->product->multiprices_base_type, + //'multiprices_default_vat_code'=>$this->product->multiprices_default_vat_code + ); + } + + /** + * Get prices per customer for a product + * + * @param int $id ID of product + * @param string $thirdparty_id Thirdparty id to filter orders of (example '1') {@pattern /^[0-9,]*$/i} + * + * @return mixed + * + * @url GET {id}/selling_multiprices/per_customer + */ + public function getCustomerPricesPerCustomer($id, $thirdparty_id = '') + { + global $conf; + + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } + + if (empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { + throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup'); + } + + $result = $this->product->fetch($id); + if (!$result) { + throw new RestException(404, 'Product not found'); + } + + if ($result > 0) { + require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; + $prodcustprice = new Productcustomerprice($this->db); + $filter = array(); + $filter['t.fk_product'] .= $id; + if ($thirdparty_id) $filter['t.fk_soc'] .= $thirdparty_id; + $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); + } + + if (empty($prodcustprice->lines)) { + throw new RestException(404, 'Prices not found'); + } + + return $prodcustprice->lines; + } + + /** + * Get prices per quantity for a product + * + * @param int $id ID of product + * + * @return mixed + * + * @url GET {id}/selling_multiprices/per_quantity + */ + public function getCustomerPricesPerQuantity($id) + { + global $conf; + + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } + + if (empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { + throw new RestException(400, 'API not available: this mode of pricing is not enabled by setup'); + } + + $result = $this->product->fetch($id); + if (!$result) { + throw new RestException(404, 'Product not found'); + } + + if ($result < 0) { + throw new RestException(503, 'Error when retrieve prices list : '.array_merge(array($this->product->error), $this->product->errors)); + } + + return array( + 'prices_by_qty'=>$this->product->prices_by_qty[0], // 1 if price by quantity was activated for the product + 'prices_by_qty_list'=>$this->product->prices_by_qty_list[0] + ); + } + + /** + * Add/Update purchase prices for a product. + * + * @param int $id ID of Product + * @param float $qty Min quantity for which price is valid + * @param float $buyprice Purchase price for the quantity min + * @param string $price_base_type HT or TTC + * @param int $fourn_id Supplier ID + * @param int $availability Product availability + * @param string $ref_fourn Supplier ref + * @param float $tva_tx New VAT Rate (For example 8.5. Should not be a string) + * @param string $charges costs affering to product + * @param float $remise_percent Discount regarding qty (percent) + * @param float $remise Discount regarding qty (amount) + * @param int $newnpr Set NPR or not + * @param int $delivery_time_days Delay in days for delivery (max). May be '' if not defined. + * @param string $supplier_reputation Reputation with this product to the defined supplier (empty, FAVORITE, DONOTORDER) + * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function). + * @param string $newdefaultvatcode Default vat code + * @param float $multicurrency_buyprice Purchase price for the quantity min in currency + * @param string $multicurrency_price_base_type HT or TTC in currency + * @param float $multicurrency_tx Rate currency + * @param string $multicurrency_code Currency code + * @param string $desc_fourn Custom description for product_fourn_price + * @param string $barcode Barcode + * @param int $fk_barcode_type Barcode type + * @return int + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url POST {id}/purchase_prices + */ + public function addPurchasePrice($id, $qty, $buyprice, $price_base_type, $fourn_id, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = null) + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } + + $result = $this->productsupplier->fetch($id); + if (!$result) { + throw new RestException(404, 'Product not found'); + } + + if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $result = $this->productsupplier->add_fournisseur(DolibarrApiAccess::$user, $fourn_id, $ref_fourn, $qty); + if ($result < 0) { + throw new RestException(500, "Error adding supplier to product : ".$this->db->lasterror()); + } + + $fourn = new Fournisseur($this->db); + $result = $fourn->fetch($fourn_id); + if ($result <= 0) { + throw new RestException(404, 'Supplier not found'); + } + + $result = $this->productsupplier->update_buyprice($qty, $buyprice, DolibarrApiAccess::$user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges, $remise_percent, $remise, $newnpr, $delivery_time_days, $supplier_reputation, $localtaxes_array, $newdefaultvatcode, $multicurrency_buyprice, $multicurrency_price_base_type, $multicurrency_tx, $multicurrency_code, $desc_fourn, $barcode, $fk_barcode_type); + + if ($result <= 0) { + throw new RestException(500, "Error updating buy price : ".$this->db->lasterror()); + } + return (int) $this->productsupplier->product_fourn_price_id; + } + + /** + * Delete purchase price for a product + * + * @param int $id Product ID + * @param int $priceid purchase price ID + * + * @url DELETE {id}/purchase_prices/{priceid} + * + * @return int + * + * @throws RestException 401 + * @throws RestException 404 + * + */ + public function deletePurchasePrice($id, $priceid) + { + if (!DolibarrApiAccess::$user->rights->produit->supprimer) { + throw new RestException(401); + } + $result = $this->productsupplier->fetch($id); + if (!$result) { + throw new RestException(404, 'Product not found'); + } + + if (!DolibarrApi::_checkAccessToResource('product', $this->productsupplier->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $resultsupplier = 0; + if ($result > 0) { + $resultsupplier = $this->productsupplier->remove_product_fournisseur_price($priceid); + } + + return $resultsupplier; + } + + /** + * Get a list of all purchase prices of products + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param int $mode Use this param to filter list (0 for all, 1 for only product, 2 for only service) + * @param int $category Use this param to filter list by category of product + * @param int $supplier Use this param to filter list by supplier + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.tobuy:=:0) and (t.tosell:=:1)" + * @return array Array of product objects + * + * @url GET purchase_prices + */ + public function getSupplierProducts($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $mode = 0, $category = 0, $supplier = 0, $sqlfilters = '') + { + global $db, $conf; + + $obj_ret = array(); + + $socid = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : ''; + + $sql = "SELECT t.rowid, t.ref, t.ref_ext"; + $sql .= " FROM ".MAIN_DB_PREFIX."product as t"; + if ($category > 0) { + $sql .= ", ".MAIN_DB_PREFIX."categorie_product as c"; + } + $sql .= ", ".MAIN_DB_PREFIX."product_fournisseur_price as s"; + + $sql .= ' WHERE t.entity IN ('.getEntity('product').')'; + + if ($supplier > 0) { + $sql .= " AND s.fk_soc = ".$this->db->escape($supplier); + } + $sql .= " AND s.fk_product = t.rowid"; + // Select products of given category + if ($category > 0) { + $sql .= " AND c.fk_categorie = ".$this->db->escape($category); + $sql .= " AND c.fk_product = t.rowid"; + } + if ($mode == 1) { + // Show only products + $sql .= " AND t.fk_product_type = 0"; + } elseif ($mode == 2) { + // Show only services + $sql .= " AND t.fk_product_type = 1"; + } + // Add sql filters + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + $sql .= $this->db->plimit($limit + 1, $offset); + } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + $i = 0; + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + + $product_fourn = new ProductFournisseur($this->db); + $product_fourn_list = $product_fourn->list_product_fournisseur_price($obj->rowid, '', '', 0, 0); + foreach ($product_fourn_list as $tmpobj) { + $this->_cleanObjectDatas($tmpobj); + } + + //var_dump($product_fourn_list->db);exit; + $obj_ret[$obj->rowid] = $product_fourn_list; + + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve product list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No product found'); + } + return $obj_ret; + } + + /** + * Get purchase prices for a product + * + * Return an array with product information. + * TODO implement getting a product by ref or by $ref_ext + * + * @param int $id ID of product + * @param string $ref Ref of element + * @param string $ref_ext Ref ext of element + * @param string $barcode Barcode of element + * @return array|mixed Data without useless information + * + * @url GET {id}/purchase_prices + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + * + */ + public function getPurchasePrices($id, $ref = '', $ref_ext = '', $barcode = '') + { + if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) { + throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode'); + } + + $id = (empty($id) ? 0 : $id); + + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(403); + } + + $result = $this->product->fetch($id, $ref, $ref_ext, $barcode); + if (!$result) { + throw new RestException(404, 'Product not found'); + } + + if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + + $product_fourn_list = array(); + + if ($result) { + $product_fourn = new ProductFournisseur($this->db); + $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->product->id, '', '', 0, 0); + } + + foreach ($product_fourn_list as $tmpobj) { + $this->_cleanObjectDatas($tmpobj); + } + + return $this->_cleanObjectDatas($product_fourn_list); + } + + /** + * Get attributes. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:color)" + * @return array + * + * @throws RestException + * + * @url GET attributes + */ + public function getAttributes($sortfield = "t.ref", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '') + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } + + $sql = "SELECT t.rowid, t.ref, t.ref_ext, t.label, t.rang, t.entity"; + $sql .= " FROM ".MAIN_DB_PREFIX."product_attribute as t"; + $sql .= ' WHERE t.entity IN ('.getEntity('product').')'; + + // Add sql filters + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; + + $sql .= $this->db->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if (!$result) { + throw new RestException(503, 'Error when retrieve product attribute list : '.$this->db->lasterror()); + } + + $return = []; + while ($result = $this->db->fetch_object($query)) { + $tmp = new ProductAttribute($this->db); + $tmp->id = $result->rowid; + $tmp->ref = $result->ref; + $tmp->ref_ext = $result->ref_ext; + $tmp->label = $result->label; + $tmp->rang = $result->rang; + $tmp->entity = $result->entity; + + $return[] = $this->_cleanObjectDatas($tmp); + } + + if (!count($return)) { + throw new RestException(404, 'No product attribute found'); + } + + return $return; + } + + /** + * Get attribute by ID. + * + * @param int $id ID of Attribute + * @return array + * + * @throws RestException + * @throws RestException 401 + * @throws RestException 404 + * + * @url GET attributes/{id} + */ + public function getAttributeById($id) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } + + $prodattr = new ProductAttribute($this->db); + $result = $prodattr->fetch((int) $id); + + if ($result < 0) { + throw new RestException(404, "Product attribute not found"); + } + + $fields = ["id", "ref", "ref_ext", "label", "rang", "entity"]; + + foreach ($prodattr as $field => $value) { + if (!in_array($field, $fields)) { + unset($prodattr->{$field}); + } + } + + $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."product_attribute_combination2val as pac2v"; + $sql .= " JOIN ".MAIN_DB_PREFIX."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid"; + $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $prodattr->id)." AND pac.entity IN (".getEntity('product').")"; $resql = $this->db->query($sql); - $obj = $this->db->fetch_object($resql); - $prodattr->is_used_by_products = (int) $obj->nb; + $obj = $this->db->fetch_object($resql); + $prodattr->is_used_by_products = (int) $obj->nb; - return $prodattr; - } + return $prodattr; + } - /** - * Get attributes by ref. - * - * @param string $ref Reference of Attribute - * @return array - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url GET attributes/ref/{ref} - */ - public function getAttributesByRef($ref) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + /** + * Get attributes by ref. + * + * @param string $ref Reference of Attribute + * @return array + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url GET attributes/ref/{ref} + */ + public function getAttributesByRef($ref) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } - $sql = "SELECT rowid, ref, ref_ext, label, rang, entity FROM ".MAIN_DB_PREFIX."product_attribute WHERE ref LIKE '".trim($ref)."' AND entity IN (".getEntity('product').")"; + $sql = "SELECT rowid, ref, ref_ext, label, rang, entity FROM ".MAIN_DB_PREFIX."product_attribute WHERE ref LIKE '".trim($ref)."' AND entity IN (".getEntity('product').")"; - $query = $this->db->query($sql); + $query = $this->db->query($sql); - if (!$this->db->num_rows($query)) { - throw new RestException(404); - } + if (!$this->db->num_rows($query)) { + throw new RestException(404); + } - $result = $this->db->fetch_object($query); + $result = $this->db->fetch_object($query); - $attr = []; - $attr['id'] = $result->rowid; - $attr['ref'] = $result->ref; - $attr['ref_ext'] = $result->ref_ext; - $attr['label'] = $result->label; - $attr['rang'] = $result->rang; + $attr = []; + $attr['id'] = $result->rowid; + $attr['ref'] = $result->ref; + $attr['ref_ext'] = $result->ref_ext; + $attr['label'] = $result->label; + $attr['rang'] = $result->rang; $attr['entity'] = $result->entity; - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."product_attribute_combination2val as pac2v"; - $sql .= " JOIN ".MAIN_DB_PREFIX."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid"; - $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")"; + $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."product_attribute_combination2val as pac2v"; + $sql .= " JOIN ".MAIN_DB_PREFIX."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid"; + $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")"; $resql = $this->db->query($sql); - $obj = $this->db->fetch_object($resql); + $obj = $this->db->fetch_object($resql); - $attr["is_used_by_products"] = (int) $obj->nb; + $attr["is_used_by_products"] = (int) $obj->nb; - return $attr; - } + return $attr; + } - /** - * Get attributes by ref_ext. - * - * @param string $ref_ext External reference of Attribute - * @return array - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url GET attributes/ref_ext/{ref_ext} - */ - public function getAttributesByRefExt($ref_ext) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + /** + * Get attributes by ref_ext. + * + * @param string $ref_ext External reference of Attribute + * @return array + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url GET attributes/ref_ext/{ref_ext} + */ + public function getAttributesByRefExt($ref_ext) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } - $sql = "SELECT rowid, ref, ref_ext, label, rang, entity FROM ".MAIN_DB_PREFIX."product_attribute WHERE ref_ext LIKE '".trim($ref_ext)."' AND entity IN (".getEntity('product').")"; + $sql = "SELECT rowid, ref, ref_ext, label, rang, entity FROM ".MAIN_DB_PREFIX."product_attribute WHERE ref_ext LIKE '".trim($ref_ext)."' AND entity IN (".getEntity('product').")"; - $query = $this->db->query($sql); + $query = $this->db->query($sql); - if (!$this->db->num_rows($query)) { - throw new RestException(404); - } + if (!$this->db->num_rows($query)) { + throw new RestException(404); + } - $result = $this->db->fetch_object($query); + $result = $this->db->fetch_object($query); - $attr = []; - $attr['id'] = $result->rowid; - $attr['ref'] = $result->ref; - $attr['ref_ext'] = $result->ref_ext; - $attr['label'] = $result->label; - $attr['rang'] = $result->rang; + $attr = []; + $attr['id'] = $result->rowid; + $attr['ref'] = $result->ref; + $attr['ref_ext'] = $result->ref_ext; + $attr['label'] = $result->label; + $attr['rang'] = $result->rang; $attr['entity'] = $result->entity; - $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."product_attribute_combination2val as pac2v"; - $sql .= " JOIN ".MAIN_DB_PREFIX."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid"; - $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")"; + $sql = "SELECT COUNT(*) as nb FROM ".MAIN_DB_PREFIX."product_attribute_combination2val as pac2v"; + $sql .= " JOIN ".MAIN_DB_PREFIX."product_attribute_combination as pac ON pac2v.fk_prod_combination = pac.rowid"; + $sql .= " WHERE pac2v.fk_prod_attr = ".((int) $result->rowid)." AND pac.entity IN (".getEntity('product').")"; $resql = $this->db->query($sql); - $obj = $this->db->fetch_object($resql); - $attr["is_used_by_products"] = (int) $obj->nb; + $obj = $this->db->fetch_object($resql); + $attr["is_used_by_products"] = (int) $obj->nb; - return $attr; - } + return $attr; + } - /** - * Add attributes. - * - * @param string $ref Reference of Attribute - * @param string $label Label of Attribute - * @param string $ref_ext Reference of Attribute - * @return int - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url POST attributes - */ - public function addAttributes($ref, $label, $ref_ext = '') - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } + /** + * Add attributes. + * + * @param string $ref Reference of Attribute + * @param string $label Label of Attribute + * @param string $ref_ext Reference of Attribute + * @return int + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url POST attributes + */ + public function addAttributes($ref, $label, $ref_ext = '') + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } - $prodattr = new ProductAttribute($this->db); - $prodattr->label = $label; - $prodattr->ref = $ref; - $prodattr->ref_ext = $ref_ext; + $prodattr = new ProductAttribute($this->db); + $prodattr->label = $label; + $prodattr->ref = $ref; + $prodattr->ref_ext = $ref_ext; - $resid = $prodattr->create(DolibarrApiAccess::$user); - if ($resid <= 0) { - throw new RestException(500, "Error creating new attribute"); - } - return $resid; - } + $resid = $prodattr->create(DolibarrApiAccess::$user); + if ($resid <= 0) { + throw new RestException(500, "Error creating new attribute"); + } + return $resid; + } - /** - * Update attributes by id. - * - * @param int $id ID of Attribute - * @param array $request_data Datas - * @return array - * - * @throws RestException - * @throws RestException 401 - * @throws RestException 404 - * - * @url PUT attributes/{id} - */ - public function putAttributes($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } + /** + * Update attributes by id. + * + * @param int $id ID of Attribute + * @param array $request_data Datas + * @return array + * + * @throws RestException + * @throws RestException 401 + * @throws RestException 404 + * + * @url PUT attributes/{id} + */ + public function putAttributes($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } - $prodattr = new ProductAttribute($this->db); + $prodattr = new ProductAttribute($this->db); - $result = $prodattr->fetch((int) $id); - if ($result == 0) { - throw new RestException(404, 'Attribute not found'); - } elseif ($result < 0) { - throw new RestException(500, "Error fetching attribute"); - } + $result = $prodattr->fetch((int) $id); + if ($result == 0) { + throw new RestException(404, 'Attribute not found'); + } elseif ($result < 0) { + throw new RestException(500, "Error fetching attribute"); + } - foreach ($request_data as $field => $value) { - if ($field == 'rowid') { continue; - } - $prodattr->$field = $value; - } + foreach ($request_data as $field => $value) { + if ($field == 'rowid') { continue; + } + $prodattr->$field = $value; + } - if ($prodattr->update(DolibarrApiAccess::$user) > 0) { - $result = $prodattr->fetch((int) $id); - if ($result == 0) { - throw new RestException(404, 'Attribute not found'); - } elseif ($result < 0) { - throw new RestException(500, "Error fetching attribute"); - } else { - return $prodattr; - } - } - throw new RestException(500, "Error updating attribute"); - } + if ($prodattr->update(DolibarrApiAccess::$user) > 0) { + $result = $prodattr->fetch((int) $id); + if ($result == 0) { + throw new RestException(404, 'Attribute not found'); + } elseif ($result < 0) { + throw new RestException(500, "Error fetching attribute"); + } else { + return $prodattr; + } + } + throw new RestException(500, "Error updating attribute"); + } - /** - * Delete attributes by id. - * - * @param int $id ID of Attribute - * @return int Result of deletion - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url DELETE attributes/{id} - */ - public function deleteAttributes($id) - { - if (!DolibarrApiAccess::$user->rights->produit->supprimer) { - throw new RestException(401); - } + /** + * Delete attributes by id. + * + * @param int $id ID of Attribute + * @return int Result of deletion + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url DELETE attributes/{id} + */ + public function deleteAttributes($id) + { + if (!DolibarrApiAccess::$user->rights->produit->supprimer) { + throw new RestException(401); + } - $prodattr = new ProductAttribute($this->db); - $prodattr->id = (int) $id; - $result = $prodattr->delete(DolibarrApiAccess::$user); + $prodattr = new ProductAttribute($this->db); + $prodattr->id = (int) $id; + $result = $prodattr->delete(DolibarrApiAccess::$user); - if ($result <= 0) { - throw new RestException(500, "Error deleting attribute"); - } + if ($result <= 0) { + throw new RestException(500, "Error deleting attribute"); + } - return $result; - } + return $result; + } - /** - * Get attribute value by id. - * - * @param int $id ID of Attribute value - * @return array - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url GET attributes/values/{id} - */ - public function getAttributeValueById($id) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + /** + * Get attribute value by id. + * + * @param int $id ID of Attribute value + * @return array + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url GET attributes/values/{id} + */ + public function getAttributeValueById($id) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } - $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE rowid = ".(int) $id." AND entity IN (".getEntity('product').")"; + $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE rowid = ".(int) $id." AND entity IN (".getEntity('product').")"; - $query = $this->db->query($sql); + $query = $this->db->query($sql); - if (!$query) { - throw new RestException(401); - } + if (!$query) { + throw new RestException(401); + } - if (!$this->db->num_rows($query)) { - throw new RestException(404, 'Attribute value not found'); - } + if (!$this->db->num_rows($query)) { + throw new RestException(404, 'Attribute value not found'); + } - $result = $this->db->fetch_object($query); + $result = $this->db->fetch_object($query); - $attrval = []; - $attrval['id'] = $result->rowid; - $attrval['fk_product_attribute'] = $result->fk_product_attribute; - $attrval['ref'] = $result->ref; - $attrval['value'] = $result->value; + $attrval = []; + $attrval['id'] = $result->rowid; + $attrval['fk_product_attribute'] = $result->fk_product_attribute; + $attrval['ref'] = $result->ref; + $attrval['value'] = $result->value; - return $attrval; - } + return $attrval; + } - /** - * Get attribute value by ref. - * - * @param int $id ID of Attribute value - * @param string $ref Ref of Attribute value - * @return array - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url GET attributes/{id}/values/ref/{ref} - */ - public function getAttributeValueByRef($id, $ref) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + /** + * Get attribute value by ref. + * + * @param int $id ID of Attribute value + * @param string $ref Ref of Attribute value + * @return array + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url GET attributes/{id}/values/ref/{ref} + */ + public function getAttributeValueByRef($id, $ref) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } - $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE ref LIKE '".trim($ref)."' AND fk_product_attribute = ".(int) $id." AND entity IN (".getEntity('product').")"; + $sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE ref LIKE '".trim($ref)."' AND fk_product_attribute = ".(int) $id." AND entity IN (".getEntity('product').")"; - $query = $this->db->query($sql); + $query = $this->db->query($sql); - if (!$query) { - throw new RestException(401); - } + if (!$query) { + throw new RestException(401); + } - if (!$this->db->num_rows($query)) { - throw new RestException(404, 'Attribute value not found'); - } + if (!$this->db->num_rows($query)) { + throw new RestException(404, 'Attribute value not found'); + } - $result = $this->db->fetch_object($query); + $result = $this->db->fetch_object($query); - $attrval = []; - $attrval['id'] = $result->rowid; - $attrval['fk_product_attribute'] = $result->fk_product_attribute; - $attrval['ref'] = $result->ref; - $attrval['value'] = $result->value; + $attrval = []; + $attrval['id'] = $result->rowid; + $attrval['fk_product_attribute'] = $result->fk_product_attribute; + $attrval['ref'] = $result->ref; + $attrval['value'] = $result->value; - return $attrval; - } + return $attrval; + } - /** - * Delete attribute value by ref. - * - * @param int $id ID of Attribute - * @param string $ref Ref of Attribute value - * @return int - * - * @throws RestException 401 - * - * @url DELETE attributes/{id}/values/ref/{ref} - */ - public function deleteAttributeValueByRef($id, $ref) - { - if (!DolibarrApiAccess::$user->rights->produit->supprimer) { - throw new RestException(401); - } + /** + * Delete attribute value by ref. + * + * @param int $id ID of Attribute + * @param string $ref Ref of Attribute value + * @return int + * + * @throws RestException 401 + * + * @url DELETE attributes/{id}/values/ref/{ref} + */ + public function deleteAttributeValueByRef($id, $ref) + { + if (!DolibarrApiAccess::$user->rights->produit->supprimer) { + throw new RestException(401); + } - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE ref LIKE '".trim($ref)."' AND fk_product_attribute = ".(int) $id." AND entity IN (".getEntity('product').")"; - $query = $this->db->query($sql); + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE ref LIKE '".trim($ref)."' AND fk_product_attribute = ".(int) $id." AND entity IN (".getEntity('product').")"; + $query = $this->db->query($sql); - if (!$query) { - throw new RestException(401); - } + if (!$query) { + throw new RestException(401); + } - if (!$this->db->num_rows($query)) { - throw new RestException(404, 'Attribute value not found'); - } + if (!$this->db->num_rows($query)) { + throw new RestException(404, 'Attribute value not found'); + } - $result = $this->db->fetch_object($query); + $result = $this->db->fetch_object($query); - $attrval = new ProductAttributeValue($this->db); - $attrval->id = $result->rowid; - $result = $attrval->delete(DolibarrApiAccess::$user); - if ($result > 0) { - return 1; - } + $attrval = new ProductAttributeValue($this->db); + $attrval->id = $result->rowid; + $result = $attrval->delete(DolibarrApiAccess::$user); + if ($result > 0) { + return 1; + } - throw new RestException(500, "Error deleting attribute value"); - } + throw new RestException(500, "Error deleting attribute value"); + } - /** - * Get all values for an attribute id. - * - * @param int $id ID of an Attribute - * @return array - * - * @throws RestException 401 - * @throws RestException 500 - * - * @url GET attributes/{id}/values - */ - public function getAttributeValues($id) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + /** + * Get all values for an attribute id. + * + * @param int $id ID of an Attribute + * @return array + * + * @throws RestException 401 + * @throws RestException 500 + * + * @url GET attributes/{id}/values + */ + public function getAttributeValues($id) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } - $objectval = new ProductAttributeValue($this->db); + $objectval = new ProductAttributeValue($this->db); - $return = $objectval->fetchAllByProductAttribute((int) $id); + $return = $objectval->fetchAllByProductAttribute((int) $id); - if (count($return) == 0) { - throw new RestException(404, 'Attribute values not found'); - } + if (count($return) == 0) { + throw new RestException(404, 'Attribute values not found'); + } foreach ($return as $key => $val) { $return[$key] = $this->_cleanObjectDatas($return[$key]); - } + } - return $return; - } + return $return; + } - /** - * Get all values for an attribute ref. - * - * @param string $ref Ref of an Attribute - * @return array - * - * @throws RestException 401 - * - * @url GET attributes/ref/{ref}/values - */ - public function getAttributeValuesByRef($ref) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + /** + * Get all values for an attribute ref. + * + * @param string $ref Ref of an Attribute + * @return array + * + * @throws RestException 401 + * + * @url GET attributes/ref/{ref}/values + */ + public function getAttributeValuesByRef($ref) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } - $return = array(); + $return = array(); - $sql = 'SELECT '; - $sql .= 'v.fk_product_attribute, v.rowid, v.ref, v.value FROM '.MAIN_DB_PREFIX.'product_attribute_value as v'; - $sql .= " WHERE v.fk_product_attribute IN (SELECT rowid FROM ".MAIN_DB_PREFIX."product_attribute WHERE ref LIKE '".$this->db->escape(trim($ref))."')"; + $sql = 'SELECT '; + $sql .= 'v.fk_product_attribute, v.rowid, v.ref, v.value FROM '.MAIN_DB_PREFIX.'product_attribute_value as v'; + $sql .= " WHERE v.fk_product_attribute IN (SELECT rowid FROM ".MAIN_DB_PREFIX."product_attribute WHERE ref LIKE '".$this->db->escape(trim($ref))."')"; - $resql = $this->db->query($sql); + $resql = $this->db->query($sql); - while ($result = $this->db->fetch_object($resql)) { - $tmp = new ProductAttributeValue($this->db); - $tmp->fk_product_attribute = $result->fk_product_attribute; - $tmp->id = $result->rowid; - $tmp->ref = $result->ref; - $tmp->value = $result->value; + while ($result = $this->db->fetch_object($resql)) { + $tmp = new ProductAttributeValue($this->db); + $tmp->fk_product_attribute = $result->fk_product_attribute; + $tmp->id = $result->rowid; + $tmp->ref = $result->ref; + $tmp->value = $result->value; - $return[] = $this->_cleanObjectDatas($tmp); - } + $return[] = $this->_cleanObjectDatas($tmp); + } - return $return; - } + return $return; + } - /** - * Add attribute value. - * - * @param int $id ID of Attribute - * @param string $ref Reference of Attribute value - * @param string $value Value of Attribute value - * @return int - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url POST attributes/{id}/values - */ - public function addAttributeValue($id, $ref, $value) - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } + /** + * Add attribute value. + * + * @param int $id ID of Attribute + * @param string $ref Reference of Attribute value + * @param string $value Value of Attribute value + * @return int + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url POST attributes/{id}/values + */ + public function addAttributeValue($id, $ref, $value) + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } - if (empty($ref) || empty($value)) { - throw new RestException(401); - } + if (empty($ref) || empty($value)) { + throw new RestException(401); + } - $objectval = new ProductAttributeValue($this->db); - $objectval->fk_product_attribute = $id; - $objectval->ref = $ref; - $objectval->value = $value; + $objectval = new ProductAttributeValue($this->db); + $objectval->fk_product_attribute = $id; + $objectval->ref = $ref; + $objectval->value = $value; - if ($objectval->create(DolibarrApiAccess::$user) > 0) { - return $objectval->id; - } - throw new RestException(500, "Error creating new attribute value"); - } + if ($objectval->create(DolibarrApiAccess::$user) > 0) { + return $objectval->id; + } + throw new RestException(500, "Error creating new attribute value"); + } - /** - * Update attribute value. - * - * @param int $id ID of Attribute - * @param array $request_data Datas - * @return array - * - * @throws RestException 401 - * @throws RestException 500 - * - * @url PUT attributes/values/{id} - */ - public function putAttributeValue($id, $request_data) - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } + /** + * Update attribute value. + * + * @param int $id ID of Attribute + * @param array $request_data Datas + * @return array + * + * @throws RestException 401 + * @throws RestException 500 + * + * @url PUT attributes/values/{id} + */ + public function putAttributeValue($id, $request_data) + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } - $objectval = new ProductAttributeValue($this->db); - $result = $objectval->fetch((int) $id); + $objectval = new ProductAttributeValue($this->db); + $result = $objectval->fetch((int) $id); - if ($result == 0) { - throw new RestException(404, 'Attribute value not found'); - } elseif ($result < 0) { - throw new RestException(500, "Error fetching attribute value"); - } + if ($result == 0) { + throw new RestException(404, 'Attribute value not found'); + } elseif ($result < 0) { + throw new RestException(500, "Error fetching attribute value"); + } - foreach ($request_data as $field => $value) { - if ($field == 'rowid') { continue; - } - $objectval->$field = $value; - } + foreach ($request_data as $field => $value) { + if ($field == 'rowid') { continue; + } + $objectval->$field = $value; + } - if ($objectval->update(DolibarrApiAccess::$user) > 0) { - $result = $objectval->fetch((int) $id); - if ($result == 0) { - throw new RestException(404, 'Attribute not found'); - } elseif ($result < 0) { - throw new RestException(500, "Error fetching attribute"); - } else { - return $objectval; - } - } - throw new RestException(500, "Error updating attribute"); - } + if ($objectval->update(DolibarrApiAccess::$user) > 0) { + $result = $objectval->fetch((int) $id); + if ($result == 0) { + throw new RestException(404, 'Attribute not found'); + } elseif ($result < 0) { + throw new RestException(500, "Error fetching attribute"); + } else { + return $objectval; + } + } + throw new RestException(500, "Error updating attribute"); + } - /** - * Delete attribute value by id. - * - * @param int $id ID of Attribute value - * @return int - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url DELETE attributes/values/{id} - */ - public function deleteAttributeValueById($id) - { - if (!DolibarrApiAccess::$user->rights->produit->supprimer) { - throw new RestException(401); - } + /** + * Delete attribute value by id. + * + * @param int $id ID of Attribute value + * @return int + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url DELETE attributes/values/{id} + */ + public function deleteAttributeValueById($id) + { + if (!DolibarrApiAccess::$user->rights->produit->supprimer) { + throw new RestException(401); + } - $objectval = new ProductAttributeValue($this->db); - $objectval->id = (int) $id; + $objectval = new ProductAttributeValue($this->db); + $objectval->id = (int) $id; - if ($objectval->delete(DolibarrApiAccess::$user) > 0) { - return 1; - } - throw new RestException(500, "Error deleting attribute value"); - } + if ($objectval->delete(DolibarrApiAccess::$user) > 0) { + return 1; + } + throw new RestException(500, "Error deleting attribute value"); + } - /** - * Get product variants. - * - * @param int $id ID of Product - * @return array - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url GET {id}/variants - */ - public function getVariants($id) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + /** + * Get product variants. + * + * @param int $id ID of Product + * @return array + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url GET {id}/variants + */ + public function getVariants($id) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } - $prodcomb = new ProductCombination($this->db); - $combinations = $prodcomb->fetchAllByFkProductParent((int) $id); + $prodcomb = new ProductCombination($this->db); + $combinations = $prodcomb->fetchAllByFkProductParent((int) $id); - foreach ($combinations as $key => $combination) { - $prodc2vp = new ProductCombination2ValuePair($this->db); - $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id); - } + foreach ($combinations as $key => $combination) { + $prodc2vp = new ProductCombination2ValuePair($this->db); + $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id); + } - return $combinations; - } + return $combinations; + } - /** - * Get product variants by Product ref. - * - * @param string $ref Ref of Product - * @return array - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url GET ref/{ref}/variants - */ - public function getVariantsByProdRef($ref) - { - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(401); - } + /** + * Get product variants by Product ref. + * + * @param string $ref Ref of Product + * @return array + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url GET ref/{ref}/variants + */ + public function getVariantsByProdRef($ref) + { + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(401); + } - $result = $this->product->fetch('', $ref); - if (!$result) { - throw new RestException(404, 'Product not found'); - } + $result = $this->product->fetch('', $ref); + if (!$result) { + throw new RestException(404, 'Product not found'); + } - $prodcomb = new ProductCombination($this->db); - $combinations = $prodcomb->fetchAllByFkProductParent((int) $this->product->id); + $prodcomb = new ProductCombination($this->db); + $combinations = $prodcomb->fetchAllByFkProductParent((int) $this->product->id); - foreach ($combinations as $key => $combination) { - $prodc2vp = new ProductCombination2ValuePair($this->db); - $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id); - } + foreach ($combinations as $key => $combination) { + $prodc2vp = new ProductCombination2ValuePair($this->db); + $combinations[$key]->attributes = $prodc2vp->fetchByFkCombination((int) $combination->id); + } - return $combinations; - } + return $combinations; + } - /** - * Add variant. - * - * "features" is a list of attributes pairs id_attribute=>id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) - * - * @param int $id ID of Product - * @param float $weight_impact Weight impact of variant - * @param float $price_impact Price impact of variant - * @param bool $price_impact_is_percent Price impact in percent (true or false) - * @param array $features List of attributes pairs id_attribute->id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) - * @param string $reference Customized reference of variant - * @param string $ref_ext External reference of variant - * @return int - * - * @throws RestException 500 - * @throws RestException 401 - * @throws RestException 404 - * - * @url POST {id}/variants - */ - public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference = '', $ref_ext = '') - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } + /** + * Add variant. + * + * "features" is a list of attributes pairs id_attribute=>id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) + * + * @param int $id ID of Product + * @param float $weight_impact Weight impact of variant + * @param float $price_impact Price impact of variant + * @param bool $price_impact_is_percent Price impact in percent (true or false) + * @param array $features List of attributes pairs id_attribute->id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) + * @param string $reference Customized reference of variant + * @param string $ref_ext External reference of variant + * @return int + * + * @throws RestException 500 + * @throws RestException 401 + * @throws RestException 404 + * + * @url POST {id}/variants + */ + public function addVariant($id, $weight_impact, $price_impact, $price_impact_is_percent, $features, $reference = '', $ref_ext = '') + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } - if (empty($id) || empty($features) || !is_array($features)) { - throw new RestException(401); - } + if (empty($id) || empty($features) || !is_array($features)) { + throw new RestException(401); + } - $weight_impact = price2num($weight_impact); - $price_impact = price2num($price_impact); + $weight_impact = price2num($weight_impact); + $price_impact = price2num($price_impact); - $prodattr = new ProductAttribute($this->db); - $prodattr_val = new ProductAttributeValue($this->db); - foreach ($features as $id_attr => $id_value) { - if ($prodattr->fetch((int) $id_attr) < 0) { - throw new RestException(401); - } - if ($prodattr_val->fetch((int) $id_value) < 0) { - throw new RestException(401); - } - } + $prodattr = new ProductAttribute($this->db); + $prodattr_val = new ProductAttributeValue($this->db); + foreach ($features as $id_attr => $id_value) { + if ($prodattr->fetch((int) $id_attr) < 0) { + throw new RestException(401); + } + if ($prodattr_val->fetch((int) $id_value) < 0) { + throw new RestException(401); + } + } - $result = $this->product->fetch((int) $id); - if (!$result) { - throw new RestException(404, 'Product not found'); - } + $result = $this->product->fetch((int) $id); + if (!$result) { + throw new RestException(404, 'Product not found'); + } - $prodcomb = new ProductCombination($this->db); + $prodcomb = new ProductCombination($this->db); - $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext); - if ($result > 0) - { - return $result; - } else { - throw new RestException(500, "Error creating new product variant"); - } - } + $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact, $reference, $ref_ext); + if ($result > 0) + { + return $result; + } else { + throw new RestException(500, "Error creating new product variant"); + } + } - /** - * Add variant by product ref. - * - * "features" is a list of attributes pairs id_attribute=>id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) - * - * @param string $ref Ref of Product - * @param float $weight_impact Weight impact of variant - * @param float $price_impact Price impact of variant - * @param bool $price_impact_is_percent Price impact in percent (true or false) - * @param array $features List of attributes pairs id_attribute->id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) - * @return int - * - * @throws RestException 500 - * @throws RestException 401 - * @throws RestException 404 - * - * @url POST ref/{ref}/variants - */ - public function addVariantByProductRef($ref, $weight_impact, $price_impact, $price_impact_is_percent, $features) - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } + /** + * Add variant by product ref. + * + * "features" is a list of attributes pairs id_attribute=>id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) + * + * @param string $ref Ref of Product + * @param float $weight_impact Weight impact of variant + * @param float $price_impact Price impact of variant + * @param bool $price_impact_is_percent Price impact in percent (true or false) + * @param array $features List of attributes pairs id_attribute->id_value. Example: array(id_color=>id_Blue, id_size=>id_small, id_option=>id_val_a, ...) + * @return int + * + * @throws RestException 500 + * @throws RestException 401 + * @throws RestException 404 + * + * @url POST ref/{ref}/variants + */ + public function addVariantByProductRef($ref, $weight_impact, $price_impact, $price_impact_is_percent, $features) + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } - if (empty($ref) || empty($features) || !is_array($features)) { - throw new RestException(401); - } + if (empty($ref) || empty($features) || !is_array($features)) { + throw new RestException(401); + } - $weight_impact = price2num($weight_impact); - $price_impact = price2num($price_impact); + $weight_impact = price2num($weight_impact); + $price_impact = price2num($price_impact); - $prodattr = new ProductAttribute($this->db); - $prodattr_val = new ProductAttributeValue($this->db); - foreach ($features as $id_attr => $id_value) { - if ($prodattr->fetch((int) $id_attr) < 0) { - throw new RestException(404); - } - if ($prodattr_val->fetch((int) $id_value) < 0) { - throw new RestException(404); - } - } + $prodattr = new ProductAttribute($this->db); + $prodattr_val = new ProductAttributeValue($this->db); + foreach ($features as $id_attr => $id_value) { + if ($prodattr->fetch((int) $id_attr) < 0) { + throw new RestException(404); + } + if ($prodattr_val->fetch((int) $id_value) < 0) { + throw new RestException(404); + } + } - $result = $this->product->fetch('', trim($ref)); - if (!$result) { - throw new RestException(404, 'Product not found'); - } + $result = $this->product->fetch('', trim($ref)); + if (!$result) { + throw new RestException(404, 'Product not found'); + } - $prodcomb = new ProductCombination($this->db); - if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) - { - $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact); - if ($result > 0) - { - return $result; - } else { - throw new RestException(500, "Error creating new product variant"); - } - } else { - return $prodcomb->id; - } - } + $prodcomb = new ProductCombination($this->db); + if (!$prodcomb->fetchByProductCombination2ValuePairs($this->product->id, $features)) + { + $result = $prodcomb->createProductCombination(DolibarrApiAccess::$user, $this->product, $features, array(), $price_impact_is_percent, $price_impact, $weight_impact); + if ($result > 0) + { + return $result; + } else { + throw new RestException(500, "Error creating new product variant"); + } + } else { + return $prodcomb->id; + } + } - /** - * Put product variants. - * - * @param int $id ID of Variant - * @param array $request_data Datas - * @return int - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url PUT variants/{id} - */ - public function putVariant($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->produit->creer) { - throw new RestException(401); - } + /** + * Put product variants. + * + * @param int $id ID of Variant + * @param array $request_data Datas + * @return int + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url PUT variants/{id} + */ + public function putVariant($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->produit->creer) { + throw new RestException(401); + } - $prodcomb = new ProductCombination($this->db); - $prodcomb->fetch((int) $id); + $prodcomb = new ProductCombination($this->db); + $prodcomb->fetch((int) $id); - foreach ($request_data as $field => $value) { - if ($field == 'rowid') { continue; - } - $prodcomb->$field = $value; - } + foreach ($request_data as $field => $value) { + if ($field == 'rowid') { continue; + } + $prodcomb->$field = $value; + } - $result = $prodcomb->update(DolibarrApiAccess::$user); - if ($result > 0) - { - return 1; - } - throw new RestException(500, "Error editing variant"); - } + $result = $prodcomb->update(DolibarrApiAccess::$user); + if ($result > 0) + { + return 1; + } + throw new RestException(500, "Error editing variant"); + } - /** - * Delete product variants. - * - * @param int $id ID of Variant - * @return int Result of deletion - * - * @throws RestException 500 - * @throws RestException 401 - * - * @url DELETE variants/{id} - */ - public function deleteVariant($id) - { - if (!DolibarrApiAccess::$user->rights->produit->supprimer) { - throw new RestException(401); - } + /** + * Delete product variants. + * + * @param int $id ID of Variant + * @return int Result of deletion + * + * @throws RestException 500 + * @throws RestException 401 + * + * @url DELETE variants/{id} + */ + public function deleteVariant($id) + { + if (!DolibarrApiAccess::$user->rights->produit->supprimer) { + throw new RestException(401); + } - $prodcomb = new ProductCombination($this->db); - $prodcomb->id = (int) $id; - $result = $prodcomb->delete(DolibarrApiAccess::$user); - if ($result <= 0) - { - throw new RestException(500, "Error deleting variant"); - } - return $result; - } + $prodcomb = new ProductCombination($this->db); + $prodcomb->id = (int) $id; + $result = $prodcomb->delete(DolibarrApiAccess::$user); + if ($result <= 0) + { + throw new RestException(500, "Error deleting variant"); + } + return $result; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->regeximgext); - unset($object->price_by_qty); - unset($object->prices_by_qty_id); - unset($object->libelle); - unset($object->product_id_already_linked); - unset($object->reputations); + unset($object->regeximgext); + unset($object->price_by_qty); + unset($object->prices_by_qty_id); + unset($object->libelle); + unset($object->product_id_already_linked); + unset($object->reputations); - unset($object->name); - unset($object->firstname); - unset($object->lastname); - unset($object->civility_id); + unset($object->name); + unset($object->firstname); + unset($object->lastname); + unset($object->civility_id); - unset($object->recuperableonly); + unset($object->recuperableonly); - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array $data Datas to validate - * @return array - * @throws RestException - */ - private function _validate($data) - { - $product = array(); - foreach (Products::$FIELDS as $field) { - if (!isset($data[$field])) { - throw new RestException(400, "$field field missing"); - } - $product[$field] = $data[$field]; - } - return $product; - } + /** + * Validate fields before create or update object + * + * @param array $data Datas to validate + * @return array + * @throws RestException + */ + private function _validate($data) + { + $product = array(); + foreach (Products::$FIELDS as $field) { + if (!isset($data[$field])) { + throw new RestException(400, "$field field missing"); + } + $product[$field] = $data[$field]; + } + return $product; + } - /** - * Get properties of a product object - * - * Return an array with product information. - * - * @param int $id ID of product - * @param string $ref Ref of element - * @param string $ref_ext Ref ext of element - * @param string $barcode Barcode of element - * @param int $includestockdata Load also information about stock (slower) - * @param bool $includesubproducts Load information about subproducts (if product is a virtual product) + /** + * Get properties of a product object + * + * Return an array with product information. + * + * @param int $id ID of product + * @param string $ref Ref of element + * @param string $ref_ext Ref ext of element + * @param string $barcode Barcode of element + * @param int $includestockdata Load also information about stock (slower) + * @param bool $includesubproducts Load information about subproducts (if product is a virtual product) * @param bool $includeparentid Load also ID of parent product (if product is a variant of a parent product) - * @return array|mixed Data without useless information - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false) - { - if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) { - throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode'); - } + * @return array|mixed Data without useless information + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + private function _fetch($id, $ref = '', $ref_ext = '', $barcode = '', $includestockdata = 0, $includesubproducts = false, $includeparentid = false) + { + if (empty($id) && empty($ref) && empty($ref_ext) && empty($barcode)) { + throw new RestException(400, 'bad value for parameter id, ref, ref_ext or barcode'); + } - $id = (empty($id) ? 0 : $id); + $id = (empty($id) ? 0 : $id); - if (!DolibarrApiAccess::$user->rights->produit->lire) { - throw new RestException(403); - } + if (!DolibarrApiAccess::$user->rights->produit->lire) { + throw new RestException(403); + } - $result = $this->product->fetch($id, $ref, $ref_ext, $barcode); - if (!$result) { - throw new RestException(404, 'Product not found'); - } + $result = $this->product->fetch($id, $ref, $ref_ext, $barcode); + if (!$result) { + throw new RestException(404, 'Product not found'); + } - if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('product', $this->product->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if ($includestockdata) { - $this->product->load_stock(); + if ($includestockdata) { + $this->product->load_stock(); - if (is_array($this->product->stock_warehouse)) { - foreach ($this->product->stock_warehouse as $keytmp => $valtmp) { - if (is_array($this->product->stock_warehouse[$keytmp]->detail_batch)) { - foreach ($this->product->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) { - unset($this->product->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db); - } - } - } - } - } + if (is_array($this->product->stock_warehouse)) { + foreach ($this->product->stock_warehouse as $keytmp => $valtmp) { + if (is_array($this->product->stock_warehouse[$keytmp]->detail_batch)) { + foreach ($this->product->stock_warehouse[$keytmp]->detail_batch as $keytmp2 => $valtmp2) { + unset($this->product->stock_warehouse[$keytmp]->detail_batch[$keytmp2]->db); + } + } + } + } + } - if ($includesubproducts) { - $childsArbo = $this->product->getChildsArbo($id, 1); + if ($includesubproducts) { + $childsArbo = $this->product->getChildsArbo($id, 1); - $keys = ['rowid', 'qty', 'fk_product_type', 'label', 'incdec']; - $childs = []; - foreach ($childsArbo as $values) { - $childs[] = array_combine($keys, $values); - } + $keys = ['rowid', 'qty', 'fk_product_type', 'label', 'incdec']; + $childs = []; + foreach ($childsArbo as $values) { + $childs[] = array_combine($keys, $values); + } - $this->product->sousprods = $childs; - } + $this->product->sousprods = $childs; + } if ($includeparentid) { $prodcomb = new ProductCombination($this->db); diff --git a/htdocs/product/fournisseurs.php b/htdocs/product/fournisseurs.php index 816e0db41c0..ef3da905990 100644 --- a/htdocs/product/fournisseurs.php +++ b/htdocs/product/fournisseurs.php @@ -1040,16 +1040,16 @@ SCRIPT; // Unit price in currency if (!empty($arrayfields['pfp.multicurrency_unitprice']['checked'])) { - print ''; } + print ''; } // Currency - if ($conf->multicurrency->enabled) { - print ''; - } + if ($conf->multicurrency->enabled) { + print ''; + } // Discount print ''; } - // Units - if (!empty($conf->global->PRODUCT_USE_UNITS)) { - print ''; - } + // Units + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + print ''; + } print ''; print ''; - print ''; + print ''; // Fields from hook $parameters = array('obj'=>$objp); $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print ''; - print "\n"; + print "\n"; $i++; } diff --git a/htdocs/product/stock/class/api_stockmovements.class.php b/htdocs/product/stock/class/api_stockmovements.class.php index a0b4d956942..dba209e5b6f 100644 --- a/htdocs/product/stock/class/api_stockmovements.class.php +++ b/htdocs/product/stock/class/api_stockmovements.class.php @@ -272,79 +272,79 @@ class StockMovements extends DolibarrApi - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param MouvementStock $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param MouvementStock $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - // Remove useless data - unset($object->civility_id); - unset($object->firstname); - unset($object->lastname); - unset($object->name); - unset($object->location_incoterms); - unset($object->label_incoterms); - unset($object->fk_incoterms); - unset($object->lines); - unset($object->total_ht); - unset($object->total_ttc); - unset($object->total_tva); - unset($object->total_localtax1); - unset($object->total_localtax2); - unset($object->note); - unset($object->note_private); - unset($object->note_public); - unset($object->shipping_method_id); - unset($object->fk_account); - unset($object->model_pdf); - unset($object->fk_delivery_address); - unset($object->cond_reglement); - unset($object->cond_reglement_id); - unset($object->mode_reglement_id); - unset($object->barcode_type_coder); - unset($object->barcode_type_label); - unset($object->barcode_type_code); - unset($object->barcode_type); - unset($object->country_code); - unset($object->country_id); - unset($object->country); - unset($object->thirdparty); - unset($object->contact); - unset($object->contact_id); - unset($object->user); - unset($object->fk_project); - unset($object->project); - unset($object->canvas); + // Remove useless data + unset($object->civility_id); + unset($object->firstname); + unset($object->lastname); + unset($object->name); + unset($object->location_incoterms); + unset($object->label_incoterms); + unset($object->fk_incoterms); + unset($object->lines); + unset($object->total_ht); + unset($object->total_ttc); + unset($object->total_tva); + unset($object->total_localtax1); + unset($object->total_localtax2); + unset($object->note); + unset($object->note_private); + unset($object->note_public); + unset($object->shipping_method_id); + unset($object->fk_account); + unset($object->model_pdf); + unset($object->fk_delivery_address); + unset($object->cond_reglement); + unset($object->cond_reglement_id); + unset($object->mode_reglement_id); + unset($object->barcode_type_coder); + unset($object->barcode_type_label); + unset($object->barcode_type_code); + unset($object->barcode_type); + unset($object->country_code); + unset($object->country_id); + unset($object->country); + unset($object->thirdparty); + unset($object->contact); + unset($object->contact_id); + unset($object->user); + unset($object->fk_project); + unset($object->project); + unset($object->canvas); - //unset($object->eatby); Filled correctly in read mode - //unset($object->sellby); Filled correctly in read mode + //unset($object->eatby); Filled correctly in read mode + //unset($object->sellby); Filled correctly in read mode - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array|null $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $stockmovement = array(); - foreach (self::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $stockmovement[$field] = $data[$field]; - } - return $stockmovement; - } + /** + * Validate fields before create or update object + * + * @param array|null $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $stockmovement = array(); + foreach (self::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $stockmovement[$field] = $data[$field]; + } + return $stockmovement; + } } diff --git a/htdocs/product/stock/class/api_warehouses.class.php b/htdocs/product/stock/class/api_warehouses.class.php index 933e8be66c9..d6f2333f3ef 100644 --- a/htdocs/product/stock/class/api_warehouses.class.php +++ b/htdocs/product/stock/class/api_warehouses.class.php @@ -28,264 +28,264 @@ */ class Warehouses extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'label', - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'label', + ); - /** - * @var Entrepot $warehouse {@type Entrepot} - */ - public $warehouse; + /** + * @var Entrepot $warehouse {@type Entrepot} + */ + public $warehouse; - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - $this->warehouse = new Entrepot($this->db); - } + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + $this->warehouse = new Entrepot($this->db); + } - /** - * Get properties of a warehouse object - * - * Return an array with warehouse informations - * - * @param int $id ID of warehouse - * @return array|mixed data without useless information - * - * @throws RestException - */ - public function get($id) - { - if (!DolibarrApiAccess::$user->rights->stock->lire) { - throw new RestException(401); - } + /** + * Get properties of a warehouse object + * + * Return an array with warehouse informations + * + * @param int $id ID of warehouse + * @return array|mixed data without useless information + * + * @throws RestException + */ + public function get($id) + { + if (!DolibarrApiAccess::$user->rights->stock->lire) { + throw new RestException(401); + } - $result = $this->warehouse->fetch($id); - if (!$result) { - throw new RestException(404, 'warehouse not found'); - } + $result = $this->warehouse->fetch($id); + if (!$result) { + throw new RestException(404, 'warehouse not found'); + } - if (!DolibarrApi::_checkAccessToResource('warehouse', $this->warehouse->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('warehouse', $this->warehouse->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - return $this->_cleanObjectDatas($this->warehouse); - } + return $this->_cleanObjectDatas($this->warehouse); + } - /** - * List warehouses - * - * Get a list of warehouses - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number + /** + * List warehouses + * + * Get a list of warehouses + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number * @param int $category Use this param to filter list by category - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'WH-%') and (t.date_creation:<:'20160101')" - * @return array Array of warehouse objects - * - * @throws RestException - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '') - { - global $db, $conf; + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'WH-%') and (t.date_creation:<:'20160101')" + * @return array Array of warehouse objects + * + * @throws RestException + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '') + { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - if (!DolibarrApiAccess::$user->rights->stock->lire) { - throw new RestException(401); - } + if (!DolibarrApiAccess::$user->rights->stock->lire) { + throw new RestException(401); + } - $sql = "SELECT t.rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as t"; - if ($category > 0) { + $sql = "SELECT t.rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."entrepot as t"; + if ($category > 0) { $sql .= ", ".MAIN_DB_PREFIX."categorie_societe as c"; - } - $sql .= ' WHERE t.entity IN ('.getEntity('stock').')'; - // Select warehouses of given category - if ($category > 0) { - $sql .= " AND c.fk_categorie = ".$this->db->escape($category); + } + $sql .= ' WHERE t.entity IN ('.getEntity('stock').')'; + // Select warehouses of given category + if ($category > 0) { + $sql .= " AND c.fk_categorie = ".$this->db->escape($category); $sql .= " AND c.fk_warehouse = t.rowid "; - } - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + } + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) - { - $page = 0; - } - $offset = $limit * $page; + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; - $sql .= $this->db->plimit($limit + 1, $offset); - } + $sql .= $this->db->plimit($limit + 1, $offset); + } - $result = $this->db->query($sql); - if ($result) - { - $i = 0; - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { - $obj = $this->db->fetch_object($result); - $warehouse_static = new Entrepot($this->db); - if ($warehouse_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($warehouse_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve warehouse list : '.$this->db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No warehouse found'); - } - return $obj_ret; - } + $result = $this->db->query($sql); + if ($result) + { + $i = 0; + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + $warehouse_static = new Entrepot($this->db); + if ($warehouse_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($warehouse_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve warehouse list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No warehouse found'); + } + return $obj_ret; + } - /** - * Create warehouse object - * - * @param array $request_data Request data - * @return int ID of warehouse - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->stock->creer) { - throw new RestException(401); - } + /** + * Create warehouse object + * + * @param array $request_data Request data + * @return int ID of warehouse + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->stock->creer) { + throw new RestException(401); + } - // Check mandatory fields - $result = $this->_validate($request_data); + // Check mandatory fields + $result = $this->_validate($request_data); - foreach ($request_data as $field => $value) { - $this->warehouse->$field = $value; - } - if ($this->warehouse->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating warehouse", array_merge(array($this->warehouse->error), $this->warehouse->errors)); - } - return $this->warehouse->id; - } + foreach ($request_data as $field => $value) { + $this->warehouse->$field = $value; + } + if ($this->warehouse->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating warehouse", array_merge(array($this->warehouse->error), $this->warehouse->errors)); + } + return $this->warehouse->id; + } - /** - * Update warehouse - * - * @param int $id Id of warehouse to update - * @param array $request_data Datas - * @return int - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->stock->creer) { - throw new RestException(401); - } + /** + * Update warehouse + * + * @param int $id Id of warehouse to update + * @param array $request_data Datas + * @return int + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->stock->creer) { + throw new RestException(401); + } - $result = $this->warehouse->fetch($id); - if (!$result) { - throw new RestException(404, 'warehouse not found'); - } + $result = $this->warehouse->fetch($id); + if (!$result) { + throw new RestException(404, 'warehouse not found'); + } - if (!DolibarrApi::_checkAccessToResource('stock', $this->warehouse->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('stock', $this->warehouse->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - foreach ($request_data as $field => $value) { - if ($field == 'id') continue; - $this->warehouse->$field = $value; - } + foreach ($request_data as $field => $value) { + if ($field == 'id') continue; + $this->warehouse->$field = $value; + } - if ($this->warehouse->update($id, DolibarrApiAccess::$user)) - return $this->get($id); + if ($this->warehouse->update($id, DolibarrApiAccess::$user)) + return $this->get($id); - return false; - } + return false; + } - /** - * Delete warehouse - * - * @param int $id Warehouse ID - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->stock->supprimer) { - throw new RestException(401); - } - $result = $this->warehouse->fetch($id); - if (!$result) { - throw new RestException(404, 'warehouse not found'); - } + /** + * Delete warehouse + * + * @param int $id Warehouse ID + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->stock->supprimer) { + throw new RestException(401); + } + $result = $this->warehouse->fetch($id); + if (!$result) { + throw new RestException(404, 'warehouse not found'); + } - if (!DolibarrApi::_checkAccessToResource('stock', $this->warehouse->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('stock', $this->warehouse->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if (!$this->warehouse->delete(DolibarrApiAccess::$user)) { - throw new RestException(401, 'error when delete warehouse'); - } + if (!$this->warehouse->delete(DolibarrApiAccess::$user)) { + throw new RestException(401, 'error when delete warehouse'); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Warehouse deleted' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Warehouse deleted' + ) + ); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Entrepot $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Entrepot $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - // Remove the subscriptions because they are handled as a subresource. - //unset($object->subscriptions); + // Remove the subscriptions because they are handled as a subresource. + //unset($object->subscriptions); - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array|null $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $warehouse = array(); - foreach (Warehouses::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $warehouse[$field] = $data[$field]; - } - return $warehouse; - } + /** + * Validate fields before create or update object + * + * @param array|null $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $warehouse = array(); + foreach (Warehouses::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $warehouse[$field] = $data[$field]; + } + return $warehouse; + } } diff --git a/htdocs/product/stock/productlot_card.php b/htdocs/product/stock/productlot_card.php index 47bd83951d0..49dea3b008c 100644 --- a/htdocs/product/stock/productlot_card.php +++ b/htdocs/product/stock/productlot_card.php @@ -309,24 +309,24 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $linkback = ''.$langs->trans("BackToList").''; - $shownav = 1; - if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; + $shownav = 1; + if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch'); - print '
'; - print '
'; + print '
'; + print '
'; - print '
'; print ''; print ''; print ''; print ''; print ''; @@ -450,32 +450,32 @@ if ($resql) } // Fields from hook - $parameters=array('arrayfields'=>$arrayfields); - $reshook=$hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook + $parameters = array('arrayfields'=>$arrayfields); + $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; print ''; - $searchpicto=$form->showFilterButtons(); + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; print $obj->date_sync; print "'; - print $obj->code ." ". $obj->name; + print $obj->code." ".$obj->name; print "'; print $obj->rate; print "'; if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined { - $selected=0; - if (in_array($obj->rowid, $arrayofselected)) $selected=1; - print 'rowid.'" class="like-link " style="margin-right:15px;important">' . img_picto('edit', 'edit') . ''; - print 'rowid.'" class="like-link" style="margin-right:45px;important">' . img_picto('delete', 'delete') . ''; - print ''; + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print 'rowid.'" class="like-link " style="margin-right:15px;important">'.img_picto('edit', 'edit').''; + print 'rowid.'" class="like-link" style="margin-right:45px;important">'.img_picto('delete', 'delete').''; + print ''; } print '
'; - print price($productfourn->fourn_multicurrency_unitprice); - print ''; + print price($productfourn->fourn_multicurrency_unitprice); + print ''; - print $productfourn->fourn_multicurrency_code ? currency_name($productfourn->fourn_multicurrency_code) : ''; - print ''; + print $productfourn->fourn_multicurrency_code ? currency_name($productfourn->fourn_multicurrency_code) : ''; + print ''; diff --git a/htdocs/product/reassort.php b/htdocs/product/reassort.php index 99e1ab771c7..715ad66e977 100644 --- a/htdocs/product/reassort.php +++ b/htdocs/product/reassort.php @@ -405,19 +405,19 @@ if ($resql) print price2num($product->stock_theorique, 'MS'); print ''.$objp->unit_short.''.$objp->unit_short.''.$langs->trans("Movements").''.$product->LibStatut($objp->statut, 5, 0).''.$product->LibStatut($objp->tobuy, 5, 1).''.$product->LibStatut($objp->tobuy, 5, 1).'
'."\n"; + print '
'."\n"; // Product - print ''; + print ''; - // Eat by + // Eat by if (empty($conf->global->PRODUCT_DISABLE_EATBY)) { print '
'.$langs->trans("Product").''; - $producttmp = new Product($db); - $producttmp->fetch($object->fk_product); - print $producttmp->getNomUrl(1, 'stock')." - ".$producttmp->label; - print '
'.$langs->trans("Product").''; + $producttmp = new Product($db); + $producttmp->fetch($object->fk_product); + print $producttmp->getNomUrl(1, 'stock')." - ".$producttmp->label; + print '
'; print $form->editfieldkey($langs->trans('EatByDate'), 'eatby', $object->eatby, $object, $user->rights->stock->creer, 'datepicker'); diff --git a/htdocs/projet/class/api_projects.class.php b/htdocs/projet/class/api_projects.class.php index 0ebd7696394..c8ca952f9ed 100644 --- a/htdocs/projet/class/api_projects.class.php +++ b/htdocs/projet/class/api_projects.class.php @@ -30,284 +30,284 @@ class Projects extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'ref', - 'title' - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'ref', + 'title' + ); - /** - * @var Project $project {@type Project} - */ - public $project; + /** + * @var Project $project {@type Project} + */ + public $project; - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - $this->project = new Project($this->db); - $this->task = new Task($this->db); - } + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + $this->project = new Project($this->db); + $this->task = new Task($this->db); + } - /** - * Get properties of a project object - * - * Return an array with project informations - * - * @param int $id ID of project - * @return array|mixed data without useless information - * - * @throws RestException - */ - public function get($id) - { - if (!DolibarrApiAccess::$user->rights->projet->lire) { - throw new RestException(401); - } + /** + * Get properties of a project object + * + * Return an array with project informations + * + * @param int $id ID of project + * @return array|mixed data without useless information + * + * @throws RestException + */ + public function get($id) + { + if (!DolibarrApiAccess::$user->rights->projet->lire) { + throw new RestException(401); + } - $result = $this->project->fetch($id); - if (!$result) { - throw new RestException(404, 'Project not found'); - } + $result = $this->project->fetch($id); + if (!$result) { + throw new RestException(404, 'Project not found'); + } - if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $this->project->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->project); - } + $this->project->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->project); + } - /** - * List projects - * - * Get a list of projects - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $thirdparty_ids Thirdparty ids to filter projects of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} + /** + * List projects + * + * Get a list of projects + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $thirdparty_ids Thirdparty ids to filter projects of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} * @param int $category Use this param to filter list by category * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')" - * @return array Array of project objects - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '') - { - global $db, $conf; + * @return array Array of project objects + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $category = 0, $sqlfilters = '') + { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - // case of external user, $thirdparty_ids param is ignored and replaced by user's socid - $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; - // If the internal user must only see his customers, force searching by him - $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + // If the internal user must only see his customers, force searching by him + $search_sale = 0; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; - $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - $sql .= " FROM ".MAIN_DB_PREFIX."projet as t"; - if ($category > 0) { + $sql = "SELECT t.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + $sql .= " FROM ".MAIN_DB_PREFIX."projet as t"; + if ($category > 0) { $sql .= ", ".MAIN_DB_PREFIX."categorie_project as c"; - } - 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('project').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - // Insert sale filter - if ($search_sale > 0) - { - $sql .= " AND sc.fk_user = ".$search_sale; - } - // Select projects of given category - if ($category > 0) { - $sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_project = t.rowid "; - } - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + $sql .= ' WHERE t.entity IN ('.getEntity('project').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; + if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; + if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + // Insert sale filter + if ($search_sale > 0) + { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Select projects of given category + if ($category > 0) { + $sql .= " AND c.fk_categorie = ".$this->db->escape($category)." AND c.fk_project = t.rowid "; + } + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; - $sql .= $this->db->plimit($limit + 1, $offset); - } + $sql .= $this->db->plimit($limit + 1, $offset); + } - dol_syslog("API Rest request"); - $result = $this->db->query($sql); + dol_syslog("API Rest request"); + $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); + if ($result) + { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) { - $obj = $this->db->fetch_object($result); - $project_static = new Project($this->db); - if ($project_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($project_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve project list : '.$this->db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No project found'); - } - return $obj_ret; - } + while ($i < $min) { + $obj = $this->db->fetch_object($result); + $project_static = new Project($this->db); + if ($project_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($project_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve project list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No project found'); + } + return $obj_ret; + } - /** - * Create project object - * - * @param array $request_data Request data - * @return int ID of project - */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->projet->creer) { - throw new RestException(401, "Insuffisant rights"); - } - // Check mandatory fields - $result = $this->_validate($request_data); + /** + * Create project object + * + * @param array $request_data Request data + * @return int ID of project + */ + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->projet->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validate($request_data); - foreach ($request_data as $field => $value) { - $this->project->$field = $value; - } - /*if (isset($request_data["lines"])) { + foreach ($request_data as $field => $value) { + $this->project->$field = $value; + } + /*if (isset($request_data["lines"])) { $lines = array(); foreach ($request_data["lines"] as $line) { array_push($lines, (object) $line); } $this->project->lines = $lines; }*/ - if ($this->project->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors)); - } + if ($this->project->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating project", array_merge(array($this->project->error), $this->project->errors)); + } - return $this->project->id; - } + return $this->project->id; + } - /** - * Get tasks of a project. - * See also API /tasks - * - * @param int $id Id of project - * @param int $includetimespent 0=Return only list of tasks. 1=Include a summary of time spent, 2=Include details of time spent lines (2 is no implemented yet) - * @return int - * - * @url GET {id}/tasks - */ - public function getLines($id, $includetimespent = 0) - { - if (!DolibarrApiAccess::$user->rights->projet->lire) { - throw new RestException(401); - } + /** + * Get tasks of a project. + * See also API /tasks + * + * @param int $id Id of project + * @param int $includetimespent 0=Return only list of tasks. 1=Include a summary of time spent, 2=Include details of time spent lines (2 is no implemented yet) + * @return int + * + * @url GET {id}/tasks + */ + public function getLines($id, $includetimespent = 0) + { + if (!DolibarrApiAccess::$user->rights->projet->lire) { + throw new RestException(401); + } - $result = $this->project->fetch($id); - if (!$result) { - throw new RestException(404, 'Project not found'); - } + $result = $this->project->fetch($id); + if (!$result) { + throw new RestException(404, 'Project not found'); + } - if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->project->getLinesArray(DolibarrApiAccess::$user); - $result = array(); - foreach ($this->project->lines as $line) // $line is a task - { - if ($includetimespent == 1) - { - $timespent = $line->getSummaryOfTimeSpent(0); - } - if ($includetimespent == 1) - { - // TODO - // Add class for timespent records and loop and fill $line->lines with records of timespent - } - array_push($result, $this->_cleanObjectDatas($line)); - } - return $result; - } + if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->project->getLinesArray(DolibarrApiAccess::$user); + $result = array(); + foreach ($this->project->lines as $line) // $line is a task + { + if ($includetimespent == 1) + { + $timespent = $line->getSummaryOfTimeSpent(0); + } + if ($includetimespent == 1) + { + // TODO + // Add class for timespent records and loop and fill $line->lines with records of timespent + } + array_push($result, $this->_cleanObjectDatas($line)); + } + return $result; + } - /** - * Get roles a user is assigned to a project with - * - * @param int $id Id of project - * @param int $userid Id of user (0 = connected user) - * - * @url GET {id}/roles - * - * @return int - */ - public function getRoles($id, $userid = 0) - { - global $db; + /** + * Get roles a user is assigned to a project with + * + * @param int $id Id of project + * @param int $userid Id of user (0 = connected user) + * + * @url GET {id}/roles + * + * @return int + */ + public function getRoles($id, $userid = 0) + { + global $db; - if (!DolibarrApiAccess::$user->rights->projet->lire) { - throw new RestException(401); - } + if (!DolibarrApiAccess::$user->rights->projet->lire) { + throw new RestException(401); + } - $result = $this->project->fetch($id); - if (!$result) { - throw new RestException(404, 'Project not found'); - } + $result = $this->project->fetch($id); + if (!$result) { + throw new RestException(404, 'Project not found'); + } - if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; - $taskstatic = new Task($this->db); - $userp = DolibarrApiAccess::$user; - if ($userid > 0) - { - $userp = new User($this->db); - $userp->fetch($userid); - } - $this->project->roles = $taskstatic->getUserRolesForProjectsOrTasks($userp, 0, $id, 0); - $result = array(); - foreach ($this->project->roles as $line) { - array_push($result, $this->_cleanObjectDatas($line)); - } - return $result; - } + require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; + $taskstatic = new Task($this->db); + $userp = DolibarrApiAccess::$user; + if ($userid > 0) + { + $userp = new User($this->db); + $userp->fetch($userid); + } + $this->project->roles = $taskstatic->getUserRolesForProjectsOrTasks($userp, 0, $id, 0); + $result = array(); + foreach ($this->project->roles as $line) { + array_push($result, $this->_cleanObjectDatas($line)); + } + return $result; + } - /** - * Add a task to given project - * - * @param int $id Id of project to update - * @param array $request_data Projectline data - * - * @url POST {id}/tasks - * - * @return int - */ - /* + /** + * Add a task to given project + * + * @param int $id Id of project to update + * @param array $request_data Projectline data + * + * @url POST {id}/tasks + * + * @return int + */ + /* public function postLine($id, $request_data = null) { if(! DolibarrApiAccess::$user->rights->projet->creer) { @@ -420,194 +420,194 @@ class Projects extends DolibarrApi - /** - * Update project general fields (won't touch lines of project) - * - * @param int $id Id of project to update - * @param array $request_data Datas - * - * @return int - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->projet->creer) { - throw new RestException(401); - } + /** + * Update project general fields (won't touch lines of project) + * + * @param int $id Id of project to update + * @param array $request_data Datas + * + * @return int + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->projet->creer) { + throw new RestException(401); + } - $result = $this->project->fetch($id); - if ($result <= 0) { - throw new RestException(404, 'Project not found'); - } + $result = $this->project->fetch($id); + if ($result <= 0) { + throw new RestException(404, 'Project not found'); + } - if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - foreach ($request_data as $field => $value) { - if ($field == 'id') continue; - $this->project->$field = $value; - } + if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + foreach ($request_data as $field => $value) { + if ($field == 'id') continue; + $this->project->$field = $value; + } - if ($this->project->update(DolibarrApiAccess::$user) >= 0) - { - return $this->get($id); - } else { - throw new RestException(500, $this->project->error); - } - } + if ($this->project->update(DolibarrApiAccess::$user) >= 0) + { + return $this->get($id); + } else { + throw new RestException(500, $this->project->error); + } + } - /** - * Delete project - * - * @param int $id Project ID - * - * @return array - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->projet->supprimer) { - throw new RestException(401); - } - $result = $this->project->fetch($id); - if (!$result) { - throw new RestException(404, 'Project not found'); - } + /** + * Delete project + * + * @param int $id Project ID + * + * @return array + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->projet->supprimer) { + throw new RestException(401); + } + $result = $this->project->fetch($id); + if (!$result) { + throw new RestException(404, 'Project not found'); + } - if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if (!$this->project->delete(DolibarrApiAccess::$user)) { - throw new RestException(500, 'Error when delete project : '.$this->project->error); - } + if (!$this->project->delete(DolibarrApiAccess::$user)) { + throw new RestException(500, 'Error when delete project : '.$this->project->error); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Project deleted' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Project deleted' + ) + ); + } - /** - * Validate a project. - * You can test this API with the following input message - * { "notrigger": 0 } - * - * @param int $id Project ID - * @param int $notrigger 1=Does not execute triggers, 0= execute triggers - * - * @url POST {id}/validate - * - * @return array - * FIXME An error 403 is returned if the request has an empty body. - * Error message: "Forbidden: Content type `text/plain` is not supported." - * Workaround: send this in the body - * { - * "notrigger": 0 - * } - */ - public function validate($id, $notrigger = 0) - { - if (!DolibarrApiAccess::$user->rights->projet->creer) { - throw new RestException(401); - } - $result = $this->project->fetch($id); - if (!$result) { - throw new RestException(404, 'Project not found'); - } + /** + * Validate a project. + * You can test this API with the following input message + * { "notrigger": 0 } + * + * @param int $id Project ID + * @param int $notrigger 1=Does not execute triggers, 0= execute triggers + * + * @url POST {id}/validate + * + * @return array + * FIXME An error 403 is returned if the request has an empty body. + * Error message: "Forbidden: Content type `text/plain` is not supported." + * Workaround: send this in the body + * { + * "notrigger": 0 + * } + */ + public function validate($id, $notrigger = 0) + { + if (!DolibarrApiAccess::$user->rights->projet->creer) { + throw new RestException(401); + } + $result = $this->project->fetch($id); + if (!$result) { + throw new RestException(404, 'Project not found'); + } - if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('project', $this->project->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $result = $this->project->setValid(DolibarrApiAccess::$user, $notrigger); - if ($result == 0) { - throw new RestException(304, 'Error nothing done. May be object is already validated'); - } - if ($result < 0) { - throw new RestException(500, 'Error when validating Project: '.$this->project->error); - } + $result = $this->project->setValid(DolibarrApiAccess::$user, $notrigger); + if ($result == 0) { + throw new RestException(304, 'Error nothing done. May be object is already validated'); + } + if ($result < 0) { + throw new RestException(500, 'Error when validating Project: '.$this->project->error); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Project validated' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Project validated' + ) + ); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->datec); - unset($object->datem); - unset($object->barcode_type); - unset($object->barcode_type_code); - unset($object->barcode_type_label); - unset($object->barcode_type_coder); - unset($object->cond_reglement_id); - unset($object->cond_reglement); - unset($object->fk_delivery_address); - unset($object->shipping_method_id); - unset($object->fk_account); - unset($object->note); - unset($object->fk_incoterms); - unset($object->label_incoterms); - unset($object->location_incoterms); - unset($object->name); - unset($object->lastname); - unset($object->firstname); - unset($object->civility_id); - unset($object->mode_reglement_id); - unset($object->country); - unset($object->country_id); - unset($object->country_code); + unset($object->datec); + unset($object->datem); + unset($object->barcode_type); + unset($object->barcode_type_code); + unset($object->barcode_type_label); + unset($object->barcode_type_coder); + unset($object->cond_reglement_id); + unset($object->cond_reglement); + unset($object->fk_delivery_address); + unset($object->shipping_method_id); + unset($object->fk_account); + unset($object->note); + unset($object->fk_incoterms); + unset($object->label_incoterms); + unset($object->location_incoterms); + unset($object->name); + unset($object->lastname); + unset($object->firstname); + unset($object->civility_id); + unset($object->mode_reglement_id); + unset($object->country); + unset($object->country_id); + unset($object->country_code); - unset($object->weekWorkLoad); - unset($object->weekWorkLoad); + unset($object->weekWorkLoad); + unset($object->weekWorkLoad); - //unset($object->lines); // for task we use timespent_lines, but for project we use lines + //unset($object->lines); // for task we use timespent_lines, but for project we use lines - unset($object->total_ht); - unset($object->total_tva); - unset($object->total_localtax1); - unset($object->total_localtax2); - unset($object->total_ttc); + unset($object->total_ht); + unset($object->total_tva); + unset($object->total_localtax1); + unset($object->total_localtax2); + unset($object->total_ttc); - unset($object->comments); + unset($object->comments); - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - private function _validate($data) - { - $object = array(); - foreach (self::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $object[$field] = $data[$field]; - } - return $object; - } + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + private function _validate($data) + { + $object = array(); + foreach (self::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $object[$field] = $data[$field]; + } + return $object; + } - // TODO - // getSummaryOfTimeSpent + // TODO + // getSummaryOfTimeSpent } diff --git a/htdocs/projet/class/api_tasks.class.php b/htdocs/projet/class/api_tasks.class.php index 707e14a2c44..e7bf2c67ce8 100644 --- a/htdocs/projet/class/api_tasks.class.php +++ b/htdocs/projet/class/api_tasks.class.php @@ -550,8 +550,8 @@ class Tasks extends DolibarrApi /** * Clean sensible object datas * - * @param Object $object Object to clean - * @return Object Object with cleaned properties + * @param Object $object Object to clean + * @return Object Object with cleaned properties */ protected function _cleanObjectDatas($object) { diff --git a/htdocs/societe/card.php b/htdocs/societe/card.php index d09424b6118..f16779148d3 100644 --- a/htdocs/societe/card.php +++ b/htdocs/societe/card.php @@ -1159,325 +1159,325 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } } - dol_htmloutput_mesg(is_numeric($error) ? '' : $error, $errors, 'error'); + dol_htmloutput_mesg(is_numeric($error) ? '' : $error, $errors, 'error'); - print ''; // Chrome ignor autocomplete + print ''; // Chrome ignor autocomplete - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($modCodeClient->code_auto || $modCodeFournisseur->code_auto) print ''; - print dol_get_fiche_head(null, 'card', '', 0, ''); + print dol_get_fiche_head(null, 'card', '', 0, ''); - print ''; + print '
'; - // Name, firstname - print 'global->SOCIETE_USEPREFIX) ? ' colspan="3"' : '').'>'; - print ''; - print $form->widgetForTranslation("name", $object, $permissiontoadd, 'string', 'alpahnohtml', 'minwidth300'); - print ''; - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { - print ''; - } - print ''; + } + print 'global->SOCIETE_USEPREFIX) ? ' colspan="3"' : '').'>'; + print ''; + print $form->widgetForTranslation("name", $object, $permissiontoadd, 'string', 'alpahnohtml', 'minwidth300'); + print ''; + if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field + { + print ''; + } + print ''; - // If javascript on, we show option individual - if ($conf->use_javascript_ajax) - { - if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) - { - // Firstname - print ''; - print ''; - print ''; + // If javascript on, we show option individual + if ($conf->use_javascript_ajax) + { + if (!empty($conf->global->THIRDPARTY_SUGGEST_ALSO_ADDRESS_CREATION)) + { + // Firstname + print ''; + print ''; + print ''; - // Title - print ''; - print ''; - } - } + // Title + print ''; + print ''; + } + } - // Alias names (commercial, trademark or alias names) - print ''; - print ''; + // Alias names (commercial, trademark or alias names) + print ''; + print ''; - // Prospect/Customer - print ''; - print ''; + // Prospect/Customer + print ''; + print ''; - if ($conf->browser->layout == 'phone') print ''; + if ($conf->browser->layout == 'phone') print ''; - print ''; - if ((!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) - || (!empty($conf->supplier_proposal->enabled) && !empty($user->rights->supplier_proposal->lire))) - { - // Supplier - print ''; - print ''; + if ((!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) + || (!empty($conf->supplier_proposal->enabled) && !empty($user->rights->supplier_proposal->lire))) + { + // Supplier + print ''; + print ''; - if ($conf->browser->layout == 'phone') print ''; + if ($conf->browser->layout == 'phone') print ''; - print ''; - } + print ''; + } - // Status - print ''; + // Status + print ''; - // Barcode - if (!empty($conf->barcode->enabled)) - { - print ''; - print ''; - } + // Barcode + if (!empty($conf->barcode->enabled)) + { + print ''; + print ''; + } - // Address - print ''; - print ''; + // Address + print ''; + print ''; - // Zip / Town - print ''; - if ($conf->browser->layout == 'phone') print ''; - print ''; + // Zip / Town + print ''; + if ($conf->browser->layout == 'phone') print ''; + print ''; - // Country - print ''; + // Country + print ''; - // State - if (empty($conf->global->SOCIETE_DISABLE_STATE)) - { - if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) - { - print ''; - } + if ($object->country_id) print $formcompany->select_state($object->state_id, $object->country_code); + else print $countrynotdefined; + print ''; + } - // Phone / Fax - print ''; - print 'browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning').' '; - if ($conf->browser->layout == 'phone') print ''; - print ''; - print 'browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning_fax').' '; + // Phone / Fax + print ''; + print 'browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning').' '; + if ($conf->browser->layout == 'phone') print ''; + print ''; + print 'browser->layout == 'phone' ? ' colspan="3"' : '').'>'.img_picto('', 'object_phoning_fax').' '; - // Email / Web - print ''; - print ''; - print ''; - print ''; + // Email / Web + print ''; + print ''; + print ''; + print ''; - if (!empty($conf->socialnetworks->enabled)) { - foreach ($socialnetworks as $key => $value) { - if ($value['active']) { - print ''; - print ''; - print ''; - print ''; - } elseif (!empty($object->socialnetworks[$key])) { - print ''; - } - } - } + if (!empty($conf->socialnetworks->enabled)) { + foreach ($socialnetworks as $key => $value) { + if ($value['active']) { + print ''; + print ''; + print ''; + print ''; + } elseif (!empty($object->socialnetworks[$key])) { + print ''; + } + } + } - // Prof ids - $i = 1; $j = 0; $NBCOLS = ($conf->browser->layout == 'phone' ? 1 : 2); - while ($i <= 6) - { - $idprof = $langs->transcountry('ProfId'.$i, $object->country_code); - if ($idprof != '-') - { - $key = 'idprof'.$i; + // Prof ids + $i = 1; $j = 0; $NBCOLS = ($conf->browser->layout == 'phone' ? 1 : 2); + while ($i <= 6) + { + $idprof = $langs->transcountry('ProfId'.$i, $object->country_code); + if ($idprof != '-') + { + $key = 'idprof'.$i; - if (($j % $NBCOLS) == 0) print ''; + if (($j % $NBCOLS) == 0) print ''; - $idprof_mandatory = 'SOCIETE_IDPROF'.($i).'_MANDATORY'; - print ''; - if (($j % $NBCOLS) == ($NBCOLS - 1)) print ''; - $j++; - } - $i++; - } - if ($NBCOLS > 1 && ($j % 2 == 1)) print ''; + print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code); + print ''; + if (($j % $NBCOLS) == ($NBCOLS - 1)) print ''; + $j++; + } + $i++; + } + if ($NBCOLS > 1 && ($j % 2 == 1)) print ''; - // Vat is used - print ''; - print ''; - if ($conf->browser->layout == 'phone') print ''; - print ''; - print ''; + print ''; + if ($conf->browser->layout == 'phone') print ''; + print ''; + print ''; - print ''; + if (!empty($conf->use_javascript_ajax)) + { + $widthpopup = 600; + if (!empty($conf->dol_use_jmobile)) $widthpopup = 350; + $heightpopup = 400; + print "\n"; + print ''; + print "\n"; + $s .= ''.$langs->trans("VATIntraCheck").''; + $s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1); + } else { + $s .= 'country_id).'" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').''; + } + } + print $s; + print ''; + print ''; - // Local Taxes - //TODO: Place into a function to control showing by country or study better option - if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") - { - print ''; - if ($conf->browser->layout == 'phone') print ''; - print ''; - } elseif ($mysoc->localtax1_assuj == "1") - { - print ''; - } elseif ($mysoc->localtax2_assuj == "1") - { - print ''; - } + // Local Taxes + //TODO: Place into a function to control showing by country or study better option + if ($mysoc->localtax1_assuj == "1" && $mysoc->localtax2_assuj == "1") + { + print ''; + if ($conf->browser->layout == 'phone') print ''; + print ''; + } elseif ($mysoc->localtax1_assuj == "1") + { + print ''; + } elseif ($mysoc->localtax2_assuj == "1") + { + print ''; + } - // Type - Workforce/Staff - print ''; - if ($conf->browser->layout == 'phone') print ''; - print ''; + // Type - Workforce/Staff + print ''; + if ($conf->browser->layout == 'phone') print ''; + print ''; - // Legal Form - print ''; - print ''; + // Legal Form + print ''; + print ''; - // Capital - print ''; - print ''; + // Capital + print ''; + print ''; - if (!empty($conf->global->MAIN_MULTILANGS)) - { - print ''; - print ''; - } + if (!empty($conf->global->MAIN_MULTILANGS)) + { + print ''; + print ''; + } // Incoterms if (!empty($conf->incoterm->enabled)) { print ''; print ''; - print ''; } diff --git a/htdocs/societe/class/api_contacts.class.php b/htdocs/societe/class/api_contacts.class.php index 4c613f08d83..bc456dd7185 100644 --- a/htdocs/societe/class/api_contacts.class.php +++ b/htdocs/societe/class/api_contacts.class.php @@ -431,131 +431,131 @@ class Contacts extends DolibarrApi } return $result; - } + } - /** - * Add a category to a contact - * - * @url POST {id}/categories/{category_id} - * - * @param int $id Id of contact - * @param int $category_id Id of category - * - * @return mixed - * - * @throws RestException 401 Insufficient rights - * @throws RestException 404 Category or contact not found - */ - public function addCategory($id, $category_id) - { - if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { - throw new RestException(401, 'Insufficient rights'); - } + /** + * Add a category to a contact + * + * @url POST {id}/categories/{category_id} + * + * @param int $id Id of contact + * @param int $category_id Id of category + * + * @return mixed + * + * @throws RestException 401 Insufficient rights + * @throws RestException 404 Category or contact not found + */ + public function addCategory($id, $category_id) + { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401, 'Insufficient rights'); + } - $result = $this->contact->fetch($id); - if (!$result) { - throw new RestException(404, 'Contact not found'); - } - $category = new Categorie($this->db); - $result = $category->fetch($category_id); - if (!$result) { - throw new RestException(404, 'category not found'); - } + $result = $this->contact->fetch($id); + if (!$result) { + throw new RestException(404, 'Contact not found'); + } + $category = new Categorie($this->db); + $result = $category->fetch($category_id); + if (!$result) { + throw new RestException(404, 'category not found'); + } - if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $category->add_type($this->contact, 'contact'); + $category->add_type($this->contact, 'contact'); - return $this->_cleanObjectDatas($this->contact); - } + return $this->_cleanObjectDatas($this->contact); + } - /** - * Remove the link between a category and a contact - * - * @url DELETE {id}/categories/{category_id} - * - * @param int $id Id of contact - * @param int $category_id Id of category - * @return mixed - * - * @throws RestException 401 Insufficient rights - * @throws RestException 404 Category or contact not found - */ - public function deleteCategory($id, $category_id) - { - if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { - throw new RestException(401, 'Insufficient rights'); - } + /** + * Remove the link between a category and a contact + * + * @url DELETE {id}/categories/{category_id} + * + * @param int $id Id of contact + * @param int $category_id Id of category + * @return mixed + * + * @throws RestException 401 Insufficient rights + * @throws RestException 404 Category or contact not found + */ + public function deleteCategory($id, $category_id) + { + if (!DolibarrApiAccess::$user->rights->societe->contact->creer) { + throw new RestException(401, 'Insufficient rights'); + } - $result = $this->contact->fetch($id); - if (!$result) { - throw new RestException(404, 'Contact not found'); - } - $category = new Categorie($this->db); - $result = $category->fetch($category_id); - if (!$result) { - throw new RestException(404, 'category not found'); - } + $result = $this->contact->fetch($id); + if (!$result) { + throw new RestException(404, 'Contact not found'); + } + $category = new Categorie($this->db); + $result = $category->fetch($category_id); + if (!$result) { + throw new RestException(404, 'category not found'); + } - if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + if (!DolibarrApi::_checkAccessToResource('category', $category->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $category->del_type($this->contact, 'contact'); + $category->del_type($this->contact, 'contact'); - return $this->_cleanObjectDatas($this->contact); - } + return $this->_cleanObjectDatas($this->contact); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->total_ht); - unset($object->total_tva); - unset($object->total_localtax1); - unset($object->total_localtax2); - unset($object->total_ttc); + unset($object->total_ht); + unset($object->total_tva); + unset($object->total_localtax1); + unset($object->total_localtax2); + unset($object->total_ttc); - unset($object->note); - unset($object->lines); - unset($object->thirdparty); + unset($object->note); + unset($object->lines); + unset($object->thirdparty); - return $object; - } + return $object; + } - /** - * Validate fields before create or update object - * - * @param array|null $data Data to validate - * @return array - * @throws RestException - */ - private function _validate($data) - { - $contact = array(); - foreach (Contacts::$FIELDS as $field) { - if (!isset($data[$field])) { - throw new RestException(400, "$field field missing"); - } - $contact[$field] = $data[$field]; - } + /** + * Validate fields before create or update object + * + * @param array|null $data Data to validate + * @return array + * @throws RestException + */ + private function _validate($data) + { + $contact = array(); + foreach (Contacts::$FIELDS as $field) { + if (!isset($data[$field])) { + throw new RestException(400, "$field field missing"); + } + $contact[$field] = $data[$field]; + } - return $contact; - } + return $contact; + } } diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 42b7da2559a..b96c9bbd9db 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1303,10 +1303,10 @@ class Societe extends CommonObject $sql .= ",mode_reglement = ".(!empty($this->mode_reglement_id) ? "'".$this->db->escape($this->mode_reglement_id)."'" : "null"); $sql .= ",cond_reglement = ".(!empty($this->cond_reglement_id) ? "'".$this->db->escape($this->cond_reglement_id)."'" : "null"); - $sql .= ",transport_mode = ".(! empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null"); + $sql .= ",transport_mode = ".(!empty($this->transport_mode_id) ? "'".$this->db->escape($this->transport_mode_id)."'" : "null"); $sql .= ",mode_reglement_supplier = ".(!empty($this->mode_reglement_supplier_id) ? "'".$this->db->escape($this->mode_reglement_supplier_id)."'" : "null"); $sql .= ",cond_reglement_supplier = ".(!empty($this->cond_reglement_supplier_id) ? "'".$this->db->escape($this->cond_reglement_supplier_id)."'" : "null"); - $sql .= ",transport_mode_supplier = ".(! empty($this->transport_mode_supplier_id)? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null"); + $sql .= ",transport_mode_supplier = ".(!empty($this->transport_mode_supplier_id) ? "'".$this->db->escape($this->transport_mode_supplier_id)."'" : "null"); $sql .= ",fk_shipping_method = ".(!empty($this->shipping_method_id) ? "'".$this->db->escape($this->shipping_method_id)."'" : "null"); $sql .= ",client = ".(!empty($this->client) ? $this->client : 0); diff --git a/htdocs/supplier_proposal/class/api_supplier_proposals.class.php b/htdocs/supplier_proposal/class/api_supplier_proposals.class.php index 156dd66e5f6..bf91be32d8d 100644 --- a/htdocs/supplier_proposal/class/api_supplier_proposals.class.php +++ b/htdocs/supplier_proposal/class/api_supplier_proposals.class.php @@ -30,185 +30,185 @@ require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class class Supplierproposals extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - static $FIELDS = array( - 'socid' - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + static $FIELDS = array( + 'socid' + ); - /** - * @var SupplierProposal $supplier_proposal {@type SupplierProposal} - */ - public $supplier_proposal; + /** + * @var SupplierProposal $supplier_proposal {@type SupplierProposal} + */ + public $supplier_proposal; - /** - * Constructor - */ - public function __construct() - { - global $db, $conf; - $this->db = $db; - $this->supplier_proposal = new SupplierProposal($this->db); - } + /** + * Constructor + */ + public function __construct() + { + global $db, $conf; + $this->db = $db; + $this->supplier_proposal = new SupplierProposal($this->db); + } - /** - * Get properties of a supplier proposal (price request) object - * - * Return an array with supplier proposal informations - * - * @param int $id ID of supplier proposal - * @return array|mixed data without useless information - * - * @throws RestException - */ - public function get($id) - { - if (!DolibarrApiAccess::$user->rights->supplier_proposal->lire) { - throw new RestException(401); - } + /** + * Get properties of a supplier proposal (price request) object + * + * Return an array with supplier proposal informations + * + * @param int $id ID of supplier proposal + * @return array|mixed data without useless information + * + * @throws RestException + */ + public function get($id) + { + if (!DolibarrApiAccess::$user->rights->supplier_proposal->lire) { + throw new RestException(401); + } - $result = $this->supplier_proposal->fetch($id); - if (!$result) { - throw new RestException(404, 'Supplier Proposal not found'); - } + $result = $this->supplier_proposal->fetch($id); + if (!$result) { + throw new RestException(404, 'Supplier Proposal not found'); + } - if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->propal->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('supplier_proposal', $this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $this->supplier_proposal->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->supplier_proposal); - } + $this->supplier_proposal->fetchObjectLinked(); + return $this->_cleanObjectDatas($this->supplier_proposal); + } - /** - * List supplier proposals - * - * Get a list of supplier proposals - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $thirdparty_ids Thirdparty ids to filter supplier proposals (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')" - * @return array Array of order objects - */ - public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') - { - global $db, $conf; + /** + * List supplier proposals + * + * Get a list of supplier proposals + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $thirdparty_ids Thirdparty ids to filter supplier proposals (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.datec:<:'20160101')" + * @return array Array of order objects + */ + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') + { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - // case of external user, $thirdparty_ids param is ignored and replaced by user's socid - $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; + // case of external user, $thirdparty_ids param is ignored and replaced by user's socid + $socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids; - // If the internal user must only see his customers, force searching by him - $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + // If the internal user must only see his customers, force searching by him + $search_sale = 0; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; - $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal as t"; + $sql = "SELECT t.rowid"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + $sql .= " FROM ".MAIN_DB_PREFIX."supplier_proposal 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').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - // Insert sale filter - if ($search_sale > 0) - { - $sql .= " AND sc.fk_user = ".$search_sale; - } - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + $sql .= ' WHERE t.entity IN ('.getEntity('propal').')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; + if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; + if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + // Insert sale filter + if ($search_sale > 0) + { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) - { - $page = 0; - } - $offset = $limit * $page; + $sql .= $this->db->order($sortfield, $sortorder); + if ($limit) { + if ($page < 0) + { + $page = 0; + } + $offset = $limit * $page; - $sql .= $this->db->plimit($limit + 1, $offset); - } + $sql .= $this->db->plimit($limit + 1, $offset); + } - $result = $this->db->query($sql); + $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - $i = 0; - while ($i < $min) - { - $obj = $this->db->fetch_object($result); - $propal_static = new SupplierProposal($this->db); - if ($propal_static->fetch($obj->rowid)) { - $obj_ret[] = $this->_cleanObjectDatas($propal_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieving supplier proposal list : '.$this->db->lasterror()); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No supplier proposal found'); - } - return $obj_ret; - } + if ($result) + { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + $i = 0; + while ($i < $min) + { + $obj = $this->db->fetch_object($result); + $propal_static = new SupplierProposal($this->db); + if ($propal_static->fetch($obj->rowid)) { + $obj_ret[] = $this->_cleanObjectDatas($propal_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieving supplier proposal list : '.$this->db->lasterror()); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No supplier proposal found'); + } + return $obj_ret; + } - /** - * Validate fields before create or update object - * - * @param array $data Array with data to verify - * @return array - * @throws RestException - */ - private function _validate($data) - { - $propal = array(); - foreach (SupplierProposals::$FIELDS as $field) { - if (!isset($data[$field])) - throw new RestException(400, "$field field missing"); - $propal[$field] = $data[$field]; - } - return $propal; - } + /** + * Validate fields before create or update object + * + * @param array $data Array with data to verify + * @return array + * @throws RestException + */ + private function _validate($data) + { + $propal = array(); + foreach (SupplierProposals::$FIELDS as $field) { + if (!isset($data[$field])) + throw new RestException(400, "$field field missing"); + $propal[$field] = $data[$field]; + } + return $propal; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->name); - unset($object->lastname); - unset($object->firstname); - unset($object->civility_id); - unset($object->address); - unset($object->datec); - unset($object->datev); + unset($object->name); + unset($object->lastname); + unset($object->firstname); + unset($object->civility_id); + unset($object->address); + unset($object->datec); + unset($object->datev); - return $object; - } + return $object; + } } diff --git a/htdocs/takepos/ajax/ajax.php b/htdocs/takepos/ajax/ajax.php index 42cdc854d8b..6da8c74361c 100644 --- a/htdocs/takepos/ajax/ajax.php +++ b/htdocs/takepos/ajax/ajax.php @@ -77,13 +77,13 @@ if ($action == 'getProducts') { $result = $thirdparty->fetch('', '', '', $term); if ($result && $thirdparty->id > 0) { - $rows = array(); - $rows[] = array( - 'rowid' => $thirdparty->id, - 'name' => $thirdparty->name, - 'barcode' => $thirdparty->barcode, - 'object' => 'thirdparty' - ); + $rows = array(); + $rows[] = array( + 'rowid' => $thirdparty->id, + 'name' => $thirdparty->name, + 'barcode' => $thirdparty->barcode, + 'object' => 'thirdparty' + ); echo json_encode($rows); exit; } diff --git a/htdocs/ticket/class/api_tickets.class.php b/htdocs/ticket/class/api_tickets.class.php index a26a01e1a98..bce4d03fd92 100644 --- a/htdocs/ticket/class/api_tickets.class.php +++ b/htdocs/ticket/class/api_tickets.class.php @@ -29,542 +29,542 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/ticket.lib.php'; */ class Tickets extends DolibarrApi { - /** - * @var array $FIELDS Mandatory fields, checked when create and update object - */ - public static $FIELDS = array( - 'subject', - 'message' - ); + /** + * @var array $FIELDS Mandatory fields, checked when create and update object + */ + public static $FIELDS = array( + 'subject', + 'message' + ); - /** - * @var array $FIELDS_MESSAGES Mandatory fields, checked when create and update object - */ - public static $FIELDS_MESSAGES = array( - 'track_id', - 'message' - ); + /** + * @var array $FIELDS_MESSAGES Mandatory fields, checked when create and update object + */ + public static $FIELDS_MESSAGES = array( + 'track_id', + 'message' + ); - /** - * @var Ticket $ticket {@type Ticket} - */ - public $ticket; + /** + * @var Ticket $ticket {@type Ticket} + */ + public $ticket; - /** - * Constructor - */ - public function __construct() - { - global $db; - $this->db = $db; - $this->ticket = new Ticket($this->db); - } + /** + * Constructor + */ + public function __construct() + { + global $db; + $this->db = $db; + $this->ticket = new Ticket($this->db); + } - /** - * Get properties of a Ticket object. - * - * Return an array with ticket informations - * - * @param int $id ID of ticket - * @return array|mixed Data without useless information - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function get($id) - { - return $this->getCommon($id, '', ''); - } + /** + * Get properties of a Ticket object. + * + * Return an array with ticket informations + * + * @param int $id ID of ticket + * @return array|mixed Data without useless information + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function get($id) + { + return $this->getCommon($id, '', ''); + } - /** - * Get properties of a Ticket object from track id - * - * Return an array with ticket informations - * - * @param string $track_id Tracking ID of ticket - * @return array|mixed Data without useless information - * - * @url GET track_id/{track_id} - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function getByTrackId($track_id) - { - return $this->getCommon(0, $track_id, ''); - } + /** + * Get properties of a Ticket object from track id + * + * Return an array with ticket informations + * + * @param string $track_id Tracking ID of ticket + * @return array|mixed Data without useless information + * + * @url GET track_id/{track_id} + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function getByTrackId($track_id) + { + return $this->getCommon(0, $track_id, ''); + } - /** - * Get properties of a Ticket object from ref - * - * Return an array with ticket informations - * - * @param string $ref Reference for ticket - * @return array|mixed Data without useless information - * - * @url GET ref/{ref} - * - * @throws RestException 401 - * @throws RestException 403 - * @throws RestException 404 - */ - public function getByRef($ref) - { - try { - return $this->getCommon(0, '', $ref); - } catch (Exception $e) - { - throw $e; - } - } + /** + * Get properties of a Ticket object from ref + * + * Return an array with ticket informations + * + * @param string $ref Reference for ticket + * @return array|mixed Data without useless information + * + * @url GET ref/{ref} + * + * @throws RestException 401 + * @throws RestException 403 + * @throws RestException 404 + */ + public function getByRef($ref) + { + try { + return $this->getCommon(0, '', $ref); + } catch (Exception $e) + { + throw $e; + } + } - /** - * Get properties of a Ticket object - * Return an array with ticket informations - * - * @param int $id ID of ticket - * @param string $track_id Tracking ID of ticket - * @param string $ref Reference for ticket - * @return array|mixed Data without useless information - */ - private function getCommon($id = 0, $track_id = '', $ref = '') - { - if (!DolibarrApiAccess::$user->rights->ticket->read) { - throw new RestException(403); - } + /** + * Get properties of a Ticket object + * Return an array with ticket informations + * + * @param int $id ID of ticket + * @param string $track_id Tracking ID of ticket + * @param string $ref Reference for ticket + * @return array|mixed Data without useless information + */ + private function getCommon($id = 0, $track_id = '', $ref = '') + { + if (!DolibarrApiAccess::$user->rights->ticket->read) { + throw new RestException(403); + } - // Check parameters - if (!$id && !$track_id && !$ref) { - throw new RestException(401, 'Wrong parameters'); - } + // Check parameters + if (!$id && !$track_id && !$ref) { + throw new RestException(401, 'Wrong parameters'); + } - $result = $this->ticket->fetch($id, $ref, $track_id); - if (!$result) { - throw new RestException(404, 'Ticket not found'); - } + $result = $this->ticket->fetch($id, $ref, $track_id); + if (!$result) { + throw new RestException(404, 'Ticket not found'); + } - // String for user assigned - if ($this->ticket->fk_user_assign > 0) { - $userStatic = new User($this->db); - $userStatic->fetch($this->ticket->fk_user_assign); - $this->ticket->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; - } + // String for user assigned + if ($this->ticket->fk_user_assign > 0) { + $userStatic = new User($this->db); + $userStatic->fetch($this->ticket->fk_user_assign); + $this->ticket->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; + } - // Messages of ticket - $messages = array(); - $this->ticket->loadCacheMsgsTicket(); - if (is_array($this->ticket->cache_msgs_ticket) && count($this->ticket->cache_msgs_ticket) > 0) { - $num = count($this->ticket->cache_msgs_ticket); - $i = 0; - while ($i < $num) { - if ($this->ticket->cache_msgs_ticket[$i]['fk_user_author'] > 0) { - $user_action = new User($this->db); - $user_action->fetch($this->ticket->cache_msgs_ticket[$i]['fk_user_author']); - } + // Messages of ticket + $messages = array(); + $this->ticket->loadCacheMsgsTicket(); + if (is_array($this->ticket->cache_msgs_ticket) && count($this->ticket->cache_msgs_ticket) > 0) { + $num = count($this->ticket->cache_msgs_ticket); + $i = 0; + while ($i < $num) { + if ($this->ticket->cache_msgs_ticket[$i]['fk_user_author'] > 0) { + $user_action = new User($this->db); + $user_action->fetch($this->ticket->cache_msgs_ticket[$i]['fk_user_author']); + } - // Now define messages - $messages[] = array( - 'id' => $this->ticket->cache_msgs_ticket[$i]['id'], - 'fk_user_action' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'], - 'fk_user_action_socid' => $user_action->socid, - 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), - 'message' => $this->ticket->cache_msgs_ticket[$i]['message'], - 'datec' => $this->ticket->cache_msgs_ticket[$i]['datec'], - 'private' => $this->ticket->cache_msgs_ticket[$i]['private'] - ); - $i++; - } - $this->ticket->messages = $messages; - } + // Now define messages + $messages[] = array( + 'id' => $this->ticket->cache_msgs_ticket[$i]['id'], + 'fk_user_action' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'], + 'fk_user_action_socid' => $user_action->socid, + 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), + 'message' => $this->ticket->cache_msgs_ticket[$i]['message'], + 'datec' => $this->ticket->cache_msgs_ticket[$i]['datec'], + 'private' => $this->ticket->cache_msgs_ticket[$i]['private'] + ); + $i++; + } + $this->ticket->messages = $messages; + } - // History - $history = array(); - $this->ticket->loadCacheLogsTicket(); - if (is_array($this->ticket->cache_logs_ticket) && count($this->ticket->cache_logs_ticket) > 0) { - $num = count($this->ticket->cache_logs_ticket); - $i = 0; - while ($i < $num) { - if ($this->ticket->cache_logs_ticket[$i]['fk_user_create'] > 0) { - $user_action = new User($this->db); - $user_action->fetch($this->ticket->cache_logs_ticket[$i]['fk_user_create']); - } + // History + $history = array(); + $this->ticket->loadCacheLogsTicket(); + if (is_array($this->ticket->cache_logs_ticket) && count($this->ticket->cache_logs_ticket) > 0) { + $num = count($this->ticket->cache_logs_ticket); + $i = 0; + while ($i < $num) { + if ($this->ticket->cache_logs_ticket[$i]['fk_user_create'] > 0) { + $user_action = new User($this->db); + $user_action->fetch($this->ticket->cache_logs_ticket[$i]['fk_user_create']); + } - // Now define messages - $history[] = array( - 'id' => $this->ticket->cache_logs_ticket[$i]['id'], - 'fk_user_author' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'], - 'fk_user_action' => $this->ticket->cache_logs_ticket[$i]['fk_user_create'], - 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), - 'message' => $this->ticket->cache_logs_ticket[$i]['message'], - 'datec' => $this->ticket->cache_logs_ticket[$i]['datec'], - ); - $i++; - } - $this->ticket->history = $history; - } + // Now define messages + $history[] = array( + 'id' => $this->ticket->cache_logs_ticket[$i]['id'], + 'fk_user_author' => $this->ticket->cache_msgs_ticket[$i]['fk_user_author'], + 'fk_user_action' => $this->ticket->cache_logs_ticket[$i]['fk_user_create'], + 'fk_user_action_string' => dolGetFirstLastname($user_action->firstname, $user_action->lastname), + 'message' => $this->ticket->cache_logs_ticket[$i]['message'], + 'datec' => $this->ticket->cache_logs_ticket[$i]['datec'], + ); + $i++; + } + $this->ticket->history = $history; + } - if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - return $this->_cleanObjectDatas($this->ticket); - } + if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + return $this->_cleanObjectDatas($this->ticket); + } - /** - * List tickets - * - * Get a list of tickets - * - * @param int $socid Filter list with thirdparty ID - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Limit for list - * @param int $page Page number - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101') and (t.fk_statut:=:1)" - * - * @return array Array of ticket objects - * - */ - public function index($socid = 0, $sortfield = "t.rowid", $sortorder = "ASC", $limit = 100, $page = 0, $sqlfilters = '') - { - global $db, $conf; + /** + * List tickets + * + * Get a list of tickets + * + * @param int $socid Filter list with thirdparty ID + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Limit for list + * @param int $page Page number + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101') and (t.fk_statut:=:1)" + * + * @return array Array of ticket objects + * + */ + public function index($socid = 0, $sortfield = "t.rowid", $sortorder = "ASC", $limit = 100, $page = 0, $sqlfilters = '') + { + global $db, $conf; - $obj_ret = array(); + $obj_ret = array(); - if (!$socid && DolibarrApiAccess::$user->socid) { - $socid = DolibarrApiAccess::$user->socid; - } + if (!$socid && DolibarrApiAccess::$user->socid) { + $socid = DolibarrApiAccess::$user->socid; + } - // If the internal user must only see his customers, force searching by him - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) { - $search_sale = DolibarrApiAccess::$user->id; - } + // If the internal user must only see his customers, force searching by him + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) { + $search_sale = DolibarrApiAccess::$user->id; + } - $sql = "SELECT t.rowid"; - 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."ticket as t"; + $sql = "SELECT t.rowid"; + 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."ticket as t"; - 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('ticket', 1).')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { - $sql .= " AND t.fk_soc = sc.fk_soc"; - } - if ($socid > 0) { - $sql .= " AND t.fk_soc = ".$socid; - } - if ($search_sale > 0) { - $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale - } + $sql .= ' WHERE t.entity IN ('.getEntity('ticket', 1).')'; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socid > 0) { + $sql .= " AND t.fk_soc = ".$socid; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } - // Insert sale filter - if ($search_sale > 0) { - $sql .= " AND sc.fk_user = ".$search_sale; - } - // Add sql filters - if ($sqlfilters) { - if (!DolibarrApi::_checkFilters($sqlfilters)) { - throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); - } - $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; - $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; - } + // Insert sale filter + if ($search_sale > 0) { + $sql .= " AND sc.fk_user = ".$search_sale; + } + // Add sql filters + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { + throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); + } + $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; + $sql .= " AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")"; + } - $sql .= $this->db->order($sortfield, $sortorder); + $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) { - if ($page < 0) { - $page = 0; - } - $offset = $limit * $page; + if ($limit) { + if ($page < 0) { + $page = 0; + } + $offset = $limit * $page; - $sql .= $this->db->plimit($limit, $offset); - } + $sql .= $this->db->plimit($limit, $offset); + } - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) { - $obj = $this->db->fetch_object($result); - $ticket_static = new Ticket($this->db); - if ($ticket_static->fetch($obj->rowid)) { - if ($ticket_static->fk_user_assign > 0) { - $userStatic = new User($this->db); - $userStatic->fetch($ticket_static->fk_user_assign); - $ticket_static->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; - } - $obj_ret[] = $this->_cleanObjectDatas($ticket_static); - } - $i++; - } - } else { - throw new RestException(503, 'Error when retrieve ticket list'); - } - if (!count($obj_ret)) { - throw new RestException(404, 'No ticket found'); - } - return $obj_ret; - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) { + $obj = $this->db->fetch_object($result); + $ticket_static = new Ticket($this->db); + if ($ticket_static->fetch($obj->rowid)) { + if ($ticket_static->fk_user_assign > 0) { + $userStatic = new User($this->db); + $userStatic->fetch($ticket_static->fk_user_assign); + $ticket_static->fk_user_assign_string = $userStatic->firstname.' '.$userStatic->lastname; + } + $obj_ret[] = $this->_cleanObjectDatas($ticket_static); + } + $i++; + } + } else { + throw new RestException(503, 'Error when retrieve ticket list'); + } + if (!count($obj_ret)) { + throw new RestException(404, 'No ticket found'); + } + return $obj_ret; + } - /** - * Create ticket object - * - * @param array $request_data Request datas - * @return int ID of ticket - */ - public function post($request_data = null) - { - $ticketstatic = new Ticket($this->db); - if (!DolibarrApiAccess::$user->rights->ticket->write) { - throw new RestException(401); - } - // Check mandatory fields - $result = $this->_validate($request_data); + /** + * Create ticket object + * + * @param array $request_data Request datas + * @return int ID of ticket + */ + public function post($request_data = null) + { + $ticketstatic = new Ticket($this->db); + if (!DolibarrApiAccess::$user->rights->ticket->write) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validate($request_data); - foreach ($request_data as $field => $value) { - $this->ticket->$field = $value; - } - if (empty($this->ticket->ref)) { - $this->ticket->ref = $ticketstatic->getDefaultRef(); - } - if (empty($this->ticket->track_id)) { - $this->ticket->track_id = generate_random_id(16); - } + foreach ($request_data as $field => $value) { + $this->ticket->$field = $value; + } + if (empty($this->ticket->ref)) { + $this->ticket->ref = $ticketstatic->getDefaultRef(); + } + if (empty($this->ticket->track_id)) { + $this->ticket->track_id = generate_random_id(16); + } - if ($this->ticket->create(DolibarrApiAccess::$user) < 0) { - throw new RestException(500, "Error creating ticket", array_merge(array($this->ticket->error), $this->ticket->errors)); - } + if ($this->ticket->create(DolibarrApiAccess::$user) < 0) { + throw new RestException(500, "Error creating ticket", array_merge(array($this->ticket->error), $this->ticket->errors)); + } - return $this->ticket->id; - } + return $this->ticket->id; + } - /** - * Create ticket object - * - * @param array $request_data Request datas - * @return int ID of ticket - * - */ - public function postNewMessage($request_data = null) - { - $ticketstatic = new Ticket($this->db); - if (!DolibarrApiAccess::$user->rights->ticket->write) { - throw new RestException(401); - } - // Check mandatory fields - $result = $this->_validateMessage($request_data); + /** + * Create ticket object + * + * @param array $request_data Request datas + * @return int ID of ticket + * + */ + public function postNewMessage($request_data = null) + { + $ticketstatic = new Ticket($this->db); + if (!DolibarrApiAccess::$user->rights->ticket->write) { + throw new RestException(401); + } + // Check mandatory fields + $result = $this->_validateMessage($request_data); - foreach ($request_data as $field => $value) { - $this->ticket->$field = $value; - } - $ticketMessageText = $this->ticket->message; - $result = $this->ticket->fetch('', '', $this->ticket->track_id); - if (!$result) { - throw new RestException(404, 'Ticket not found'); - } - $this->ticket->message = $ticketMessageText; - if (!$this->ticket->createTicketMessage(DolibarrApiAccess::$user)) { - throw new RestException(500); - } - return $this->ticket->id; - } + foreach ($request_data as $field => $value) { + $this->ticket->$field = $value; + } + $ticketMessageText = $this->ticket->message; + $result = $this->ticket->fetch('', '', $this->ticket->track_id); + if (!$result) { + throw new RestException(404, 'Ticket not found'); + } + $this->ticket->message = $ticketMessageText; + if (!$this->ticket->createTicketMessage(DolibarrApiAccess::$user)) { + throw new RestException(500); + } + return $this->ticket->id; + } - /** - * Update ticket - * - * @param int $id Id of ticket to update - * @param array $request_data Datas - * @return int - * - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->ticket->write) { - throw new RestException(401); - } + /** + * Update ticket + * + * @param int $id Id of ticket to update + * @param array $request_data Datas + * @return int + * + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->ticket->write) { + throw new RestException(401); + } - $result = $this->ticket->fetch($id); - if (!$result) { - throw new RestException(404, 'Ticket not found'); - } + $result = $this->ticket->fetch($id); + if (!$result) { + throw new RestException(404, 'Ticket not found'); + } - if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - foreach ($request_data as $field => $value) { - $this->ticket->$field = $value; - } + foreach ($request_data as $field => $value) { + $this->ticket->$field = $value; + } - if ($this->ticket->update($id, DolibarrApiAccess::$user)) { - return $this->get($id); - } + if ($this->ticket->update($id, DolibarrApiAccess::$user)) { + return $this->get($id); + } - return false; - } + return false; + } - /** - * Delete ticket - * - * @param int $id Ticket ID - * @return array - * - */ - public function delete($id) - { - if (!DolibarrApiAccess::$user->rights->ticket->delete) { - throw new RestException(401); - } - $result = $this->ticket->fetch($id); - if (!$result) { - throw new RestException(404, 'Ticket not found'); - } + /** + * Delete ticket + * + * @param int $id Ticket ID + * @return array + * + */ + public function delete($id) + { + if (!DolibarrApiAccess::$user->rights->ticket->delete) { + throw new RestException(401); + } + $result = $this->ticket->fetch($id); + if (!$result) { + throw new RestException(404, 'Ticket not found'); + } - if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('ticket', $this->ticket->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if (!$this->ticket->delete($id)) { - throw new RestException(500); - } + if (!$this->ticket->delete($id)) { + throw new RestException(500); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'Ticket deleted' - ) - ); - } + return array( + 'success' => array( + 'code' => 200, + 'message' => 'Ticket deleted' + ) + ); + } - /** - * Validate fields before create or update object - * - * @param array $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validate($data) - { - $ticket = array(); - foreach (Tickets::$FIELDS as $field) { - if (!isset($data[$field])) { - throw new RestException(400, "$field field missing"); - } - $ticket[$field] = $data[$field]; - } - return $ticket; - } + /** + * Validate fields before create or update object + * + * @param array $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validate($data) + { + $ticket = array(); + foreach (Tickets::$FIELDS as $field) { + if (!isset($data[$field])) { + throw new RestException(400, "$field field missing"); + } + $ticket[$field] = $data[$field]; + } + return $ticket; + } - /** - * Validate fields before create or update object message - * - * @param array $data Data to validate - * @return array - * - * @throws RestException - */ - private function _validateMessage($data) - { - $ticket = array(); - foreach (Tickets::$FIELDS_MESSAGES as $field) { - if (!isset($data[$field])) { - throw new RestException(400, "$field field missing"); - } - $ticket[$field] = $data[$field]; - } - return $ticket; - } + /** + * Validate fields before create or update object message + * + * @param array $data Data to validate + * @return array + * + * @throws RestException + */ + private function _validateMessage($data) + { + $ticket = array(); + foreach (Tickets::$FIELDS_MESSAGES as $field) { + if (!isset($data[$field])) { + throw new RestException(400, "$field field missing"); + } + $ticket[$field] = $data[$field]; + } + return $ticket; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param Object $object Object to clean - * @return Object Object with cleaned properties - * - * @todo use an array for properties to clean - * - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param Object $object Object to clean + * @return Object Object with cleaned properties + * + * @todo use an array for properties to clean + * + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - // Other attributes to clean - $attr2clean = array( - "contact", - "contact_id", - "ref_previous", - "ref_next", - "ref_ext", - "table_element_line", - "statut", - "country", - "country_id", - "country_code", - "barcode_type", - "barcode_type_code", - "barcode_type_label", - "barcode_type_coder", - "mode_reglement_id", - "cond_reglement_id", - "cond_reglement", - "fk_delivery_address", - "shipping_method_id", - "modelpdf", - "fk_account", - "note_public", - "note_private", - "note", - "total_ht", - "total_tva", - "total_localtax1", - "total_localtax2", - "total_ttc", - "fk_incoterms", - "label_incoterms", - "location_incoterms", - "name", - "lastname", - "firstname", - "civility_id", - "canvas", - "cache_msgs_ticket", - "cache_logs_ticket", - "cache_types_tickets", - "cache_category_tickets", - "regeximgext", - "statuts_short", - "statuts" - ); - foreach ($attr2clean as $toclean) { - unset($object->$toclean); - } + // Other attributes to clean + $attr2clean = array( + "contact", + "contact_id", + "ref_previous", + "ref_next", + "ref_ext", + "table_element_line", + "statut", + "country", + "country_id", + "country_code", + "barcode_type", + "barcode_type_code", + "barcode_type_label", + "barcode_type_coder", + "mode_reglement_id", + "cond_reglement_id", + "cond_reglement", + "fk_delivery_address", + "shipping_method_id", + "modelpdf", + "fk_account", + "note_public", + "note_private", + "note", + "total_ht", + "total_tva", + "total_localtax1", + "total_localtax2", + "total_ttc", + "fk_incoterms", + "label_incoterms", + "location_incoterms", + "name", + "lastname", + "firstname", + "civility_id", + "canvas", + "cache_msgs_ticket", + "cache_logs_ticket", + "cache_types_tickets", + "cache_category_tickets", + "regeximgext", + "statuts_short", + "statuts" + ); + foreach ($attr2clean as $toclean) { + unset($object->$toclean); + } - // If object has lines, remove $db property - if (isset($object->lines) && count($object->lines) > 0) { - $nboflines = count($object->lines); - for ($i = 0; $i < $nboflines; $i++) { - $this->_cleanObjectDatas($object->lines[$i]); - } - } + // If object has lines, remove $db property + if (isset($object->lines) && count($object->lines) > 0) { + $nboflines = count($object->lines); + for ($i = 0; $i < $nboflines; $i++) { + $this->_cleanObjectDatas($object->lines[$i]); + } + } - // If object has linked objects, remove $db property - if (isset($object->linkedObjects) && count($object->linkedObjects) > 0) { - foreach ($object->linkedObjects as $type_object => $linked_object) { - foreach ($linked_object as $object2clean) { - $this->_cleanObjectDatas($object2clean); - } - } - } - return $object; - } + // If object has linked objects, remove $db property + if (isset($object->linkedObjects) && count($object->linkedObjects) > 0) { + foreach ($object->linkedObjects as $type_object => $linked_object) { + foreach ($linked_object as $object2clean) { + $this->_cleanObjectDatas($object2clean); + } + } + } + return $object; + } } diff --git a/htdocs/ticket/class/utils_diff.class.php b/htdocs/ticket/class/utils_diff.class.php index 2553158ff16..6edccdfa0ff 100644 --- a/htdocs/ticket/class/utils_diff.class.php +++ b/htdocs/ticket/class/utils_diff.class.php @@ -159,7 +159,7 @@ class Diff * @param string $start the starting index * @return array array of diff */ - private static function generatePartialDiff($table, $sequence1, $sequence2, $start) + private static function generatePartialDiff($table, $sequence1, $sequence2, $start) { // initialise the diff $diff = array(); diff --git a/htdocs/user/passwordforgotten.php b/htdocs/user/passwordforgotten.php index 24954992e90..789d67544a3 100644 --- a/htdocs/user/passwordforgotten.php +++ b/htdocs/user/passwordforgotten.php @@ -77,7 +77,7 @@ if ($action == 'validatenewpassword' && $username && $passwordhash) { // Clear session unset($_SESSION['dol_login']); - $_SESSION['dol_loginmesg'] = $langs->trans('NewPasswordValidated'); // Save message for the session page + $_SESSION['dol_loginmesg'] = $langs->trans('NewPasswordValidated'); // Save message for the session page $newpassword = $edituser->setPassword($user, $edituser->pass_temp, 0); dol_syslog("passwordforgotten.php new password for user->id=".$edituser->id." validated in database"); @@ -112,7 +112,7 @@ if ($action == 'buildnewpassword' && $username) if ($result <= 0 && $edituser->error == 'USERNOTFOUND') { $message = '
'; - if ($object->particulier || $private) - { - print ''.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName', 'name').''; - } else { + // Name, firstname + print '
'; + if ($object->particulier || $private) + { + print ''.$langs->trans('ThirdPartyName').' / '.$langs->trans('LastName', 'name').''; + } else { print ''.$form->editfieldkey('ThirdPartyName', 'name', '', $object, 0).''; - } - print ''.$langs->trans('Prefix').'
'.$langs->trans('Prefix').'
'.$form->editfieldkey('FirstName', 'firstname', '', $object, 0).'
'.$form->editfieldkey('FirstName', 'firstname', '', $object, 0).'
'.$form->editfieldkey('UserTitle', 'civility_id', '', $object, 0).''; - print $formcompany->select_civility($object->civility_id, 'civility_id', 'maxwidth100').'
'.$form->editfieldkey('UserTitle', 'civility_id', '', $object, 0).''; + print $formcompany->select_civility($object->civility_id, 'civility_id', 'maxwidth100').'
'.$form->editfieldkey('ProspectCustomer', 'customerprospect', '', $object, 0, 'string', '', 1).''; - $selected = (GETPOSTISSET('client') ?GETPOST('client', 'int') : $object->client); - print $formcompany->selectProspectCustomerType($selected); - print '
'.$form->editfieldkey('ProspectCustomer', 'customerprospect', '', $object, 0, 'string', '', 1).''; + $selected = (GETPOSTISSET('client') ?GETPOST('client', 'int') : $object->client); + print $formcompany->selectProspectCustomerType($selected); + print '
'.$form->editfieldkey('CustomerCode', 'customer_code', '', $object, 0).''; - print ''; + if (empty($tmpcode) && !empty($modCodeClient->code_auto)) $tmpcode = $modCodeClient->getNextValue($object, 0); + print ''; + print '
'; + print ''.$form->editfieldkey('CustomerCode', 'customer_code', '', $object, 0).''; + print '
'; $tmpcode = $object->code_client; - if (empty($tmpcode) && !empty($modCodeClient->code_auto)) $tmpcode = $modCodeClient->getNextValue($object, 0); - print ''; - print ''; - $s = $modCodeClient->getToolTip($langs, $object, 0); - print $form->textwithpicto('', $s, 1); - print '
'; - print '
'; + $s = $modCodeClient->getToolTip($langs, $object, 0); + print $form->textwithpicto('', $s, 1); + print '
'; + print '
'.$form->editfieldkey('Vendor', 'fournisseur', '', $object, 0, 'string', '', 1).''; - $default = -1; - if (!empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)) $default = 1; - print $form->selectyesno("fournisseur", (GETPOST('fournisseur', 'int') != '' ? GETPOST('fournisseur', 'int') : (GETPOST("type", 'alpha') == '' ? $default : $object->fournisseur)), 1, 0, (GETPOST("type", 'alpha') == '' ? 1 : 0)); - print '
'.$form->editfieldkey('Vendor', 'fournisseur', '', $object, 0, 'string', '', 1).''; + $default = -1; + if (!empty($conf->global->THIRDPARTY_SUPPLIER_BY_DEFAULT)) $default = 1; + print $form->selectyesno("fournisseur", (GETPOST('fournisseur', 'int') != '' ? GETPOST('fournisseur', 'int') : (GETPOST("type", 'alpha') == '' ? $default : $object->fournisseur)), 1, 0, (GETPOST("type", 'alpha') == '' ? 1 : 0)); + print '
'; - if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) - { - print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0); - } - print ''; - if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) - { - print '
'; - $tmpcode = $object->code_fournisseur; - if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) $tmpcode = $modCodeFournisseur->getNextValue($object, 1); - print ''; - print ''; - $s = $modCodeFournisseur->getToolTip($langs, $object, 1); - print $form->textwithpicto('', $s, 1); - print '
'; - } - print '
'; + if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) + { + print $form->editfieldkey('SupplierCode', 'supplier_code', '', $object, 0); + } + print ''; + if (!empty($conf->fournisseur->enabled) && !empty($user->rights->fournisseur->lire)) + { + print '
'; + $tmpcode = $object->code_fournisseur; + if (empty($tmpcode) && !empty($modCodeFournisseur->code_auto)) $tmpcode = $modCodeFournisseur->getNextValue($object, 1); + print ''; + print ''; + $s = $modCodeFournisseur->getToolTip($langs, $object, 1); + print $form->textwithpicto('', $s, 1); + print '
'; + } + print '
'.$form->editfieldkey('Status', 'status', '', $object, 0).''; - print $form->selectarray('status', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), 1); - print '
'.$form->editfieldkey('Status', 'status', '', $object, 0).''; + print $form->selectarray('status', array('0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), 1); + print '
'.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).''; - print '
'.$form->editfieldkey('Gencod', 'barcode', '', $object, 0).''; + print '
'; - print $form->editfieldkey('Address', 'address', '', $object, 0); - print ''; - print ''; - print $form->widgetForTranslation("address", $object, $permissiontoadd, 'textarea', 'alphanohtml', 'quatrevingtpercent'); - print '
'; + print $form->editfieldkey('Address', 'address', '', $object, 0); + print ''; + print ''; + print $form->widgetForTranslation("address", $object, $permissiontoadd, 'textarea', 'alphanohtml', 'quatrevingtpercent'); + print '
'.$form->editfieldkey('Zip', 'zipcode', '', $object, 0).''; - print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent'); - print '
'.$form->editfieldkey('Town', 'town', '', $object, 0).''; - print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent'); - print $form->widgetForTranslation("town", $object, $permissiontoadd, 'string', 'alphanohtml', 'maxwidth100 quatrevingtpercent'); - print '
'.$form->editfieldkey('Zip', 'zipcode', '', $object, 0).''; + print $formcompany->select_ziptown($object->zip, 'zipcode', array('town', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent'); + print '
'.$form->editfieldkey('Town', 'town', '', $object, 0).''; + print $formcompany->select_ziptown($object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id'), 0, 0, '', 'maxwidth100 quatrevingtpercent'); + print $form->widgetForTranslation("town", $object, $permissiontoadd, 'string', 'alphanohtml', 'maxwidth100 quatrevingtpercent'); + print '
'.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).''; - print img_picto('', 'globe-americas', 'class="paddingrightonly"'); - print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 widthcentpercentminusx'); - if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - print '
'.$form->editfieldkey('Country', 'selectcountry_id', '', $object, 0).''; + print img_picto('', 'globe-americas', 'class="paddingrightonly"'); + print $form->select_country((GETPOSTISSET('country_id') ? GETPOST('country_id') : $object->country_id), 'country_id', '', 0, 'minwidth300 widthcentpercentminusx'); + if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print '
'.$form->editfieldkey('Region-State', 'state_id', '', $object, 0).''; - } else { - print '
'.$form->editfieldkey('State', 'state_id', '', $object, 0).''; - } + // State + if (empty($conf->global->SOCIETE_DISABLE_STATE)) + { + if (!empty($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT) && ($conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 1 || $conf->global->MAIN_SHOW_REGION_IN_STATE_SELECT == 2)) + { + print '
'.$form->editfieldkey('Region-State', 'state_id', '', $object, 0).''; + } else { + print '
'.$form->editfieldkey('State', 'state_id', '', $object, 0).''; + } - if ($object->country_id) print $formcompany->select_state($object->state_id, $object->country_code); - else print $countrynotdefined; - print '
'.$form->editfieldkey('Phone', 'phone', '', $object, 0).'
'.$form->editfieldkey('Fax', 'fax', '', $object, 0).'
'.$form->editfieldkey('Phone', 'phone', '', $object, 0).'
'.$form->editfieldkey('Fax', 'fax', '', $object, 0).'
'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '', $conf->global->SOCIETE_EMAIL_MANDATORY).''.img_picto('', 'object_email').'
'.$form->editfieldkey('Web', 'url', '', $object, 0).''.img_picto('', 'globe').'
'.$form->editfieldkey('EMail', 'email', '', $object, 0, 'string', '', $conf->global->SOCIETE_EMAIL_MANDATORY).''.img_picto('', 'object_email').'
'.$form->editfieldkey('Web', 'url', '', $object, 0).''.img_picto('', 'globe').'
'; - print ''; - print '
'; + print ''; + print '
'.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', (empty($conf->global->$idprof_mandatory) ? 0 : 1)).''; + $idprof_mandatory = 'SOCIETE_IDPROF'.($i).'_MANDATORY'; + print ''.$form->editfieldkey($idprof, $key, '', $object, 0, 'string', '', (empty($conf->global->$idprof_mandatory) ? 0 : 1)).''; - print $formcompany->get_input_id_prof($i, $key, $object->$key, $object->country_code); - print '
'.$form->editfieldkey('VATIsUsed', 'assujtva_value', '', $object, 0).''; - print $form->selectyesno('assujtva_value', GETPOSTISSET('assujtva_value') ?GETPOST('assujtva_value', 'int') : 1, 1); // Assujeti par defaut en creation - print '
'.$form->editfieldkey('VATIntra', 'intra_vat', '', $object, 0).''; - $s = ''; + // Vat is used + print '
'.$form->editfieldkey('VATIsUsed', 'assujtva_value', '', $object, 0).''; + print $form->selectyesno('assujtva_value', GETPOSTISSET('assujtva_value') ?GETPOST('assujtva_value', 'int') : 1, 1); // Assujeti par defaut en creation + print '
'.$form->editfieldkey('VATIntra', 'intra_vat', '', $object, 0).''; + $s = ''; - if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object)) - { - $s .= ' '; + if (empty($conf->global->MAIN_DISABLEVATCHECK) && isInEEC($object)) + { + $s .= ' '; - if (!empty($conf->use_javascript_ajax)) - { - $widthpopup = 600; - if (!empty($conf->dol_use_jmobile)) $widthpopup = 350; - $heightpopup = 400; - print "\n"; - print ''; - print "\n"; - $s .= ''.$langs->trans("VATIntraCheck").''; - $s = $form->textwithpicto($s, $langs->trans("VATIntraCheckDesc", $langs->transnoentitiesnoconv("VATIntraCheck")), 1); - } else { - $s .= 'country_id).'" target="_blank">'.img_picto($langs->trans("VATIntraCheckableOnEUSite"), 'help').''; - } - } - print $s; - print '
'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; - print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1); - print '
'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; - print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1); - print '
'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; - print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1); - print '
'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; - print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1); - print '
'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; + print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1); + print '
'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; + print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1); + print '
'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).''; + print $form->selectyesno('localtax1assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX1 : 0), 1); + print '
'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).''; + print $form->selectyesno('localtax2assuj_value', (isset($conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2) ? $conf->global->THIRDPARTY_DEFAULT_USELOCALTAX2 : 0), 1); + print '
'.$form->editfieldkey('ThirdPartyType', 'typent_id', '', $object, 0).'browser->layout == 'phone' ? ' colspan="3"' : '').'>'."\n"; - $sortparam = (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), $object->typent_id, 0, 0, 0, '', 0, 0, 0, $sortparam); - if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - print '
'.$form->editfieldkey('Workforce', 'effectif_id', '', $object, 0).'browser->layout == 'phone' ? ' colspan="3"' : '').'>'; - print $form->selectarray("effectif_id", $formcompany->effectif_array(0), $object->effectif_id); - if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); - print '
'.$form->editfieldkey('ThirdPartyType', 'typent_id', '', $object, 0).'browser->layout == 'phone' ? ' colspan="3"' : '').'>'."\n"; + $sortparam = (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), $object->typent_id, 0, 0, 0, '', 0, 0, 0, $sortparam); + if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print '
'.$form->editfieldkey('Workforce', 'effectif_id', '', $object, 0).'browser->layout == 'phone' ? ' colspan="3"' : '').'>'; + print $form->selectarray("effectif_id", $formcompany->effectif_array(0), $object->effectif_id); + if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + print '
'.$form->editfieldkey('JuridicalStatus', 'forme_juridique_code', '', $object, 0).''; - if ($object->country_id) - { - print $formcompany->select_juridicalstatus($object->forme_juridique_code, $object->country_code, '', 'forme_juridique_code'); - } else { - print $countrynotdefined; - } - print '
'.$form->editfieldkey('JuridicalStatus', 'forme_juridique_code', '', $object, 0).''; + if ($object->country_id) + { + print $formcompany->select_juridicalstatus($object->forme_juridique_code, $object->country_code, '', 'forme_juridique_code'); + } else { + print $countrynotdefined; + } + print '
'.$form->editfieldkey('Capital', 'capital', '', $object, 0).' '; - print ''.$langs->trans("Currency".$conf->currency).'
'.$form->editfieldkey('Capital', 'capital', '', $object, 0).' '; + print ''.$langs->trans("Currency".$conf->currency).'
'.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).''."\n"; - print $formadmin->select_language(GETPOST('default_lang', 'alpha') ? GETPOST('default_lang', 'alpha') : ($object->default_lang ? $object->default_lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone'); - print '
'.$form->editfieldkey('DefaultLang', 'default_lang', '', $object, 0).''."\n"; + print $formadmin->select_language(GETPOST('default_lang', 'alpha') ? GETPOST('default_lang', 'alpha') : ($object->default_lang ? $object->default_lang : ''), 'default_lang', 0, 0, 1, 0, 0, 'maxwidth200onsmartphone'); + print '
'.$form->editfieldkey('IncotermLabel', 'incoterm_id', '', $object, 0).''; - print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : '')); + print ''; + print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : '')); print '