From 1a407e4c229e7e26e4e46667d6362027e1651fa9 Mon Sep 17 00:00:00 2001 From: ptibogxiv Date: Sun, 4 Oct 2020 22:09:40 +0200 Subject: [PATCH 01/69] NEW set entity when creating invoice on takepos usefull for marketplace, coworking, multibranding shop --- htdocs/takepos/invoice.php | 1 + 1 file changed, 1 insertion(+) diff --git a/htdocs/takepos/invoice.php b/htdocs/takepos/invoice.php index d3ec86a7268..3b8cf455e5c 100644 --- a/htdocs/takepos/invoice.php +++ b/htdocs/takepos/invoice.php @@ -284,6 +284,7 @@ if (($action == "addline" || $action == "freezone") && $placeid == 0) $invoice->date = dol_now(); $invoice->module_source = 'takepos'; $invoice->pos_source = $_SESSION["takeposterminal"]; + $invoice->entity = !empty($_SESSION["takeposinvoiceentity"])?$_SESSION["takeposinvoiceentity"]:$conf->entity; if ($invoice->socid <= 0) { From 050a4770d3aa7bb386971c8904bb04329ced3841 Mon Sep 17 00:00:00 2001 From: Alexandre SPANGARO Date: Tue, 6 Oct 2020 10:04:15 +0200 Subject: [PATCH 02/69] WIP NEW Add clone functionality on miscellaneous payment --- .../bank/class/paymentvarious.class.php | 19 +++++ htdocs/compta/bank/various_payment/card.php | 69 ++++++++++++++++++- htdocs/langs/en_US/banks.lang | 1 + 3 files changed, 87 insertions(+), 2 deletions(-) diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index 14466915d76..712fb3d8113 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -263,6 +263,7 @@ class PaymentVarious extends CommonObject $this->subledger_account = $obj->subledger_account; $this->accountancy_code = $obj->accountancy_code; $this->fk_project = $obj->fk_project; + $this->accountid = 1; // to clone $this->fk_bank = $obj->fk_bank; $this->fk_user_author = $obj->fk_user_author; $this->fk_user_modif = $obj->fk_user_modif; @@ -338,6 +339,24 @@ class PaymentVarious extends CommonObject $this->fk_user_modif = ''; } + /** + * Check if a miscellaneous payment can be created into database + * + * @return boolean True or false + */ + public function check() + { + $newamount = price2num($this->amount, 'MT'); + + // Validation parametres + if (!$newamount > 0 || empty($this->datep)) + { + return false; + } + + return true; + } + /** * Create in database * diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php index 371dbaa65e2..67a9590c91d 100644 --- a/htdocs/compta/bank/various_payment/card.php +++ b/htdocs/compta/bank/various_payment/card.php @@ -41,8 +41,9 @@ $langs->loadLangs(array("compta", "banks", "bills", "users", "accountancy", "cat // Get parameters $id = GETPOST('id', 'int'); -$action = GETPOST('action', 'alpha'); -$cancel = GETPOST('cancel', 'aZ09'); +$action = GETPOST('action', 'alpha'); +$confirm = GETPOST('confirm'); +$cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); $accountid = GETPOST("accountid") > 0 ? GETPOST("accountid", "int") : 0; @@ -225,6 +226,53 @@ if (empty($reshook)) } } +// Action clone object +if ($action == 'confirm_clone' && $confirm != 'yes') { $action = ''; } + +if ($action == 'confirm_clone' && $confirm == 'yes' && ($user->rights->banque->modifier)) +{ + $db->begin(); + + $originalId = $id; + + $object->fetch($id); + + if ($object->id > 0) + { + $object->id = $object->ref = null; + + if (GETPOST('clone_label', 'alphanohtml')) { + $object->label = GETPOST('clone_label', 'alphanohtml'); + } else { + $object->label = $langs->trans("CopyOf").' '.$object->label; + } + + $newdatepayment = dol_mktime(0, 0, 0, GETPOST('clone_date_paymentmonth', 'int'), GETPOST('clone_date_paymentday', 'int'), GETPOST('clone_date_paymentyear', 'int')); + if ($newdatepayment) $object->datep = $newdatepayment; + + if ($object->check()) + { + $id = $object->create($user); + if ($id > 0) + { + $db->commit(); + $db->close(); + + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + $id = $originalId; + $db->rollback(); + + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } else { + $db->rollback(); + dol_print_error($db, $object->error); + } +} + /* * View @@ -419,6 +467,17 @@ if ($id) $head = various_payment_prepare_head($object); + // Clone confirmation + if ($action === 'clone') + { + $formquestion = array( + array('type' => 'text', 'name' => 'clone_label', 'label' => $langs->trans("Label"), 'value' => $langs->trans("CopyOf").' '.$object->label), + ); + $formquestion[] = array('type' => 'date', 'name' => 'clone_date_payment', 'label' => $langs->trans("DatePayment"), 'value' => -1); + + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneVariousPayment', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 220); + } + dol_fiche_head($head, 'card', $langs->trans("VariousPayment"), -1, $object->picto); $morehtmlref = '
'; @@ -542,6 +601,12 @@ if ($id) // TODO // Add button modify + // Clone + if ($user->rights->banque->modifier) + { + print '"; + } + // Delete if (empty($object->rappro)) { diff --git a/htdocs/langs/en_US/banks.lang b/htdocs/langs/en_US/banks.lang index 3cfa7ad2538..ffe5ee9ca1c 100644 --- a/htdocs/langs/en_US/banks.lang +++ b/htdocs/langs/en_US/banks.lang @@ -168,6 +168,7 @@ ShowVariousPayment=Show miscellaneous payment AddVariousPayment=Add miscellaneous payment VariousPaymentId=Miscellaneous payment ID VariousPaymentLabel=Miscellaneous payment label +ConfirmCloneVariousPayment=Confirm the clone of a miscellaneous payment SEPAMandate=SEPA mandate YourSEPAMandate=Your SEPA mandate FindYourSEPAMandate=This is your SEPA mandate to authorize our company to make direct debit order to your bank. Return it signed (scan of the signed document) or send it by mail to From 3ceb5c217f48af4f221447ce8398d8838a412d1b Mon Sep 17 00:00:00 2001 From: "Sekan, Tobias" Date: Tue, 6 Oct 2020 12:56:28 +0200 Subject: [PATCH 03/69] Show count on project overview tab --- htdocs/core/lib/project.lib.php | 68 ++++++++++++++++++--------- htdocs/projet/class/project.class.php | 39 +++++++++++++++ 2 files changed, 85 insertions(+), 22 deletions(-) diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index 782e18151b2..91cf281c83c 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -30,23 +30,23 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; /** * Prepare array with list of tabs * - * @param Object $object Object related to tabs - * @return array Array of tabs to show + * @param Project $object Object related to tabs + * @return array Array of tabs to show */ -function project_prepare_head($object) +function project_prepare_head(Project $project) { global $db, $langs, $conf, $user; $h = 0; $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/projet/card.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/card.php?id='.$project->id; $head[$h][1] = $langs->trans("Project"); $head[$h][2] = 'project'; $h++; - $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); - $head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$object->id; + $nbContact = count($project->liste_contact(-1, 'internal')) + count($project->liste_contact(-1, 'external')); + $head[$h][0] = DOL_URL_ROOT.'/projet/contact.php?id='.$project->id; $head[$h][1] = $langs->trans("ProjectContact"); if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; $head[$h][2] = 'contact'; @@ -55,12 +55,12 @@ function project_prepare_head($object) if (empty($conf->global->PROJECT_HIDE_TASKS)) { // Then tab for sub level of projet, i mean tasks - $head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/tasks.php?id='.$project->id; $head[$h][1] = $langs->trans("Tasks"); require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; $taskstatic = new Task($db); - $nbTasks = count($taskstatic->getTasksArray(0, 0, $object->id, 0, 0)); + $nbTasks = count($taskstatic->getTasksArray(0, 0, $project->id, 0, 0)); if ($nbTasks > 0) $head[$h][1] .= ''.($nbTasks).''; $head[$h][2] = 'tasks'; $h++; @@ -71,7 +71,7 @@ function project_prepare_head($object) //$sql .= " WHERE t.fk_user = u.rowid AND t.fk_task = pt.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt"; $sql .= " WHERE t.fk_task = pt.rowid"; - $sql .= " AND pt.fk_projet =".$object->id; + $sql .= " AND pt.fk_projet =".$project->id; $resql = $db->query($sql); if ($resql) { @@ -79,7 +79,7 @@ function project_prepare_head($object) if ($obj) $nbTimeSpent = 1; } else dol_print_error($db); - $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?withproject=1&projectid='.$project->id; $head[$h][1] = $langs->trans("TimeSpent"); if ($nbTimeSpent > 0) $head[$h][1] .= '...'; $head[$h][2] = 'timespent'; @@ -91,8 +91,32 @@ function project_prepare_head($object) || !empty($conf->facture->enabled) || !empty($conf->contrat->enabled) || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) { - $head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$object->id; + $count = 0; + + if (!empty($conf->propal->enabled)) $count += $project->getElementCount('propal', 'propal'); + if (!empty($conf->commande->enabled)) $count += $project->getElementCount('order', 'commande'); + if (!empty($conf->facture->enabled)) $count += $project->getElementCount('invoice', 'facture'); + if (!empty($conf->facture->enabled)) $count += $project->getElementCount('invoice_predefined', 'facture_rec'); + if (!empty($conf->supplier_proposal->enabled)) $count += $project->getElementCount('proposal_supplier', 'supplier_proposal'); + if (!empty($conf->supplier_order->enabled)) $count += $project->getElementCount('order_supplier', 'commande_fournisseur'); + if (!empty($conf->supplier_invoice->enabled)) $count += $project->getElementCount('invoice_supplier', 'facture_fourn'); + if (!empty($conf->contrat->enabled)) $count += $project->getElementCount('contract', 'contrat'); + if (!empty($conf->ficheinter->enabled)) $count += $project->getElementCount('intervention', 'fichinter'); + if (!empty($conf->expedition->enabled)) $count += $project->getElementCount('shipping', 'expedition'); + if (!empty($conf->mrp->enabled)) $count += $project->getElementCount('mrp', 'mrp_mo', 'fk_project'); + if (!empty($conf->deplacement->enabled)) $count += $project->getElementCount('trip', 'deplacement'); + if (!empty($conf->expensereport->enabled)) $count += $project->getElementCount('expensereport', 'expensereport'); + if (!empty($conf->don->enabled)) $count += $project->getElementCount('donation', 'don'); + if (!empty($conf->loan->enabled)) $count += $project->getElementCount('loan', 'loan'); + if (!empty($conf->tax->enabled)) $count += $project->getElementCount('chargesociales', 'chargesociales'); + if (!empty($conf->projet->enabled)) $count += $project->getElementCount('project_task', 'projet_task'); + if (!empty($conf->stock->enabled)) $count += $project->getElementCount('stock_mouvement', 'stock'); + if (!empty($conf->salaries->enabled)) $count += $project->getElementCount('salaries', 'payment_salary'); + if (!empty($conf->banque->enabled)) $count += $project->getElementCount('variouspayment', 'payment_various'); + + $head[$h][0] = DOL_URL_ROOT.'/projet/element.php?id='.$project->id; $head[$h][1] = $langs->trans("ProjectOverview"); + if ($count > 0) $head[$h][1] .= ''.$count.''; $head[$h][2] = 'element'; $h++; } @@ -101,15 +125,15 @@ function project_prepare_head($object) // 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, 'project'); + complete_head_from_modules($conf, $langs, $project, $head, $h, 'project'); 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.'/projet/note.php?id='.$object->id; + if (!empty($project->note_private)) $nbNote++; + if (!empty($project->note_public)) $nbNote++; + $head[$h][0] = DOL_URL_ROOT.'/projet/note.php?id='.$project->id; $head[$h][1] = $langs->trans('Notes'); if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; $head[$h][2] = 'notes'; @@ -118,10 +142,10 @@ function project_prepare_head($object) require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($object->ref); + $upload_dir = $conf->projet->dir_output."/".dol_sanitizeFileName($project->ref); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $object->element, $object->id); - $head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$object->id; + $nbLinks = Link::count($db, $project->element, $project->id); + $head[$h][0] = DOL_URL_ROOT.'/projet/document.php?id='.$project->id; $head[$h][1] = $langs->trans('Documents'); if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; $head[$h][2] = 'document'; @@ -130,15 +154,15 @@ function project_prepare_head($object) // Manage discussion if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) { - $nbComments = $object->getNbComments(); - $head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$object->id; + $nbComments = $project->getNbComments(); + $head[$h][0] = DOL_URL_ROOT.'/projet/comment.php?id='.$project->id; $head[$h][1] = $langs->trans("CommentLink"); if ($nbComments > 0) $head[$h][1] .= ''.$nbComments.''; $head[$h][2] = 'project_comment'; $h++; } - $head[$h][0] = DOL_URL_ROOT.'/projet/info.php?id='.$object->id; + $head[$h][0] = DOL_URL_ROOT.'/projet/info.php?id='.$project->id; $head[$h][1] .= $langs->trans("Events"); if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { @@ -148,7 +172,7 @@ function project_prepare_head($object) $head[$h][2] = 'agenda'; $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'project', 'remove'); + complete_head_from_modules($conf, $langs, $project, $head, $h, 'project', 'remove'); return $head; } diff --git a/htdocs/projet/class/project.class.php b/htdocs/projet/class/project.class.php index 30a2a0c242b..83bd4e3b2a4 100644 --- a/htdocs/projet/class/project.class.php +++ b/htdocs/projet/class/project.class.php @@ -806,6 +806,45 @@ class Project extends CommonObject } } + /** + * Return the count of a type of linked elements of this project + * + * @param string $type The type of the linked elements (e.g. 'propal', 'order', 'invoice', 'order_supplier', 'invoice_supplier') + * @param string $tablename The name of table associated of the type + * @param string $projectkey (optional) Equivalent key to fk_projet for actual type + * @return integer The count of the linked elements (the count is zero on request error too) + */ + public function getElementCount($type, $tablename, $projectkey = 'fk_projet') + { + if ($this->id <= 0) return 0; + + if ($type == 'agenda') { + $sql = "SELECT COUNT(id) as nb FROM ".MAIN_DB_PREFIX."actioncomm WHERE fk_project = ".$this->id." AND entity IN (".getEntity('agenda').")"; + } elseif ($type == 'expensereport') { + $sql = "SELECT COUNT(ed.rowid) as nb FROM ".MAIN_DB_PREFIX."expensereport as e, ".MAIN_DB_PREFIX."expensereport_det as ed WHERE e.rowid = ed.fk_expensereport AND e.entity IN (".getEntity('expensereport').") AND ed.fk_projet = ".$this->id; + } elseif ($type == 'project_task') { + $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt WHERE pt.fk_projet = ".$this->id; + } elseif ($type == 'project_task_time') { // Case we want to duplicate line foreach user + $sql = "SELECT DISTINCT COUNT(pt.rowid) as nb FROM ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."projet_task_time as ptt WHERE pt.rowid = ptt.fk_task AND pt.fk_projet = ".$this->id; + } elseif ($type == 'stock_mouvement') { + $sql = 'SELECT COUNT(ms.rowid) as nb FROM '.MAIN_DB_PREFIX."stock_mouvement as ms, ".MAIN_DB_PREFIX."entrepot as e WHERE e.rowid = ms.fk_entrepot AND e.entity IN (".getEntity('stock').") AND ms.origintype = 'project' AND ms.fk_origin = ".$this->id." AND ms.type_mouvement = 1"; + } elseif ($type == 'loan') { + $sql = 'SELECT COUNT(l.rowid) as nb FROM '.MAIN_DB_PREFIX."loan as l WHERE l.entity IN (".getEntity('loan').") AND l.fk_projet = ".$this->id; + } else { + $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX.$tablename." WHERE ".$projectkey." = ".$this->id." AND entity IN (".getEntity($type).")"; + } + + $result = $this->db->query($sql); + + if (!$result) return 0; + + $obj = $this->db->fetch_object($result); + + $this->db->free($result); + + return $obj->nb; + } + /** * Delete tasks with no children first, then task with children recursively * From 503f190fd47e23145d5490153b0200bd8b6802da Mon Sep 17 00:00:00 2001 From: Alexandre SPANGARO Date: Tue, 6 Oct 2020 14:39:10 +0200 Subject: [PATCH 04/69] Fix --- htdocs/compta/bank/class/paymentvarious.class.php | 1 - htdocs/compta/bank/various_payment/card.php | 12 ++++++++++-- htdocs/compta/bank/various_payment/list.php | 4 ++-- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index 712fb3d8113..064f8ac8d41 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -263,7 +263,6 @@ class PaymentVarious extends CommonObject $this->subledger_account = $obj->subledger_account; $this->accountancy_code = $obj->accountancy_code; $this->fk_project = $obj->fk_project; - $this->accountid = 1; // to clone $this->fk_bank = $obj->fk_bank; $this->fk_user_author = $obj->fk_user_author; $this->fk_user_modif = $obj->fk_user_modif; diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php index 67a9590c91d..62d022c0157 100644 --- a/htdocs/compta/bank/various_payment/card.php +++ b/htdocs/compta/bank/various_payment/card.php @@ -248,7 +248,13 @@ if ($action == 'confirm_clone' && $confirm == 'yes' && ($user->rights->banque->m } $newdatepayment = dol_mktime(0, 0, 0, GETPOST('clone_date_paymentmonth', 'int'), GETPOST('clone_date_paymentday', 'int'), GETPOST('clone_date_paymentyear', 'int')); + $newdatevalue = dol_mktime(0, 0, 0, GETPOST('clone_date_valuemonth', 'int'), GETPOST('clone_date_valueday', 'int'), GETPOST('clone_date_valueyear', 'int')); if ($newdatepayment) $object->datep = $newdatepayment; + if (!empty($newdatevalue)) { + $object->datev = $newdatevalue; + } else { + $object->datev = $newdatepayment; + } if ($object->check()) { @@ -473,9 +479,11 @@ if ($id) $formquestion = array( array('type' => 'text', 'name' => 'clone_label', 'label' => $langs->trans("Label"), 'value' => $langs->trans("CopyOf").' '.$object->label), ); - $formquestion[] = array('type' => 'date', 'name' => 'clone_date_payment', 'label' => $langs->trans("DatePayment"), 'value' => -1); + $formquestion[] = array('type' => 'date', 'tdclass'=>'fieldrequired', 'name' => 'clone_date_payment', 'label' => $langs->trans("DatePayment"), 'value' => -1); + $formquestion[] = array('type' => 'date', 'name' => 'clone_date_value', 'label' => $langs->trans("DateValue"), 'value' => -1); + $formquestion[] = array('type' => 'other', 'tdclass'=>'fieldrequired', 'name' => 'accountid', 'label' => $langs->trans("BankAccount"), 'value' => $form->select_comptes($accountid, "accountid", 0, '', 1)); - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneVariousPayment', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 220); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneVariousPayment', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 300); } dol_fiche_head($head, 'card', $langs->trans("VariousPayment"), -1, $object->picto); diff --git a/htdocs/compta/bank/various_payment/list.php b/htdocs/compta/bank/various_payment/list.php index 54216f06358..2fb2c56fc46 100644 --- a/htdocs/compta/bank/various_payment/list.php +++ b/htdocs/compta/bank/various_payment/list.php @@ -490,9 +490,9 @@ if ($result) print $accountstatic->getNomUrl(1); } else { print ' '; - print ''; - if (!$i) $totalarray['nbfield']++; } + print ''; + if (!$i) $totalarray['nbfield']++; } // Bank entry From b0d20f92dcd1ae14932428793950ef6b498cc7ec Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 6 Oct 2020 17:32:55 +0200 Subject: [PATCH 05/69] FIX autofocus on first setup --- htdocs/admin/company.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index 88f6034a3b6..00bd17e865f 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -421,7 +421,7 @@ print ''.$langs->trans( // Name print ''; -print 'global->MAIN_OPTIMIZEFORTEXTBROWSER) ? '' : ' autofocus="autofocus"').'>'."\n"; +print 'global->MAIN_INFO_SOCIETE_NOM) ? ' autofocus="autofocus"' : '').'>'."\n"; // Address print ''; From 04f8de41884339f9686edb33bc10298b9c66a80d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 6 Oct 2020 17:59:31 +0200 Subject: [PATCH 06/69] Remove dependency --- htdocs/core/modules/modSocialNetworks.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/modules/modSocialNetworks.class.php b/htdocs/core/modules/modSocialNetworks.class.php index 67be8eef281..fd426323e0e 100644 --- a/htdocs/core/modules/modSocialNetworks.class.php +++ b/htdocs/core/modules/modSocialNetworks.class.php @@ -66,7 +66,7 @@ class modSocialNetworks extends DolibarrModules // Dependencies $this->hidden = !empty($conf->global->MODULE_SOCIALNETWORKS_DISABLED); // A condition to hide module - $this->depends = array('modSociete'); // List of module class names as string that must be enabled if this module is enabled + $this->depends = array(); // List of module class names as string that must be enabled if this module is enabled $this->requiredby = array(); // List of module ids to disable if this one is disabled $this->conflictwith = array(); // List of module class names as string this module is in conflict with $this->phpmin = array(5, 4); // Minimum version of PHP required by module From 79e94e3a2ccec3778fbcaade3bb478ce53cd3360 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 6 Oct 2020 21:59:38 +0200 Subject: [PATCH 07/69] Removed unexpected file --- build/makepack-dolibarr.pl | 3 +++ 1 file changed, 3 insertions(+) diff --git a/build/makepack-dolibarr.pl b/build/makepack-dolibarr.pl index 24b32dcff91..85212d9c5ba 100755 --- a/build/makepack-dolibarr.pl +++ b/build/makepack-dolibarr.pl @@ -620,6 +620,9 @@ if ($nboftargetok) { $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/fonts/utils`; $ret=`rm -fr $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/tools`; $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/tecnickcom/tcpdf/LICENSE.TXT`; + + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/includes/autoload.php`; + $ret=`rm -f $BUILDROOT/$PROJECT/htdocs/theme/common/octicons/LICENSE`; } From 13ec304b79560bdbcaad58125911e787e6563775 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 6 Oct 2020 23:30:51 +0200 Subject: [PATCH 08/69] Update project.lib.php --- htdocs/core/lib/project.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index 91cf281c83c..29a522e7335 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; /** * Prepare array with list of tabs * - * @param Project $object Object related to tabs + * @param Project $project Object related to tabs * @return array Array of tabs to show */ function project_prepare_head(Project $project) From 77788a05912340de7f9885dc9399532ad9b5a023 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 00:26:03 +0200 Subject: [PATCH 09/69] Clean code --- htdocs/core/class/html.form.class.php | 1 + htdocs/core/db/DoliDB.class.php | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 3f4938360e0..320992c50c4 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -5315,6 +5315,7 @@ class Form } // Analysis of the pre-selection date + $reg = array(); if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/', $set_time, $reg)) // deprecated usage { // Date format 'YYYY-MM-DD' or 'YYYY-MM-DD HH:MM:SS' diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index 12a39c1384a..c13e3e8f85e 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -87,10 +87,10 @@ abstract class DoliDB implements Database * @param int $param Date TMS to convert * @return string Date in a string YYYY-MM-DD HH:MM:SS */ - public function idate($param) + public function idate($param, $tzoutput = 'tzserver') { // TODO GMT $param should be gmt, so we should add tzouptut to 'gmt' - return dol_print_date($param, "%Y-%m-%d %H:%M:%S"); + return dol_print_date($param, "%Y-%m-%d %H:%M:%S", 'tzserver'); } /** From e9bcd95c39f0b1f2ffa88ff1dfe72bcdf783763d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 00:49:19 +0200 Subject: [PATCH 10/69] Add information column on page to export source of accounting document --- htdocs/compta/accounting-files.php | 42 +++++++++++++++---- .../fourn/class/fournisseur.facture.class.php | 4 +- 2 files changed, 36 insertions(+), 10 deletions(-) diff --git a/htdocs/compta/accounting-files.php b/htdocs/compta/accounting-files.php index 61c0b855c75..b39d2da5001 100644 --- a/htdocs/compta/accounting-files.php +++ b/htdocs/compta/accounting-files.php @@ -182,7 +182,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; $sql .= " AND t.fk_statut <> ".Don::STATUS_DRAFT; } - // Paiements of salaries + // Payments of salaries if (GETPOST('selectpaymentsofsalaries')) { if (!empty($sql)) $sql .= " UNION ALL"; $sql .= " SELECT t.rowid as id, t.entity, t.label as ref, 1 as paid, amount as total_ht, amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, t.fk_user as fk_soc, t.datep as date, t.dateep as date_due, 'SalaryPayment' as item, CONCAT(CONCAT(u.lastname, ' '), u.firstname) as thirdparty_name, '' as thirdparty_code, c.code as country_code, '' as vatnum, ".PAY_DEBIT." as sens"; @@ -203,7 +203,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { // Various payments if (GETPOST('selectvariouspayment')) { if (!empty($sql)) $sql .= " UNION ALL"; - $sql .= " SELECT t.rowid as id, t.entity, t.label as ref, 1 as paid, t.amount as total_ht, t.amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.datep as date, t.datep as date_due, 'VariousPayment' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum, sens"; + $sql .= " SELECT t.rowid as id, t.entity, t.ref, 1 as paid, t.amount as total_ht, t.amount as total_ttc, 0 as total_vat, '".$db->escape($conf->currency)."' as currency, 0 as fk_soc, t.datep as date, t.datep as date_due, 'VariousPayment' as item, '' as thirdparty_name, '' as thirdparty_code, '' as country_code, '' as vatnum, sens"; $sql .= " FROM ".MAIN_DB_PREFIX."payment_various as t"; $sql .= " WHERE datep between ".$wheretail; $sql .= " AND t.entity IN (".($entity == 1 ? '0,1' : $entity).')'; @@ -606,13 +606,14 @@ if (!empty($date_start) && !empty($date_stop)) print_liste_field_titre($arrayfields['ref']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder, 'nowraponall '); print ''.$langs->trans("Document").''; print ''.$langs->trans("Paid").''; - print ''.$langs->trans("TotalHT").''; - print ''.$langs->trans("TotalTTC").''; - print ''.$langs->trans("TotalVAT").''; + print ''.$langs->trans("TotalHT").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').''; + print ''.$langs->trans("TotalTTC").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').''; + print ''.$langs->trans("TotalVAT").($conf->multicurrency->enabled ? ' ('.$conf->currency.')' : '').''; print ''.$langs->trans("ThirdParty").''; print ''.$langs->trans("Code").''; print ''.$langs->trans("Country").''; print ''.$langs->trans("VATIntra").''; + if ($conf->multicurrency->enabled) print ''.$langs->trans("Currency").''; print ''; if ($result) { @@ -620,7 +621,11 @@ if (!empty($date_start) && !empty($date_stop)) if (empty($TData)) { - print ''.$langs->trans("NoItem").''; + print ''.$langs->trans("NoItem").''; + if (! empty($conf->multicurrency->enabled)) { + print ''; + } + print ''; } else { // Sort array by date ASC to calculate balance @@ -647,7 +652,7 @@ if (!empty($date_start) && !empty($date_stop)) print dol_print_date($data['date'], 'day'); print "\n"; - // Date + // Date due print ''; print dol_print_date($data['date_due'], 'day'); print "\n"; @@ -658,10 +663,18 @@ if (!empty($date_start) && !empty($date_stop)) if ($data['item'] == 'Invoice') { $invoice->id = $data['id']; $invoice->ref = $data['ref']; + $invoice->total_ht = $data['amount_ht']; + $invoice->total_ttc = $data['amount_ttc']; + $invoice->total_tva = $data['amount_vat']; + $invoice->multicurrency_code = $data['currency']; print $invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0); } elseif ($data['item'] == 'SupplierInvoice') { $supplier_invoice->id = $data['id']; $supplier_invoice->ref = $data['ref']; + $supplier_invoice->total_ht = $data['amount_ht']; + $supplier_invoice->total_ttc = $data['amount_ttc']; + $supplier_invoice->total_tva = $data['amount_vat']; + $supplier_invoice->multicurrency_code = $data['currency']; print $supplier_invoice->getNomUrl(1, '', 0, 0, '', 0, 0, 0); } elseif ($data['item'] == 'ExpenseReport') { $expensereport->id = $data['id']; @@ -712,7 +725,7 @@ if (!empty($date_start) && !empty($date_stop)) // Total VAT print ''.price($data['sens'] ? $data['amount_vat'] : -$data['amount_vat'])."\n"; - print ''.$data['thirdparty_name']."\n"; + print ''.$data['thirdparty_name']."\n"; print ''.$data['thirdparty_code']."\n"; @@ -730,6 +743,10 @@ if (!empty($date_start) && !empty($date_stop)) $totalVAT_debit -= $data['amount_vat']; } + if (! empty($conf->multicurrency->enabled)) { + print ''.$data['currency']."\n"; + } + print "\n"; } @@ -740,6 +757,9 @@ if (!empty($date_start) && !empty($date_stop)) print ''.price(price2num($totalIT_credit, 'MT')).''; print ''.price(price2num($totalVAT_credit, 'MT')).''; print ''; + if (! empty($conf->multicurrency->enabled)) { + print ''; + } print "\n"; // Total debits print ''; @@ -748,6 +768,9 @@ if (!empty($date_start) && !empty($date_stop)) print ''.price(price2num($totalIT_debit, 'MT')).''; print ''.price(price2num($totalVAT_debit, 'MT')).''; print ''; + if (! empty($conf->multicurrency->enabled)) { + print ''; + } print "\n"; // Balance print ''; @@ -756,6 +779,9 @@ if (!empty($date_start) && !empty($date_stop)) print ''.price(price2num($totalIT_credit + $totalIT_debit, 'MT')).''; print ''.price(price2num($totalVAT_credit + $totalVAT_debit, 'MT')).''; print ''; + if (! empty($conf->multicurrency->enabled)) { + print ''; + } print "\n"; } } diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 0c0e32a2055..289eaf2d05b 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -2286,7 +2286,7 @@ class FactureFournisseur extends CommonInvoice if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice - $label = ''.$langs->trans("SupplierInvoice").''; + $label = img_picto('', $this->picto).' '.$langs->trans("SupplierInvoice").''; if ($this->type == self::TYPE_REPLACEMENT) $label = ''.$langs->transnoentitiesnoconv("InvoiceReplace").''; elseif ($this->type == self::TYPE_CREDIT_NOTE) $label = ''.$langs->transnoentitiesnoconv("CreditNote").''; elseif ($this->type == self::TYPE_DEPOSIT) $label = ''.$langs->transnoentitiesnoconv("Deposit").''; @@ -2301,7 +2301,7 @@ class FactureFournisseur extends CommonInvoice if (!empty($this->total_ht)) $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); if (!empty($this->total_tva)) - $label .= '
'.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); + $label .= '
'.$langs->trans('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); if (!empty($this->total_ttc)) $label .= '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); if ($moretitle) $label .= ' - '.$moretitle; From 31f4d99e1993ce9bb132b0fdadf69d4602b4671f Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 00:53:01 +0200 Subject: [PATCH 11/69] css --- htdocs/compta/accounting-files.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/compta/accounting-files.php b/htdocs/compta/accounting-files.php index b39d2da5001..020b85bf06c 100644 --- a/htdocs/compta/accounting-files.php +++ b/htdocs/compta/accounting-files.php @@ -581,7 +581,7 @@ if (!empty($date_start) && !empty($date_stop)) foreach ($listofchoices as $choice => $val) { $param .= '&'.$choice.'='.(GETPOST($choice, 'int') ? 1 : 0); } - print '
'."\n"; + print ''."\n"; print ''; echo dol_print_date($date_start, 'day')." - ".dol_print_date($date_stop, 'day'); @@ -592,7 +592,7 @@ if (!empty($date_start) && !empty($date_stop)) print ''; } - print ''; + print ''; print '
'."\n"; print '
'; From ea8ec4ea90fc48b1293487e7b4240b6040ad8adf Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 00:59:05 +0200 Subject: [PATCH 12/69] Clean code --- ChangeLog | 1 + htdocs/core/class/html.form.class.php | 21 +-------------------- 2 files changed, 2 insertions(+), 20 deletions(-) diff --git a/ChangeLog b/ChangeLog index ca5834f63f2..53282d1c1d3 100644 --- a/ChangeLog +++ b/ChangeLog @@ -24,6 +24,7 @@ Following changes may create regressions for some external modules, but were nec * The GETPOST(..., 'alpha') has now the same behaviour than GETPOST(..., 'alphanohtml') so no html will be allowed. Use GETPOST(..., 'restricthtml') to accept HTML. * If you have links in your code with '&action=delete' as a parameter, you must also add '&token='.newToken() as another parameter to avoid CSRF protection errors. * The API addPayment for api_invoice has evolved to accept amount into a foreign currency. You must provide array(amount=>X,mutlicurrency_ammount=>Y) instead of amount. +* The method select_thirdparty(), deprecated since 3.8, into html.form.class.php has been removed. ***** ChangeLog for 12.0.3 compared to 12.0.2 ***** FIX: 10.0 - when the mime file name is different from the filesystem name, the attachment name should be the mime filename diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 320992c50c4..f01bac8e7fb 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -1083,25 +1083,6 @@ class Form } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML code to select a company. - * - * @param int $selected Preselected products - * @param string $htmlname Name of HTML select field (must be unique in page) - * @param int $filter Filter on thirdparty - * @param int $limit Limit on number of returned lines - * @param array $ajaxoptions Options for ajax_autocompleter - * @param int $forcecombo Force to load all values and output a standard combobox (with no beautification) - * @return string Return select box for thirdparty. - * @deprecated 3.8 Use select_company instead. For exemple $form->select_thirdparty(GETPOST('socid'),'socid','',0) => $form->select_company(GETPOST('socid'),'socid','',1,0,0,array(),0) - */ - public function select_thirdparty($selected = '', $htmlname = 'socid', $filter = '', $limit = 20, $ajaxoptions = array(), $forcecombo = 0) - { - // phpcs:enable - return $this->select_thirdparty_list($selected, $htmlname, $filter, 1, 0, $forcecombo, array(), '', 0, $limit); - } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Output html form to select a third party @@ -5808,7 +5789,7 @@ class Form * @param int $disabled 1=Html component is disabled * @param string $selected_input_value Value of preselected input text (for use with ajax) * @return string Return HTML string - * @see selectForFormsList() select_thirdparty() + * @see selectForFormsList() select_thirdparty_list() */ public function selectForForms($objectdesc, $htmlname, $preselectedvalue, $showempty = '', $searchkey = '', $placeholder = '', $morecss = '', $moreparams = '', $forcecombo = 0, $disabled = 0, $selected_input_value = '') { From 294688891d378bfc813376f7fdb06efa45f577c0 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 01:10:26 +0200 Subject: [PATCH 13/69] CSS --- htdocs/accountancy/journal/bankjournal.php | 3 ++- htdocs/langs/en_US/accountancy.lang | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/htdocs/accountancy/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php index 7062c25b108..530dd6c5942 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -970,8 +970,9 @@ if (empty($action) || $action == 'view') { $obj = $db->fetch_object($resql); if ($obj->nb > 0) { - print '
'.img_warning().' '.$langs->trans("TheJournalCodeIsNotDefinedOnSomeBankAccount"); + print '
'.img_warning().' '.$langs->trans("TheJournalCodeIsNotDefinedOnSomeBankAccount"); print ' : '.$langs->trans("AccountancyAreaDescBank", 9, ''.$langs->transnoentitiesnoconv("MenuAccountancy").'-'.$langs->transnoentitiesnoconv("Setup")."-".$langs->transnoentitiesnoconv("BankAccounts").''); + print '
'; } } else dol_print_error($db); diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index edf5056d616..223b4552f3e 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -82,7 +82,7 @@ AccountancyAreaDescAnalyze=STEP %s: Add or edit existing transactions and genera AccountancyAreaDescClosePeriod=STEP %s: Close period so we can't make modification in a future. -TheJournalCodeIsNotDefinedOnSomeBankAccount=A mandatory step in setup was not complete (accounting code journal not defined for all bank accounts) +TheJournalCodeIsNotDefinedOnSomeBankAccount=A mandatory step in setup has not been completed (accounting code journal not defined for all bank accounts) Selectchartofaccounts=Select active chart of accounts ChangeAndLoad=Change and load Addanaccount=Add an accounting account From 8febb19b507ed234b0a35375a32ac8c0002db515 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 01:12:27 +0200 Subject: [PATCH 14/69] Translation --- htdocs/langs/en_US/accountancy.lang | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/langs/en_US/accountancy.lang b/htdocs/langs/en_US/accountancy.lang index 223b4552f3e..0b6c90f23e5 100644 --- a/htdocs/langs/en_US/accountancy.lang +++ b/htdocs/langs/en_US/accountancy.lang @@ -115,7 +115,7 @@ ExpenseReportsVentilation=Expense report binding CreateMvts=Create new transaction UpdateMvts=Modification of a transaction ValidTransaction=Validate transaction -WriteBookKeeping=Register transactions in Ledger +WriteBookKeeping=Register transactions in accounting Bookkeeping=Ledger AccountBalance=Account balance ObjectsRef=Source object ref From 973502bb1e6ac99ee162dc73851824b683cfb71e Mon Sep 17 00:00:00 2001 From: Alexandre SPANGARO Date: Wed, 7 Oct 2020 09:36:29 +0200 Subject: [PATCH 15/69] Fix --- htdocs/compta/bank/class/paymentvarious.class.php | 4 ++-- htdocs/compta/bank/various_payment/card.php | 5 +++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/htdocs/compta/bank/class/paymentvarious.class.php b/htdocs/compta/bank/class/paymentvarious.class.php index 064f8ac8d41..157a7096eb8 100644 --- a/htdocs/compta/bank/class/paymentvarious.class.php +++ b/htdocs/compta/bank/class/paymentvarious.class.php @@ -347,8 +347,8 @@ class PaymentVarious extends CommonObject { $newamount = price2num($this->amount, 'MT'); - // Validation parametres - if (!$newamount > 0 || empty($this->datep)) + // Validation of parameters + if (!($newamount) > 0 || empty($this->datep)) { return false; } diff --git a/htdocs/compta/bank/various_payment/card.php b/htdocs/compta/bank/various_payment/card.php index 62d022c0157..56843c9032f 100644 --- a/htdocs/compta/bank/various_payment/card.php +++ b/htdocs/compta/bank/various_payment/card.php @@ -272,6 +272,11 @@ if ($action == 'confirm_clone' && $confirm == 'yes' && ($user->rights->banque->m setEventMessages($object->error, $object->errors, 'errors'); } + } else { + $id = $originalId; + $db->rollback(); + + setEventMessages($object->error, $object->errors, 'errors'); } } else { $db->rollback(); From 29ee420f3e2565e5cb815f0452d0122658a2312a Mon Sep 17 00:00:00 2001 From: "Sekan, Tobias" Date: Wed, 7 Oct 2020 11:18:31 +0200 Subject: [PATCH 16/69] Selectable columns on sup. invoice payment list --- htdocs/core/menus/standard/eldy.lib.php | 2 +- htdocs/fourn/paiement/card.php | 4 +- htdocs/fourn/paiement/list.php | 429 ++++++++++++++++++++++++ 3 files changed, 432 insertions(+), 3 deletions(-) create mode 100644 htdocs/fourn/paiement/list.php diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php index 2c3549cdea9..047cfe2d6b3 100644 --- a/htdocs/core/menus/standard/eldy.lib.php +++ b/htdocs/core/menus/standard/eldy.lib.php @@ -1043,7 +1043,7 @@ function print_left_eldy_menu($db, $menu_array_before, $menu_array_after, &$tabM $newmenu->add("/fourn/facture/list.php?leftmenu=suppliers_bills_paid&search_status=2", $langs->trans("BillShortStatusPaid"), 2, $user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_paid'); } - $newmenu->add("/fourn/facture/paiement.php?leftmenu=suppliers_bills_payment", $langs->trans("Payments"), 1, $user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_payment'); + $newmenu->add("/fourn/paiement/list.php?leftmenu=suppliers_bills_payment", $langs->trans("Payments"), 1, $user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_payment'); $newmenu->add("/fourn/facture/rapport.php?leftmenu=suppliers_bills_report", $langs->trans("Reportings"), 2, $user->rights->fournisseur->facture->lire, '', $mainmenu, 'suppliers_bills_report'); diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php index 9a7af329f50..da2d04574ee 100644 --- a/htdocs/fourn/paiement/card.php +++ b/htdocs/fourn/paiement/card.php @@ -74,7 +74,7 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisse if ($result > 0) { $db->commit(); - header('Location: '.DOL_URL_ROOT.'/fourn/facture/paiement.php'); + header('Location: '.DOL_URL_ROOT.'/fourn/paiement/list.php'); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -166,7 +166,7 @@ if ($result > 0) print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_valide'); } - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref'); diff --git a/htdocs/fourn/paiement/list.php b/htdocs/fourn/paiement/list.php new file mode 100644 index 00000000000..874a15bb8ac --- /dev/null +++ b/htdocs/fourn/paiement/list.php @@ -0,0 +1,429 @@ + + * Copyright (C) 2004 Eric Seigne + * Copyright (C) 2004-2020 Laurent Destailleur + * Copyright (C) 2004 Christophe Combelles + * Copyright (C) 2005 Marc Barilley / Ocebo + * Copyright (C) 2005-2012 Regis Houssin + * Copyright (C) 2014 Teddy Andreotti <125155@supinfo.com> + * Copyright (C) 2015 Marcos García + * Copyright (C) 2015 Juanjo Menent + * Copyright (C) 2017 Alexandre Spangaro + * Copyright (C) 2018 Frédéric France + * Copyright (C) 2020 Tobias Sekan + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/** + * \file htdocs/fourn/paiment/list.php +* \ingroup fournisseur,facture + * \brief Payment list for supplier invoices + */ + +require '../../main.inc.php'; + +// Security check +if ($user->socid) $socid = $user->socid; + +// doesn't work :-( +// restrictedArea($user, 'fournisseur'); + +// doesn't work :-( +// require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +// $object = new PaiementFourn($db); +// restrictedArea($user, $object->element); + +if(!$user->rights->fournisseur->facture->lire) { + accessforbidden(); +} + +require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; + + +// Load translation files required by the page +$langs->loadLangs(array('companies', 'bills', 'banks', 'compta')); + +$action = GETPOST('action', 'alpha'); +$massaction = GETPOST('massaction', 'alpha'); +$optioncss = GETPOST('optioncss', 'alpha'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'vendorpaymentlist'; + +$socid = GETPOST('socid', 'int'); + +$search_ref = GETPOST('search_ref', 'alpha'); +$search_day = GETPOST('search_day', 'int'); +$search_month = GETPOST('search_month', 'int'); +$search_year = GETPOST('search_year', 'int'); +$search_company = GETPOST('search_company', 'alpha'); +$search_payment_type = GETPOST('search_payment_type'); +$search_cheque_num = GETPOST('search_cheque_num', 'alpha'); +$search_bank_account = GETPOST('search_bank_account', 'int'); +$search_amount = GETPOST('search_amount', 'alpha'); // alpha because we must be able to search on '< x' + +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'alpha'); +$sortorder = GETPOST('sortorder', 'alpha'); +$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST('page', 'int'); + +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 (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) $sortfield = "p.datep"; + +// TODO: add global search for this list + +$arrayfields = array( + 'p.ref' =>array('label'=>"RefPayment", 'checked'=>1, 'position'=>10), + 'p.datep' =>array('label'=>"Date", 'checked'=>1, 'position'=>20), + 's.nom' =>array('label'=>"ThirdParty", 'checked'=>1, 'position'=>30), + 'c.libelle' =>array('label'=>"Type", 'checked'=>1, 'position'=>40), + 'p.num_paiement' =>array('label'=>"Numero", 'checked'=>1, 'position'=>50, 'tooltip'=>"ChequeOrTransferNumber"), + 'ba.label' =>array('label'=>"Account", 'checked'=>1, 'position'=>60, 'enable'=>(!empty($conf->banque->enabled))), + 'p.amount' =>array('label'=>"Amount", 'checked'=>1, 'position'=>70), +); +$arrayfields = dol_sort_array($arrayfields, 'position'); + +$hookmanager->initHooks(array('paymentsupplierlist')); +$object = new PaiementFourn($db); + +/* +* Actions +*/ + +$parameters = array('socid'=>$socid); +$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)) { + 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 + $search_ref = ''; + $search_day = ''; + $search_month = ''; + $search_year = ''; + $search_company = ''; + $search_payment_type = ''; + $search_cheque_num = ''; + $search_bank_account = ''; + $search_amount = ''; + } +} + +/* + * View + */ + +llxHeader('', $langs->trans('ListPayment')); + +$form = new Form($db); +$formother = new FormOther($db); +$companystatic = new Societe($db); +$paymentfournstatic = new PaiementFourn($db); + +$sql = 'SELECT p.rowid, p.ref, p.datep, p.amount as pamount, p.num_paiement'; +$sql .= ', s.rowid as socid, s.nom as name, s.email'; +$sql .= ', c.code as paiement_type, c.libelle as paiement_libelle'; +$sql .= ', ba.rowid as bid, ba.label'; +if (!$user->rights->societe->client->voir) $sql .= ', sc.fk_soc, sc.fk_user'; +$sql .= ', SUM(pf.amount)'; + +$sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn AS p'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn AS pf ON p.rowid=pf.fk_paiementfourn'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn AS f ON f.rowid=pf.fk_facturefourn'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement AS c ON p.fk_paiement = c.id'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON s.rowid = f.fk_soc'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; +$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; +if (!$user->rights->societe->client->voir) $sql .= ', '.MAIN_DB_PREFIX.'societe_commerciaux as sc'; + +$sql .= ' WHERE f.entity = '.$conf->entity; +if (!$user->rights->societe->client->voir) $sql .= ' AND s.rowid = sc.fk_soc AND sc.fk_user = '.$user->id; +if ($socid > 0) $sql .= ' AND f.fk_soc = '.$socid; +if ($search_ref) $sql .= natural_search('p.ref', $search_ref); +$sql .= dolSqlDateFilter('p.datep', $search_day, $search_month, $search_year); +if ($search_company) $sql .= natural_search('s.nom', $search_company); +if ($search_payment_type != '') $sql .= " AND c.code='".$db->escape($search_payment_type)."'"; +if ($search_cheque_num != '') $sql .= natural_search('p.num_paiement', $search_cheque_num); +if ($search_amount) $sql .= natural_search('p.amount', $search_amount, 1); +if ($search_bank_account > 0) $sql .= ' AND b.fk_account='.$search_bank_account."'"; + +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; + +$sql .= ' GROUP BY p.rowid, p.datep, p.amount, p.num_paiement, s.rowid, s.nom, c.code, c.libelle, ba.rowid, ba.label'; +if (!$user->rights->societe->client->voir) $sql .= ', sc.fk_soc, sc.fk_user'; + +$sql .= $db->order($sortfield, $sortorder); + +$nbtotalofrecords = ''; +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 + $page = 0; + $offset = 0; + } +} + +$sql .= $db->plimit($limit + 1, $offset); + +$resql = $db->query($sql); +if (!$resql) { + dol_print_error($db); + llxFooter(); + $db->close(); + exit; +} + +$num = $db->num_rows($resql); +$i = 0; + +$param = ''; +if (!empty($contextpage) && $contextpage != $_SERVER['PHP_SELF']) $param .= '&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + +if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); +if ($saerch_day) $param .= '&search_day='.urlencode($search_day); +if ($saerch_month) $param .= '&search_month='.urlencode($search_month); +if ($search_year) $param .= '&search_year='.urlencode($search_year); +if ($search_company) $param .= '&search_company='.urlencode($search_company); +if ($search_payment_type) $param .= '&search_company='.urlencode($search_payment_type); +if ($search_cheque_num) $param .= '&search_cheque_num='.urlencode($search_cheque_num); +if ($search_amount) $param .= '&search_amount='.urlencode($search_amount); + +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; + +print '
'; +if ($optioncss != '') print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + +print_barre_liste($langs->trans('SupplierPayments'), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'supplier_invoice', 0, '', '', $limit, 0, 0, 1); + +$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; + +if ($moreforfilter) { + print '
'; + print $moreforfilter; + 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); + +print '
'; +print ''; + +print ''; + +// Filter: Ref +if (!empty($arrayfields['p.ref']['checked'])) { + print ''; +} + +// Filter: Date +if (!empty($arrayfields['p.datep']['checked'])) { + print ''; +} + +// Filter: Thirdparty +if (!empty($arrayfields['s.nom']['checked'])) { + print ''; +} + +// Filter: Payment type +if (!empty($arrayfields['c.libelle']['checked'])) { + print ''; +} + +// Filter: Cheque number (fund transfer) +if (!empty($arrayfields['p.num_paiement']['checked'])) { + print ''; +} + +// Filter: Bank account +if (!empty($arrayfields['ba.label']['checked'])) { + print ''; +} + +// Filter: Amount +if (!empty($arrayfields['p.amount']['checked'])) { + print ''; +} + +// Fields from hook +$parameters = array('arrayfields'=>$arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +// Buttons +print ''; + +print ''; + +print ''; +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER["PHP_SELF"], 'p.rowid', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.datep']['checked'])) print_liste_field_titre($arrayfields['p.datep']['label'], $_SERVER["PHP_SELF"], 'p.datep', '', $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['c.libelle']['checked'])) print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], 'c.libelle', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.num_paiement']['checked'])) print_liste_field_titre($arrayfields['p.num_paiement']['label'], $_SERVER["PHP_SELF"], "p.num_paiement", '', $param, '', $sortfield, $sortorder, '', $arrayfields['p.num_paiement']['tooltip']); +if (!empty($arrayfields['ba.label']['checked'])) print_liste_field_titre($arrayfields['ba.label']['label'], $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.amount']['checked'])) print_liste_field_titre($arrayfields['p.amount']['label'], $_SERVER["PHP_SELF"], 'p.amount', '', $param, '', $sortfield, $sortorder, 'right '); + +// 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 +print $hookmanager->resPrint; + +print_liste_field_titre($selectedfields, $_SERVER['PHP_SELF'], '', '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); +print ''; + +$checkedCount = 0; +foreach($arrayfields as $column) { + if($column['checked']) { + $checkedCount++; + } +} + +$i = 0; +$totalarray = array(); +while ($i < min($num, $limit)) { + $objp = $db->fetch_object($resql); + + $paymentfournstatic->id = $objp->rowid; + $paymentfournstatic->ref = $objp->ref; + $paymentfournstatic->datepaye = $objp->datep; + + $companystatic->id = $objp->socid; + $companystatic->name = $objp->name; + $companystatic->email = $objp->email; + + print ''; + + // No + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Ref + if (!empty($arrayfields['p.ref']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Date + if (!empty($arrayfields['p.datep']['checked'])) { + $dateformatforpayment = 'day'; + if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Thirdparty + if (!empty($arrayfields['s.nom']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Pyament type + if (!empty($arrayfields['c.libelle']['checked'])) { + $payment_type = $langs->trans("PaymentType".$objp->paiement_type) != ("PaymentType".$objp->paiement_type) ? $langs->trans("PaymentType".$objp->paiement_type) : $objp->paiement_libelle; + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Cheque number (fund transfer) + if (!empty($arrayfields['p.num_paiement']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Account + if (!empty($arrayfields['ba.label']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } + + // Amount + if (!empty($arrayfields['p.amount']['checked'])) { + print ''; + if (!$i) $totalarray['nbfield']++; + $totalarray['pos'][$checkedCount] = 'amount'; + $totalarray['val']['amount'] += $objp->pamount; + } + + // Buttons + print ''; + if (!$i) $totalarray['nbfield']++; + + print ''; + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +print '
'; + print ''; + print ''; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + print ''; + $formother->select_year($search_year ? $search_year : -1, 'search_year', 1, 20, 5); + print ''; + print ''; + print ''; + $form->select_types_paiements($search_payment_type, 'search_payment_type', '', 2, 1, 1); + print ''; + print ''; + print ''; + $form->select_comptes($search_bank_account, 'search_bank_account', 0, '', 1); + print ''; + print ''; + print ''; +print $form->showFilterAndCheckAddButtons(0); +print '
'.(($offset * $limit) + $i).''.$paymentfournstatic->getNomUrl(1).''.dol_print_date($db->jdate($objp->datep), $dateformatforpayment).''; + if ($objp->socid > 0) { + print $companystatic->getNomUrl(1, '', 24); + } + print ''.$payment_type.' '.dol_trunc($objp->num_paiement, 32).''.$objp->num_paiement.''; + if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).''; + else print ' '; + print ''.price($objp->pamount).'
'; +print '
'; +print '
'; + +// End of page +llxFooter(); +$db->close(); From e26ab93179d914c0d6de8c6599cad96f546a2c75 Mon Sep 17 00:00:00 2001 From: "Sekan, Tobias" Date: Wed, 7 Oct 2020 11:22:23 +0200 Subject: [PATCH 17/69] missing code remove from last commit --- htdocs/fourn/facture/paiement.php | 249 ------------------------------ 1 file changed, 249 deletions(-) diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index 65b8936a592..8c2fdbdb5b6 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -787,255 +787,6 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } else dol_print_error($db); } -/* - * Show list - */ -if (empty($action) || $action == 'list') -{ - $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; - $sortfield = GETPOST("sortfield", 'alpha'); - $sortorder = GETPOST("sortorder", 'alpha'); - $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); - if (empty($page) || $page == -1) { $page = 0; } - $offset = $limit * $page; - $pageprev = $page - 1; - $pagenext = $page + 1; - if (!$sortorder) $sortorder = 'DESC'; - if (!$sortfield) $sortfield = 'p.datep'; - - $sql = 'SELECT p.rowid as pid, p.ref, p.datep as dp, p.amount as pamount, p.num_paiement,'; - $sql .= ' s.rowid as socid, s.nom as name,'; - $sql .= ' c.code as paiement_type, c.libelle as paiement_libelle,'; - $sql .= ' ba.rowid as bid, ba.label,'; - if (!$user->rights->societe->client->voir) $sql .= ' sc.fk_soc, sc.fk_user,'; - $sql .= ' SUM(pf.amount)'; - $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn AS p'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn AS pf ON p.rowid=pf.fk_paiementfourn'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn AS f ON f.rowid=pf.fk_facturefourn'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement AS c ON p.fk_paiement = c.id'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe AS s ON s.rowid = f.fk_soc'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank_account as ba ON b.fk_account = ba.rowid'; - if (!$user->rights->societe->client->voir) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= " WHERE f.entity = ".$conf->entity; - if (!$user->rights->societe->client->voir) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid > 0) $sql .= ' AND f.fk_soc = '.$socid; - $sql .= dolSqlDateFilter('p.datep', $day, $month, $year); - if ($search_ref) $sql .= natural_search('p.rowid', $search_ref); - if ($search_account > 0) $sql .= " AND b.fk_account=".$search_account; - if ($search_paymenttype != "") $sql .= " AND c.code='".$db->escape($search_paymenttype)."'"; - if ($search_payment_num != '') $sql .= natural_search('p.num_paiement', $search_payment_num); - if ($search_amount) $sql .= natural_search('p.amount', $search_amount, 1); - if ($search_company) $sql .= natural_search('s.nom', $search_company); - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; - $sql .= " GROUP BY p.rowid, p.datep, p.amount, p.num_paiement, s.rowid, s.nom, c.code, c.libelle, ba.rowid, ba.label"; - if (!$user->rights->societe->client->voir) $sql .= ", sc.fk_soc, sc.fk_user"; - // Add where from extra fields - - $sql .= $db->order($sortfield, $sortorder); - - $nbtotalofrecords = ''; - if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) - { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { - $page = 0; - $offset = 0; - } - } - - $sql .= $db->plimit($limit + 1, $offset); - - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - - $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($day) $param .= ($day ? "&day=".urlencode($day) : ""); - if ($month) $param .= ($month ? "&month=".urlencode($month) : ""); - if ($year) $param .= ($year ? "&year=".urlencode($year) : ""); - if ($search_ref) $param .= ($search_ref ? "&search_ref=".urlencode($search_ref) : ""); - if ($search_company) $param .= ($search_company ? "&search_company=".urlencode($search_company) : ""); - if ($search_amount != '') $param .= ($search_amount ? "&search_amount=".urlencode($search_amount) : ""); - if ($search_payment_num) $param .= ($search_payment_num ? "&search_payment_num=".urlencode($search_payment_num) : ""); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - // Add $param from extra fields - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; - - $massactionbutton = $form->selectMassAction('', $massaction == 'presend' ? array() : array('presend'=>$langs->trans("SendByMail"), 'builddoc'=>$langs->trans("PDFMerge"))); - - print '
'; - if ($optioncss != '') print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - - print_barre_liste($langs->trans('SupplierPayments'), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'supplier_invoice', 0, '', '', $limit, 0, 0, 1); - - $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; - - if ($moreforfilter) - { - print '
'; - print $moreforfilter; - print '
'; - } - - $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - - print '
'; - print ''."\n"; - - // Lines for filters fields - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if (!empty($conf->banque->enabled)) - { - print ''; - } - print ''; - print ''; - print "\n"; - - print ''; - print_liste_field_titre("RefPayment", $_SERVER["PHP_SELF"], 'p.rowid', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Date", $_SERVER["PHP_SELF"], 'dp', '', $param, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre("ThirdParty", $_SERVER["PHP_SELF"], 's.nom', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Type", $_SERVER["PHP_SELF"], 'c.libelle', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Numero", $_SERVER["PHP_SELF"], "p.num_paiement", "", $param, "", $sortfield, $sortorder); - if (!empty($conf->banque->enabled)) - { - print_liste_field_titre("Account", $_SERVER["PHP_SELF"], 'ba.label', '', $param, '', $sortfield, $sortorder); - } - print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], 'p.amount', '', $param, '', $sortfield, $sortorder, 'right '); - - $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('', $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch '); - print "\n"; - - $paymentfournstatic = new PaiementFourn($db); - - $i = 0; - $totalarray = array(); - while ($i < min($num, $limit)) - { - $objp = $db->fetch_object($resql); - - $paymentfournstatic->id = $objp->pid; - $paymentfournstatic->ref = $objp->ref; - $paymentfournstatic->datepaye = $objp->dp; - - print ''; - - // Ref payment - print ''; - if (!$i) $totalarray['nbfield']++; - - // Date - $dateformatforpayment = 'day'; - if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; - print '\n"; - if (!$i) $totalarray['nbfield']++; - - // Thirdparty - print ''; - if (!$i) $totalarray['nbfield']++; - - // Type - $payment_type = $langs->trans("PaymentType".$objp->paiement_type) != ("PaymentType".$objp->paiement_type) ? $langs->trans("PaymentType".$objp->paiement_type) : $objp->paiement_libelle; - print '\n"; - if (!$i) $totalarray['nbfield']++; - - // Payment number - print ''; - if (!$i) $totalarray['nbfield']++; - - // Account - if (!empty($conf->banque->enabled)) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } - - // Amount - print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'amount'; - $totalarray['val']['amount'] += $objp->pamount; - - // Ref invoice - /*$invoicesupplierstatic->ref=$objp->ref_supplier; - $invoicesupplierstatic->id=$objp->facid; - print '';*/ - - print ''; - if (!$i) $totalarray['nbfield']++; - - print ''; - $i++; - } - - // Show total line - include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; - - print "
'; - print ''; - print ''; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; - print ''; - $formother->select_year($year ? $year : -1, 'year', 1, 20, 5); - print ''; - print ''; - print ''; - $form->select_types_paiements($search_paymenttype, 'search_paymenttype', '', 2, 1, 1); - print ''; - print ''; - print ''; - $form->select_comptes($search_account, 'search_account', 0, '', 1); - print ''; - print ''; - print ''; - $searchpicto = $form->showFilterAndCheckAddButtons(0); - print $searchpicto; - print '
'; - print $paymentfournstatic->getNomUrl(1); - print ''.dol_print_date($db->jdate($objp->dp), $dateformatforpayment)."'; - if ($objp->socid) print ''.img_object($langs->trans('ShowCompany'), 'company').' '.dol_trunc($objp->name, 32).''; - else print ' '; - print ''.$payment_type.' '.dol_trunc($objp->num_paiement, 32)."'.$objp->num_paiement.''; - if ($objp->bid) print ''.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).''; - else print ' '; - print ''.price($objp->pamount).''; - print $invoicesupplierstatic->getNomUrl(1); - print '
"; - print "
"; - print "
\n"; - } else { - dol_print_error($db); - } -} - // End of page llxFooter(); $db->close(); From 85b7458b021fe4831ad46f3999f86d3dae8e8860 Mon Sep 17 00:00:00 2001 From: stickler-ci Date: Wed, 7 Oct 2020 09:24:37 +0000 Subject: [PATCH 18/69] Fixing style errors. --- htdocs/fourn/paiement/list.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/htdocs/fourn/paiement/list.php b/htdocs/fourn/paiement/list.php index 874a15bb8ac..1a89e7f6906 100644 --- a/htdocs/fourn/paiement/list.php +++ b/htdocs/fourn/paiement/list.php @@ -45,7 +45,7 @@ if ($user->socid) $socid = $user->socid; // $object = new PaiementFourn($db); // restrictedArea($user, $object->element); -if(!$user->rights->fournisseur->facture->lire) { +if (!$user->rights->fournisseur->facture->lire) { accessforbidden(); } @@ -327,8 +327,8 @@ print_liste_field_titre($selectedfields, $_SERVER['PHP_SELF'], '', '', '', 'alig print ''; $checkedCount = 0; -foreach($arrayfields as $column) { - if($column['checked']) { +foreach ($arrayfields as $column) { + if ($column['checked']) { $checkedCount++; } } From d1c2772ee7f8af0ef4b9e3daca8dad52b7ebceb7 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 12:31:15 +0200 Subject: [PATCH 19/69] NEW Add function dolButtonToOpenUrlInDialogPopup() to be able to open any url into a dialog popup. --- htdocs/core/lib/functions.lib.php | 33 +++++++++++++++++++++++++++++++ htdocs/website/index.php | 19 +----------------- 2 files changed, 34 insertions(+), 18 deletions(-) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 7538c69465b..53d1b5fe40b 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -1209,6 +1209,38 @@ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = } } +/** + * Return HTML code to output a button to open a dialog popup box. + * Such buttons must be included inside a HTML form. + * + * @param string $name A name for the html component + * @param string $label Label of button + * @param string $buttonstring button string + * @param string $url Url to open + * @param string $disabled Disabled text + * @return string HTML component with button + */ +function dolButtonToOpenUrlInDialogPopup($name, $label, $buttonstring, $url, $disabled = '') +{ + //print ''; + $out = ''.$buttonstring.''; + $out .= ''; + return $out; +} /** * Show tab header of a card @@ -1224,6 +1256,7 @@ function dol_syslog($message, $level = LOG_INFO, $ident = 0, $suffixinfilename = * @param int $limittoshow Limit number of tabs to show. Use 0 to use automatic default value. * @param string $moretabssuffix A suffix to use when you have several dol_get_fiche_head() in same page * @return void + * @deprecated Use print dol_get_fiche_head() instead */ function dol_fiche_head($links = array(), $active = '0', $title = '', $notab = 0, $picto = '', $pictoisfullpath = 0, $morehtmlright = '', $morecss = '', $limittoshow = 0, $moretabssuffix = '') { diff --git a/htdocs/website/index.php b/htdocs/website/index.php index fed5be51e87..f62e98575a2 100644 --- a/htdocs/website/index.php +++ b/htdocs/website/index.php @@ -2410,24 +2410,7 @@ if (!GETPOST('hide_websitemenu')) if (! empty($conf->categorie->enabled)) { //print ''; - - //print ''; - print ''; - print ''; + print dolButtonToOpenUrlInDialogPopup('categories', $langs->transnoentitiesnoconv("Categories"), '', '/categories/index.php?leftmenu=website&nosearch=1&type=website_page&website='.$website->ref, $disabled); } print ''; From 145b1e97cae58a0fb84641fafbc06db061a46efa Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 12:41:25 +0200 Subject: [PATCH 20/69] Fix sql --- htdocs/core/modules/mailings/fraise.modules.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/htdocs/core/modules/mailings/fraise.modules.php b/htdocs/core/modules/mailings/fraise.modules.php index efec11c0ba7..5bf96f5afc1 100644 --- a/htdocs/core/modules/mailings/fraise.modules.php +++ b/htdocs/core/modules/mailings/fraise.modules.php @@ -246,10 +246,10 @@ class mailing_fraise extends MailingTargets $sql .= " a.lastname, a.firstname,"; $sql .= " a.datefin, a.civility as civility_id, a.login, a.societe"; // Other fields $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a"; - if ($_POST['filter_category']) + if (GETPOST('filter_category')) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_member as cm ON cm.fk_member = a.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON c.rowid = cm.fk_categorie"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON c.rowid = cm.fk_categorie ON c.rowid='".$this->db->escape(GETPOST('filter_category'))."'"; } $sql .= " , ".MAIN_DB_PREFIX."adherent_type as ta"; $sql .= " WHERE a.entity IN (".getEntity('member').") AND a.email <> ''"; // Note that null != '' is false @@ -267,8 +267,6 @@ class mailing_fraise extends MailingTargets $sql .= " AND a.fk_adherent_type = ta.rowid"; // Filter on type if (GETPOSTISSET('filter_type')) $sql .= " AND ta.rowid='".$this->db->escape(GETPOST('filter_type'))."'"; - // Filter on category - if (GETPOSTISSET('filter_category')) $sql .= " AND c.rowid='".$this->db->escape(GETPOST('filter_category'))."'"; $sql .= " ORDER BY a.email"; //print $sql; From 59e89fd53aedbfc7e5683956f50cd5f53f9a96f8 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 12:42:41 +0200 Subject: [PATCH 21/69] Fix --- htdocs/core/modules/mailings/fraise.modules.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/core/modules/mailings/fraise.modules.php b/htdocs/core/modules/mailings/fraise.modules.php index 5bf96f5afc1..deb39c495eb 100644 --- a/htdocs/core/modules/mailings/fraise.modules.php +++ b/htdocs/core/modules/mailings/fraise.modules.php @@ -248,8 +248,8 @@ class mailing_fraise extends MailingTargets $sql .= " FROM ".MAIN_DB_PREFIX."adherent as a"; if (GETPOST('filter_category')) { - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_member as cm ON cm.fk_member = a.rowid"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie as c ON c.rowid = cm.fk_categorie ON c.rowid='".$this->db->escape(GETPOST('filter_category'))."'"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."categorie_member as cm ON cm.fk_member = a.rowid"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."categorie as c ON c.rowid = cm.fk_categorie ON c.rowid='".$this->db->escape(GETPOST('filter_category'))."'"; } $sql .= " , ".MAIN_DB_PREFIX."adherent_type as ta"; $sql .= " WHERE a.entity IN (".getEntity('member').") AND a.email <> ''"; // Note that null != '' is false From e369610538a7972477f2fa2deac4c99d5bf22c6d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 12:48:05 +0200 Subject: [PATCH 22/69] Fix --- htdocs/core/modules/mailings/fraise.modules.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/modules/mailings/fraise.modules.php b/htdocs/core/modules/mailings/fraise.modules.php index deb39c495eb..201792e2e11 100644 --- a/htdocs/core/modules/mailings/fraise.modules.php +++ b/htdocs/core/modules/mailings/fraise.modules.php @@ -266,7 +266,7 @@ class mailing_fraise extends MailingTargets if ($dateendsubscriptionbefore > 0) $sql .= " AND datefin < '".$this->db->idate($dateendsubscriptionbefore)."'"; $sql .= " AND a.fk_adherent_type = ta.rowid"; // Filter on type - if (GETPOSTISSET('filter_type')) $sql .= " AND ta.rowid='".$this->db->escape(GETPOST('filter_type'))."'"; + if (GETPOSTISSET('filter_type') && GETPOST('filter_type') > 0) $sql .= " AND ta.rowid='".$this->db->escape(GETPOST('filter_type'))."'"; $sql .= " ORDER BY a.email"; //print $sql; From 33fe5eb85f099bc216ec93d596132af4b1510204 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 12:53:17 +0200 Subject: [PATCH 23/69] Fix sql request --- htdocs/core/modules/mailings/fraise.modules.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/modules/mailings/fraise.modules.php b/htdocs/core/modules/mailings/fraise.modules.php index 201792e2e11..ddc3e32f802 100644 --- a/htdocs/core/modules/mailings/fraise.modules.php +++ b/htdocs/core/modules/mailings/fraise.modules.php @@ -249,7 +249,7 @@ class mailing_fraise extends MailingTargets if (GETPOST('filter_category')) { $sql .= " INNER JOIN ".MAIN_DB_PREFIX."categorie_member as cm ON cm.fk_member = a.rowid"; - $sql .= " INNER JOIN ".MAIN_DB_PREFIX."categorie as c ON c.rowid = cm.fk_categorie ON c.rowid='".$this->db->escape(GETPOST('filter_category'))."'"; + $sql .= " INNER JOIN ".MAIN_DB_PREFIX."categorie as c ON c.rowid = cm.fk_categorie AND c.rowid = ".((int) GETPOST('filter_category', 'int')); } $sql .= " , ".MAIN_DB_PREFIX."adherent_type as ta"; $sql .= " WHERE a.entity IN (".getEntity('member').") AND a.email <> ''"; // Note that null != '' is false From 3f39766064a8758578fa9e4aa3d533b33cf7e0a8 Mon Sep 17 00:00:00 2001 From: "Sekan, Tobias" Date: Wed, 7 Oct 2020 13:10:04 +0200 Subject: [PATCH 24/69] Allow zero quality on supplier order line --- htdocs/fourn/class/fournisseur.commande.class.php | 3 +-- htdocs/fourn/commande/card.php | 6 +++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index 3d6d2c2f837..f354b89186d 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -1554,7 +1554,7 @@ class CommandeFournisseur extends CommonOrder include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (!$qty) $qty = 1; + if (empty($qty)) $qty = 0; if (!$info_bits) $info_bits = 0; if (empty($txtva)) $txtva = 0; if (empty($txlocaltax1)) $txlocaltax1 = 0; @@ -2526,7 +2526,6 @@ class CommandeFournisseur extends CommonOrder $remise_percent = price2num($remise_percent); $qty = price2num($qty); - if (!$qty) $qty = 1; $pu = price2num($pu); $pu_ht_devise = price2num($pu_ht_devise); $txtva = price2num($txtva); diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 4a26d3b4cb6..322f4c78aa3 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -406,7 +406,7 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); $error++; } - if (!GETPOST('qty')) + if (GETPOST('qty', 'int') == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; @@ -666,7 +666,7 @@ if (empty($reshook)) $productsupplier = new ProductFournisseur($db); if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) { - if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num($_POST['qty']), $line->fk_product, 'none', GETPOST('socid', 'int')) < 0) + if ($line->fk_product > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty', 'int')), $line->fk_product, 'none', GETPOST('socid', 'int')) < 0) { setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); } @@ -719,7 +719,7 @@ if (empty($reshook)) $lineid, $_POST['product_desc'], $ht, - $_POST['qty'], + GETPOST('qty', 'int'), $_POST['remise_percent'], $vat_rate, $localtax1_rate, From 3ace9f638acf583b3d19eb79e94291506c5a0089 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 13:20:38 +0200 Subject: [PATCH 25/69] Clean code --- htdocs/core/modules/mailings/fraise.modules.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/htdocs/core/modules/mailings/fraise.modules.php b/htdocs/core/modules/mailings/fraise.modules.php index ddc3e32f802..95f180b80ff 100644 --- a/htdocs/core/modules/mailings/fraise.modules.php +++ b/htdocs/core/modules/mailings/fraise.modules.php @@ -238,8 +238,8 @@ class mailing_fraise extends MailingTargets $cibles = array(); $now = dol_now(); - $dateendsubscriptionafter = dol_mktime($_POST['subscriptionafterhour'], $_POST['subscriptionaftermin'], $_POST['subscriptionaftersec'], $_POST['subscriptionaftermonth'], $_POST['subscriptionafterday'], $_POST['subscriptionafteryear']); - $dateendsubscriptionbefore = dol_mktime($_POST['subscriptionbeforehour'], $_POST['subscriptionbeforemin'], $_POST['subscriptionbeforesec'], $_POST['subscriptionbeforemonth'], $_POST['subscriptionbeforeday'], $_POST['subscriptionbeforeyear']); + $dateendsubscriptionafter = dol_mktime(GETPOST('subscriptionafterhour', 'int'), GETPOST('subscriptionaftermin', 'int'), GETPOST('subscriptionaftersec', 'int'), GETPOST('subscriptionaftermonth', 'int'), GETPOST('subscriptionafterday', 'int'), GETPOST('subscriptionafteryear', 'int')); + $dateendsubscriptionbefore = dol_mktime(GETPOST('subscriptionbeforehour', 'int'), GETPOST('subscriptionbeforemin', 'int'), GETPOST('subscriptionbeforesec', 'int'), GETPOST('subscriptionbeforemonth', 'int'), GETPOST('subscriptionbeforeday', 'int'), GETPOST('subscriptionbeforeyear', 'int')); // La requete doit retourner: id, email, fk_contact, name, firstname $sql = "SELECT a.rowid as id, a.email as email, null as fk_contact, "; @@ -255,18 +255,18 @@ class mailing_fraise extends MailingTargets $sql .= " WHERE a.entity IN (".getEntity('member').") AND a.email <> ''"; // Note that null != '' is false $sql .= " AND a.email NOT IN (SELECT email FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE fk_mailing=".$this->db->escape($mailing_id).")"; // Filter on status - if (isset($_POST["filter"]) && $_POST["filter"] == '-1') { + if (GETPOST("filter") == '-1') { $sql .= " AND a.statut=-1"; } - if (isset($_POST["filter"]) && $_POST["filter"] == '1a') $sql .= " AND a.statut=1 AND (a.datefin >= '".$this->db->idate($now)."' OR ta.subscription = 0)"; - if (isset($_POST["filter"]) && $_POST["filter"] == '1b') $sql .= " AND a.statut=1 AND ((a.datefin IS NULL or a.datefin < '".$this->db->idate($now)."') AND ta.subscription = 1)"; - if (isset($_POST["filter"]) && $_POST["filter"] == '0') $sql .= " AND a.statut=0"; + if (GETPOST("filter", 'aZ09') == '1a') $sql .= " AND a.statut=1 AND (a.datefin >= '".$this->db->idate($now)."' OR ta.subscription = 0)"; + if (GETPOST("filter", 'aZ09') == '1b') $sql .= " AND a.statut=1 AND ((a.datefin IS NULL or a.datefin < '".$this->db->idate($now)."') AND ta.subscription = 1)"; + if (GETPOST("filter", 'aZ09') === '0') $sql .= " AND a.statut=0"; // Filter on date if ($dateendsubscriptionafter > 0) $sql .= " AND datefin > '".$this->db->idate($dateendsubscriptionafter)."'"; if ($dateendsubscriptionbefore > 0) $sql .= " AND datefin < '".$this->db->idate($dateendsubscriptionbefore)."'"; $sql .= " AND a.fk_adherent_type = ta.rowid"; // Filter on type - if (GETPOSTISSET('filter_type') && GETPOST('filter_type') > 0) $sql .= " AND ta.rowid='".$this->db->escape(GETPOST('filter_type'))."'"; + if (GETPOST('filter_type', 'int') > 0) $sql .= " AND ta.rowid='".$this->db->escape(GETPOST('filter_type', 'int'))."'"; $sql .= " ORDER BY a.email"; //print $sql; From 5da923c80d567c095ab8b38263cebbe9bd35cb43 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 13:42:46 +0200 Subject: [PATCH 26/69] phpcs --- htdocs/core/db/DoliDB.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/db/DoliDB.class.php b/htdocs/core/db/DoliDB.class.php index c13e3e8f85e..8af9f7bbc25 100644 --- a/htdocs/core/db/DoliDB.class.php +++ b/htdocs/core/db/DoliDB.class.php @@ -87,7 +87,7 @@ abstract class DoliDB implements Database * @param int $param Date TMS to convert * @return string Date in a string YYYY-MM-DD HH:MM:SS */ - public function idate($param, $tzoutput = 'tzserver') + public function idate($param) { // TODO GMT $param should be gmt, so we should add tzouptut to 'gmt' return dol_print_date($param, "%Y-%m-%d %H:%M:%S", 'tzserver'); From a119a75fe01b23396b811ccebeb3eb5a48dc9553 Mon Sep 17 00:00:00 2001 From: "Sekan, Tobias" Date: Wed, 7 Oct 2020 14:00:32 +0200 Subject: [PATCH 27/69] add more filter on monthly statement list --- htdocs/holiday/month_report.php | 64 ++++++++++++++++++++++++++++----- 1 file changed, 55 insertions(+), 9 deletions(-) diff --git a/htdocs/holiday/month_report.php b/htdocs/holiday/month_report.php index baf444ce295..c8f07d50cc3 100644 --- a/htdocs/holiday/month_report.php +++ b/htdocs/holiday/month_report.php @@ -48,7 +48,10 @@ $massaction = GETPOST('massaction', 'alpha'); $contextpage = GETPOST('contextpage', 'aZ'); $optioncss = GETPOST('optioncss', 'aZ'); -$search_ref = GETPOST('search_ref', 'alpha'); +$search_ref = GETPOST('search_ref', 'alphanohtml'); +$search_employee = GETPOST('search_employee', 'int'); +$search_type = GETPOST('search_type', 'int'); +$search_description = GETPOST('search_description', 'alphanohtml'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); @@ -82,6 +85,9 @@ if (empty($reshook)) if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { $search_ref = ''; + $search_employee = ''; + $search_type = ''; + $search_description = ''; $toselect = ''; $search_array_options = array(); } @@ -135,7 +141,10 @@ $sql.= " WHERE cp.rowid > 0"; $sql.= " AND cp.statut = 3"; // 3 = Approved $sql.= " AND (date_format(cp.date_debut, '%Y-%m') = '".$db->escape($year_month)."' OR date_format(cp.date_fin, '%Y-%m') = '".$db->escape($year_month)."')"; -if ($search_ref != '') $sql.= natural_search('cp.ref', $search_ref, 0); +if (!empty($search_ref)) $sql .= natural_search('cp.ref', $search_ref); +if (!empty($search_employee)) $sql .= " AND cp.fk_user = '".$db->escape($search_employee)."'"; +if (!empty($search_type)) $sql .= ' AND cp.fk_type IN ('.$db->escape($search_type).')'; +if (!empty($search_description)) $sql.= natural_search('cp.description', $search_description); $sql.= $db->order($sortfield, $sortorder); @@ -149,9 +158,12 @@ if (empty($resql)) $num = $db->num_rows($resql); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param.= '&limit='.urlencode($limit); -if ($search_ref) $param = '&search_ref='.urlencode($search_ref); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.= '&contextpage='.urlencode($contextpage); +if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if (!empty($search_ref)) $param .= '&search_ref='.urlencode($search_ref); +if (!empty($search_employee)) $param .= '&search_employee='.urlencode($search_employee); +if (!empty($search_type)) $param .= '&search_type='.urlencode($search_type); +if (!empty($search_description)) $param .= '&search_description='.urlencode($search_description); print '
'; if ($optioncss != '') print ''; @@ -184,16 +196,50 @@ print '
'; print ''; print ''; -if (!empty($arrayfields['cp.ref']['checked'])) print ''; -if (!empty($arrayfields['cp.fk_user']['checked'])) print ''; -if (!empty($arrayfields['ct.label']['checked'])) print ''; + +// Filter: Ref +if (!empty($arrayfields['cp.ref']['checked'])) { + print ''; +} + +// Filter: Employee +if (!empty($arrayfields['cp.fk_user']['checked'])) { + print ''; +} + +// Filter: Type +if (!empty($arrayfields['ct.label']['checked'])) { + $typeleaves = $holidaystatic->getTypes(1, -1); + $arraytypeleaves = array(); + foreach ($typeleaves as $key => $val) + { + $labeltoshow = ($langs->trans($val['code']) != $val['code'] ? $langs->trans($val['code']) : $val['label']); + $arraytypeleaves[$val['rowid']] = $labeltoshow; + } + + print ''; +} + if (!empty($arrayfields['cp.date_debut']['checked'])) print ''; if (!empty($arrayfields['cp.date_fin']['checked'])) print ''; if (!empty($arrayfields['used_days']['checked'])) print ''; if (!empty($arrayfields['date_start_month']['checked'])) print ''; if (!empty($arrayfields['date_end_month']['checked'])) print ''; if (!empty($arrayfields['used_days_month']['checked'])) print ''; -if (!empty($arrayfields['cp.description']['checked'])) print ''; + +// Filter: Description +if (!empty($arrayfields['cp.description']['checked'])) { + print ''; +} + // Action column print '
'; + print ''; + print ''; + print $form->select_dolusers($search_employee, "search_employee", 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); + print ''; + print $form->selectarray('search_type', $arraytypeleaves, $search_type, 1); + print ''; + print ''; + print ''; $searchpicto = $form->showFilterButtons(); From 4c87949be02919790b5b06ef76991a456f853037 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 14:53:10 +0200 Subject: [PATCH 28/69] Fix scrutinizer --- htdocs/compta/facture/class/api_invoices.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index b913b405734..0ab4974ce7f 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -1499,7 +1499,7 @@ class Invoices extends DolibarrApi $amount = price2num($amountarray["multicurrency_amount"], 'MT'); } - if ($amount > $remainstopay && $accepthigherpayment == false) { + if ($amount > $remainstopay && !$accepthigherpayment) { $this->db->rollback(); throw new RestException(400, 'Payment amount on invoice ID '.$id.' ('.$amount.') is higher than remain to pay ('.$remainstopay.')'); } From 96ab66ea5a3a000edef6b4ab66289dd91899042d Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Wed, 7 Oct 2020 14:58:54 +0200 Subject: [PATCH 29/69] Add function --- htdocs/core/lib/functions2.lib.php | 72 ++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php index 7cc14060aac..d16a2b90243 100644 --- a/htdocs/core/lib/functions2.lib.php +++ b/htdocs/core/lib/functions2.lib.php @@ -2384,3 +2384,75 @@ function price2fec($amount) return $output; } + +/** + * Check the syntax of some PHP code. + * @param string $code PHP code to check. + * @return boolean|array If false, then check was successful, otherwise an array(message,line) of errors is returned. + */ +function phpSyntaxError($code) +{ + if (!defined("CR")) define("CR","\r"); + if (!defined("LF")) define("LF","\n") ; + if (!defined("CRLF")) define("CRLF","\r\n") ; + + $braces=0; + $inString=0; + foreach (token_get_all(' Date: Wed, 7 Oct 2020 13:01:28 +0000 Subject: [PATCH 30/69] Scrutinizer Auto-Fixes This commit consists of patches automatically generated for this project on https://scrutinizer-ci.com --- htdocs/accountancy/admin/defaultaccounts.php | 38 +- htdocs/accountancy/admin/fiscalyear_card.php | 10 +- htdocs/accountancy/admin/journals_list.php | 2 +- htdocs/accountancy/admin/subaccount.php | 36 +- .../accountancy/class/bookkeeping.class.php | 318 +- htdocs/accountancy/journal/bankjournal.php | 8 +- htdocs/adherents/subscription/card.php | 176 +- htdocs/admin/defaultvalues.php | 168 +- htdocs/admin/dict.php | 1766 ++++---- htdocs/admin/ecm_directories_extrafields.php | 20 +- htdocs/admin/ecm_files_extrafields.php | 20 +- htdocs/admin/menus/index.php | 8 +- htdocs/admin/oauthlogintokens.php | 520 +-- htdocs/admin/receiptprinter.php | 592 +-- htdocs/admin/security_file.php | 20 +- htdocs/admin/tools/dolibarr_export.php | 398 +- htdocs/admin/translation.php | 486 +-- htdocs/admin/website.php | 708 ++-- htdocs/api/class/api_setup.class.php | 3718 ++++++++--------- htdocs/bom/tpl/objectline_view.tpl.php | 38 +- htdocs/categories/photos.php | 140 +- htdocs/categories/traduction.php | 136 +- htdocs/comm/card.php | 628 +-- .../comm/propal/class/api_proposals.class.php | 554 +-- htdocs/commande/class/api_orders.class.php | 12 +- htdocs/compta/bank/bankentries_list.php | 1478 +++---- htdocs/compta/deplacement/card.php | 708 ++-- htdocs/contact/list.php | 4 +- htdocs/core/boxes/box_activity.php | 736 ++-- .../core/class/commondocgenerator.class.php | 1950 ++++----- htdocs/core/class/hookmanager.class.php | 226 +- htdocs/core/class/html.formother.class.php | 1940 ++++----- htdocs/core/lib/ecm.lib.php | 38 +- htdocs/core/lib/files.lib.php | 4 +- htdocs/core/lib/functions.lib.php | 20 +- htdocs/core/lib/payments.lib.php | 240 +- htdocs/core/lib/pdf.lib.php | 6 +- htdocs/core/modules/modCommande.class.php | 36 +- htdocs/core/modules/modFournisseur.class.php | 58 +- htdocs/core/modules/modMrp.class.php | 524 +-- htdocs/core/modules/modPropale.class.php | 34 +- .../modules/modWebServicesClient.class.php | 68 +- .../modules/printing/printgcp.modules.php | 866 ++-- htdocs/core/tpl/bloc_comment.tpl.php | 92 +- htdocs/ecm/class/ecmdirectory.class.php | 2 +- htdocs/ecm/file_card.php | 166 +- .../class/expensereport.class.php | 4 +- htdocs/fichinter/card.php | 522 +-- .../fourn/class/fournisseur.facture.class.php | 4 +- htdocs/fourn/commande/list.php | 42 +- htdocs/fourn/facture/card.php | 520 +-- htdocs/fourn/facture/document.php | 94 +- htdocs/hrm/index.php | 236 +- .../doc/pdf_standard_myobject.modules.php | 1364 +++--- htdocs/mrp/mo_card.php | 476 +-- htdocs/product/admin/dynamic_prices.php | 498 +-- htdocs/product/card.php | 56 +- .../class/productcustomerprice.class.php | 2 +- htdocs/product/price.php | 844 ++-- htdocs/product/stock/replenish.php | 6 +- htdocs/projet/class/project.class.php | 4 +- htdocs/projet/list.php | 126 +- htdocs/projet/tasks/task.php | 250 +- htdocs/resource/card.php | 40 +- htdocs/resource/list.php | 74 +- htdocs/societe/card.php | 1408 +++---- htdocs/societe/notify/card.php | 586 +-- htdocs/societe/paymentmodes.php | 136 +- htdocs/societe/price.php | 378 +- htdocs/takepos/index.php | 8 +- htdocs/takepos/invoice.php | 14 +- htdocs/takepos/pay.php | 4 +- htdocs/takepos/receipt.php | 32 +- htdocs/takepos/send.php | 44 +- htdocs/user/class/user.class.php | 12 +- htdocs/user/list.php | 48 +- htdocs/user/notify/card.php | 542 +-- htdocs/website/class/websitepage.class.php | 132 +- htdocs/website/index.php | 518 +-- htdocs/website/websiteaccount_card.php | 60 +- htdocs/zapier/hook_card.php | 126 +- 81 files changed, 14463 insertions(+), 14463 deletions(-) diff --git a/htdocs/accountancy/admin/defaultaccounts.php b/htdocs/accountancy/admin/defaultaccounts.php index 3d03dc9c4b6..b9377ce4431 100644 --- a/htdocs/accountancy/admin/defaultaccounts.php +++ b/htdocs/accountancy/admin/defaultaccounts.php @@ -47,9 +47,9 @@ $action = GETPOST('action', 'aZ09'); $list_account_main = array( - 'ACCOUNTING_ACCOUNT_CUSTOMER', - 'ACCOUNTING_ACCOUNT_SUPPLIER', - 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', + 'ACCOUNTING_ACCOUNT_CUSTOMER', + 'ACCOUNTING_ACCOUNT_SUPPLIER', + 'SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', ); $list_account = array(); @@ -120,9 +120,9 @@ if ($action == 'update') { $constvalue = GETPOST($constname, 'alpha'); - if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { - $error++; - } + if (!dolibarr_set_const($db, $constname, $constvalue, 'chaine', 0, '', $conf->entity)) { + $error++; + } } if (!$error) { @@ -159,20 +159,20 @@ print ''; print ''; foreach ($list_account_main as $key) { - print ''; - // Param - $label = $langs->trans($key); - $keydesc = $key.'_Desc'; + print ''; + // Param + $label = $langs->trans($key); + $keydesc = $key.'_Desc'; - $htmltext = $langs->trans($keydesc); - print ''; - // Value - print ''; - print ''; + $htmltext = $langs->trans($keydesc); + print ''; + // Value + print ''; + print ''; } diff --git a/htdocs/accountancy/admin/fiscalyear_card.php b/htdocs/accountancy/admin/fiscalyear_card.php index a122d3acab5..a4227a761a4 100644 --- a/htdocs/accountancy/admin/fiscalyear_card.php +++ b/htdocs/accountancy/admin/fiscalyear_card.php @@ -300,16 +300,16 @@ if ($action == 'create') if (!empty($user->rights->accounting->fiscalyear->write)) { - /* + /* * Barre d'actions */ - print '
'; + print ''; + print '
'; } } } else { diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php index e48ee43ef8d..819160e7d23 100644 --- a/htdocs/accountancy/admin/journals_list.php +++ b/htdocs/accountancy/admin/journals_list.php @@ -22,7 +22,7 @@ * \brief Setup page to configure journals */ -if (!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +if (!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; diff --git a/htdocs/accountancy/admin/subaccount.php b/htdocs/accountancy/admin/subaccount.php index fd6e33b6d00..a6f61283d75 100644 --- a/htdocs/accountancy/admin/subaccount.php +++ b/htdocs/accountancy/admin/subaccount.php @@ -59,10 +59,10 @@ if (!$sortfield) $sortfield = "label"; if (!$sortorder) $sortorder = "ASC"; $arrayfields = array( - 'subaccount'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), - 'label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), - 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), - 'reconcilable'=>array('label'=>$langs->trans("Reconcilable"), 'checked'=>1) + 'subaccount'=>array('label'=>$langs->trans("AccountNumber"), 'checked'=>1), + 'label'=>array('label'=>$langs->trans("Label"), 'checked'=>1), + 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), + 'reconcilable'=>array('label'=>$langs->trans("Reconcilable"), 'checked'=>1) ); if ($conf->global->MAIN_FEATURES_LEVEL < 2) unset($arrayfields['reconcilable']); @@ -80,17 +80,17 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if (!empty($cancel)) $action = ''; + if (!empty($cancel)) $action = ''; - 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 test are required to be compatible with all browsers - { - $search_subaccount = ""; - $search_label = ""; - $search_type = ""; + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All test are required to be compatible with all browsers + { + $search_subaccount = ""; + $search_label = ""; + $search_type = ""; $search_array_options = array(); - } + } } @@ -273,13 +273,13 @@ if ($resql) print '
'.$langs->trans("WarningCreateSubAccounts").'
'; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - $moreforfilter = ''; - $massactionbutton = ''; + $moreforfilter = ''; + $massactionbutton = ''; - print '
'; - print '
'.$langs->trans("ThirdParties").' | '.$langs->trans("Users").'
'; - print $form->textwithpicto($label, $htmltext); - print ''; // Do not force class=right, or it align also the content of the select box - print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); - print '
'; + print $form->textwithpicto($label, $htmltext); + print ''; // Do not force class=right, or it align also the content of the select box + print $formaccounting->select_account($conf->global->$key, $key, 1, '', 1, 1); + print '
'."\n"; + print '
'; + print '
'."\n"; // Line for search fields print ''; @@ -293,7 +293,7 @@ if ($resql) print ''; print ''; - print ''; + print ''; if (!empty($arrayfields['subaccount']['checked'])) print_liste_field_titre($arrayfields['subaccount']['label'], $_SERVER["PHP_SELF"], "subaccount", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['label']['checked'])) print_liste_field_titre($arrayfields['label']['label'], $_SERVER["PHP_SELF"], "label", "", $param, '', $sortfield, $sortorder); if (!empty($arrayfields['type']['checked'])) print_liste_field_titre($arrayfields['type']['label'], $_SERVER["PHP_SELF"], "type", "", $param, '', $sortfield, $sortorder, 'center '); diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 790aba68203..f5f4bf80221 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -57,80 +57,80 @@ class BookKeeping extends CommonObject */ public $id; - /** - * @var string Date of source document, in db date NOT NULL - */ + /** + * @var string Date of source document, in db date NOT NULL + */ public $doc_date; - /** - * @var int Deadline for payment - */ + /** + * @var int Deadline for payment + */ public $date_lim_reglement; - /** - * @var string doc_type - */ - public $doc_type; + /** + * @var string doc_type + */ + public $doc_type; - /** - * @var string doc_ref - */ + /** + * @var string doc_ref + */ public $doc_ref; /** - * @var int ID - */ + * @var int ID + */ public $fk_doc; /** - * @var int ID - */ + * @var int ID + */ public $fk_docdet; - /** - * @var string thirdparty code - */ - public $thirdparty_code; + /** + * @var string thirdparty code + */ + public $thirdparty_code; - /** - * @var string subledger account - */ + /** + * @var string subledger account + */ public $subledger_account; - /** - * @var string subledger label - */ + /** + * @var string subledger label + */ public $subledger_label; - /** - * @var string doc_type - */ + /** + * @var string doc_type + */ public $numero_compte; - /** - * @var string label compte - */ - public $label_compte; + /** + * @var string label compte + */ + public $label_compte; - /** - * @var string label operation - */ - public $label_operation; + /** + * @var string label operation + */ + public $label_operation; - /** - * @var float FEC:Debit - */ + /** + * @var float FEC:Debit + */ public $debit; - /** - * @var float FEC:Credit - */ + /** + * @var float FEC:Credit + */ public $credit; - /** - * @var float FEC:Amount (Not necessary) - * @deprecated Use $amount - */ + /** + * @var float FEC:Amount (Not necessary) + * @deprecated Use $amount + */ public $montant; /** @@ -138,34 +138,34 @@ class BookKeeping extends CommonObject */ public $amount; - /** - * @var string FEC:Sens (Not necessary) - */ + /** + * @var string FEC:Sens (Not necessary) + */ public $sens; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_author; - /** - * @var string key for import - */ + /** + * @var string key for import + */ public $import_key; - /** - * @var string code journal - */ + /** + * @var string code journal + */ public $code_journal; - /** - * @var string label journal - */ + /** + * @var string label journal + */ public $journal_label; - /** - * @var int accounting transaction id - */ + /** + * @var int accounting transaction id + */ public $piece_num; /** @@ -179,8 +179,8 @@ class BookKeeping extends CommonObject * * @param DoliDb $db Database handler */ - public function __construct(DoliDB $db) - { + public function __construct(DoliDB $db) + { $this->db = $db; } @@ -191,8 +191,8 @@ class BookKeeping extends CommonObject * @param bool $notrigger false=launch triggers after, true=disable triggers * @return int <0 if KO, Id of created object if OK */ - public function create(User $user, $notrigger = false) - { + public function create(User $user, $notrigger = false) + { global $conf, $langs; dol_syslog(__METHOD__, LOG_DEBUG); @@ -504,11 +504,11 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, Id of created object if OK */ - public function createStd(User $user, $notrigger = false, $mode = '') - { + public function createStd(User $user, $notrigger = false, $mode = '') + { global $conf, $langs; - $langs->loadLangs(array("accountancy", "bills", "compta")); + $langs->loadLangs(array("accountancy", "bills", "compta")); dol_syslog(__METHOD__, LOG_DEBUG); @@ -578,7 +578,7 @@ class BookKeeping extends CommonObject $now = dol_now(); // Check parameters - $this->journal_label = $langs->trans($this->journal_label); + $this->journal_label = $langs->trans($this->journal_label); // Insert request $sql = 'INSERT INTO '.MAIN_DB_PREFIX.$this->table_element.$mode.' ('; @@ -673,8 +673,8 @@ class BookKeeping extends CommonObject * * @return int <0 if KO, 0 if not found, >0 if OK */ - public function fetch($id, $ref = null, $mode = '') - { + public function fetch($id, $ref = null, $mode = '') + { global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -771,8 +771,8 @@ class BookKeeping extends CommonObject * * @return int <0 if KO, >=0 if OK */ - public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') - { + public function fetchAllByAccount($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND') + { global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -904,11 +904,11 @@ class BookKeeping extends CommonObject * @param int $offset Offset limit * @param array $filter Filter array * @param string $filtermode Filter mode (AND or OR) - * @param int $showAlreadyExportMovements Show movements when field 'date_export' is not empty (0:No / 1:Yes (Default)) + * @param int $showAlreadyExportMovements Show movements when field 'date_export' is not empty (0:No / 1:Yes (Default)) * @return int <0 if KO, >0 if OK */ - public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $showAlreadyExportMovements = 1) - { + public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND', $showAlreadyExportMovements = 1) + { global $conf; dol_syslog(__METHOD__, LOG_DEBUG); @@ -940,7 +940,7 @@ class BookKeeping extends CommonObject $sql .= " t.date_creation,"; $sql .= " t.date_lim_reglement,"; $sql .= " t.tms as date_modification,"; - $sql .= " t.date_export"; + $sql .= " t.date_export"; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; // Manage filter $sqlwhere = array(); @@ -960,8 +960,8 @@ class BookKeeping extends CommonObject $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.tms>=' || $key == 't.tms<=') { $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; - } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') { - $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; + } elseif ($key == 't.date_export>=' || $key == 't.date_export<=') { + $sqlwhere[] = $key.'\''.$this->db->idate($value).'\''; } elseif ($key == 't.credit' || $key == 't.debit') { $sqlwhere[] = natural_search($key, $value, 1, 1); } else { @@ -970,9 +970,9 @@ class BookKeeping extends CommonObject } } $sql .= ' WHERE t.entity IN ('.getEntity('accountancy').')'; - if ($showAlreadyExportMovements == 0) { - $sql .= " AND t.date_export IS NULL"; - } + if ($showAlreadyExportMovements == 0) { + $sql .= " AND t.date_export IS NULL"; + } if (count($sqlwhere) > 0) { $sql .= ' AND '.implode(' '.$filtermode.' ', $sqlwhere); } @@ -1020,7 +1020,7 @@ class BookKeeping extends CommonObject $line->date_creation = $this->db->jdate($obj->date_creation); $line->date_lim_reglement = $this->db->jdate($obj->date_lim_reglement); $line->date_modification = $this->db->jdate($obj->date_modification); - $line->date_export = $this->db->jdate($obj->date_export); + $line->date_export = $this->db->jdate($obj->date_export); $this->lines[] = $line; @@ -1133,8 +1133,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode ('' or _tmp') * @return int <0 if KO, >0 if OK */ - public function update(User $user, $notrigger = false, $mode = '') - { + public function update(User $user, $notrigger = false, $mode = '') + { $error = 0; dol_syslog(__METHOD__, LOG_DEBUG); @@ -1300,8 +1300,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, >0 if OK */ - public function delete(User $user, $notrigger = false, $mode = '') - { + public function delete(User $user, $notrigger = false, $mode = '') + { dol_syslog(__METHOD__, LOG_DEBUG); $error = 0; @@ -1348,8 +1348,8 @@ class BookKeeping extends CommonObject * @param string $importkey Import key * @return int Result */ - public function deleteByImportkey($importkey) - { + public function deleteByImportkey($importkey) + { $this->db->begin(); // first check if line not yet in bookkeeping @@ -1379,11 +1379,11 @@ class BookKeeping extends CommonObject * @param int $delmonth Month * @return int <0 if KO, >0 if OK */ - public function deleteByYearAndJournal($delyear = 0, $journal = '', $mode = '', $delmonth = 0) - { - global $langs; + public function deleteByYearAndJournal($delyear = 0, $journal = '', $mode = '', $delmonth = 0) + { + global $langs; - if (empty($delyear) && empty($journal)) + if (empty($delyear) && empty($journal)) { $this->error = 'ErrorOneFieldRequired'; return -1; @@ -1428,8 +1428,8 @@ class BookKeeping extends CommonObject * @param int $piecenum Piecenum to delete * @return int Result */ - public function deleteMvtNum($piecenum) - { + public function deleteMvtNum($piecenum) + { global $conf; $this->db->begin(); @@ -1463,8 +1463,8 @@ class BookKeeping extends CommonObject * @param int $fromid Id of object to clone * @return int New id of clone */ - public function createFromClone(User $user, $fromid) - { + public function createFromClone(User $user, $fromid) + { dol_syslog(__METHOD__, LOG_DEBUG); $error = 0; @@ -1511,8 +1511,8 @@ class BookKeeping extends CommonObject * * @return void */ - public function initAsSpecimen() - { + public function initAsSpecimen() + { global $user; $now = dol_now(); @@ -1548,8 +1548,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, >0 if OK */ - public function fetchPerMvt($piecenum, $mode = '') - { + public function fetchPerMvt($piecenum, $mode = '') + { global $conf; $sql = "SELECT piece_num,doc_date,code_journal,journal_label,doc_ref,doc_type,date_creation"; @@ -1613,8 +1613,8 @@ class BookKeeping extends CommonObject * @param string $mode Mode * @return int <0 if KO, >0 if OK */ - public function fetchAllPerMvt($piecenum, $mode = '') - { + public function fetchAllPerMvt($piecenum, $mode = '') + { global $conf; $sql = "SELECT rowid, doc_date, doc_type,"; @@ -1664,16 +1664,16 @@ class BookKeeping extends CommonObject return 1; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Export bookkeeping * * @param string $model Model * @return int Result */ - public function export_bookkeeping($model = 'ebp') - { - // phpcs:enable + public function export_bookkeeping($model = 'ebp') + { + // phpcs:enable global $conf; $sql = "SELECT rowid, doc_date, doc_type,"; @@ -1739,10 +1739,10 @@ class BookKeeping extends CommonObject $this->db->begin(); - if ($direction == 0) + if ($direction == 0) { $next_piecenum = $this->getNextNumMvt(); - $now = dol_now(); + $now = dol_now(); if ($next_piecenum < 0) { $error++; @@ -1819,22 +1819,22 @@ class BookKeeping extends CommonObject */ } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Return list of accounts with label by chart of accounts - * - * @param string $selectid Preselected chart of accounts - * @param string $htmlname Name of field in html form - * @param int $showempty Add an empty field - * @param array $event Event options - * @param int $select_in Value is a aa.rowid (0 default) or aa.account_number (1) - * @param int $select_out Set value returned by select 0=rowid (default), 1=account_number - * @param int $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number - * @return string String with HTML select - */ - public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') - { - // phpcs:enable + * Return list of accounts with label by chart of accounts + * + * @param string $selectid Preselected chart of accounts + * @param string $htmlname Name of field in html form + * @param int $showempty Add an empty field + * @param array $event Event options + * @param int $select_in Value is a aa.rowid (0 default) or aa.account_number (1) + * @param int $select_out Set value returned by select 0=rowid (default), 1=account_number + * @param int $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number + * @return string String with HTML select + */ + public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') + { + // phpcs:enable global $conf; require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php'; @@ -1891,7 +1891,7 @@ class BookKeeping extends CommonObject return $out; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Description of a root accounting account * @@ -1900,7 +1900,7 @@ class BookKeeping extends CommonObject */ public function get_compte_racine($account = null) { - // phpcs:enable + // phpcs:enable global $conf; $pcgver = $conf->global->CHARTOFACCOUNTS; @@ -1932,16 +1932,16 @@ class BookKeeping extends CommonObject } } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Description of accounting account * * @param string $account Accounting account * @return string Account desc */ - public function get_compte_desc($account = null) - { - // phpcs:enable + public function get_compte_desc($account = null) + { + // phpcs:enable global $conf; $pcgver = $conf->global->CHARTOFACCOUNTS; @@ -1989,13 +1989,13 @@ class BookKeepingLine public $doc_ref; /** - * @var int ID - */ + * @var int ID + */ public $fk_doc; /** - * @var int ID - */ + * @var int ID + */ public $fk_docdet; public $thirdparty_code; @@ -2007,26 +2007,26 @@ class BookKeepingLine public $debit; public $credit; - /** - * @var float Amount - * @deprecated see $amount - */ + /** + * @var float Amount + * @deprecated see $amount + */ public $montant; - /** - * @var float Amount - */ + /** + * @var float Amount + */ public $amount; - /** - * @var string Sens - */ - public $sens; - public $lettering_code; + /** + * @var string Sens + */ + public $sens; + public $lettering_code; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_author; public $import_key; @@ -2035,17 +2035,17 @@ class BookKeepingLine public $piece_num; /** - * @var integer|string date_creation - */ + * @var integer|string date_creation + */ public $date_creation; /** * @var integer|string $date_modification; */ - public $date_modification; + public $date_modification; - /** - * @var integer|string $date_export; - */ - public $date_export; + /** + * @var integer|string $date_export; + */ + public $date_export; } diff --git a/htdocs/accountancy/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php index 530dd6c5942..0ed6db948a2 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -180,10 +180,10 @@ if ($result) { $account_supplier = (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : 'NotDefined'); // NotDefined is a reserved word $account_customer = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : 'NotDefined'); // NotDefined is a reserved word $account_employee = (!empty($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT) ? $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT : 'NotDefined'); // NotDefined is a reserved word - $account_pay_vat = (!empty($conf->global->ACCOUNTING_VAT_PAY_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT : 'NotDefined'); // NotDefined is a reserved word - $account_pay_donation = (!empty($conf->global->DONATION_ACCOUNTINGACCOUNT) ? $conf->global->DONATION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word - $account_pay_subscription = (!empty($conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT) ? $conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word - $account_transfer = (!empty($conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH) ? $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH : 'NotDefined'); // NotDefined is a reserved word + $account_pay_vat = (!empty($conf->global->ACCOUNTING_VAT_PAY_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_PAY_ACCOUNT : 'NotDefined'); // NotDefined is a reserved word + $account_pay_donation = (!empty($conf->global->DONATION_ACCOUNTINGACCOUNT) ? $conf->global->DONATION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word + $account_pay_subscription = (!empty($conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT) ? $conf->global->ADHERENT_SUBSCRIPTION_ACCOUNTINGACCOUNT : 'NotDefined'); // NotDefined is a reserved word + $account_transfer = (!empty($conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH) ? $conf->global->ACCOUNTING_ACCOUNT_TRANSFER_CASH : 'NotDefined'); // NotDefined is a reserved word $tabcompany = array(); $tabuser = array(); diff --git a/htdocs/adherents/subscription/card.php b/htdocs/adherents/subscription/card.php index a79355de768..017962701e4 100644 --- a/htdocs/adherents/subscription/card.php +++ b/htdocs/adherents/subscription/card.php @@ -110,7 +110,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'update' && !$cance } else { $db->rollback(); - if ($object->error) { + if ($object->error) { $errmsg = $object->error; } else { foreach ($object->errors as $error) { @@ -128,13 +128,13 @@ if ($user->rights->adherent->cotisation->creer && $action == 'update' && !$cance if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->adherent->cotisation->creer) { $result = $object->fetch($rowid); - $result = $object->delete($user); - if ($result > 0) { - header("Location: ".DOL_URL_ROOT."/adherents/card.php?rowid=".$object->fk_adherent); - exit; - } else { - $mesg = $adh->error; - } + $result = $object->delete($user); + if ($result > 0) { + header("Location: ".DOL_URL_ROOT."/adherents/card.php?rowid=".$object->fk_adherent); + exit; + } else { + $mesg = $adh->error; + } } @@ -159,7 +159,7 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') { * ********************************************/ - $object->fetch($rowid); + $object->fetch($rowid); $result = $adh->fetch($object->fk_adherent); $head = subscription_prepare_head($object); @@ -172,13 +172,13 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') { dol_fiche_head($head, 'general', $langs->trans("Subscription"), 0, 'payment'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - print "\n"; + print "\n"; print '
'; - // Ref - print ''; + // Ref + print ''; print ''; @@ -195,24 +195,24 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') { print $form->selectarray("typeid", $adht->liste_array(), (GETPOSTISSET("typeid") ? GETPOST("typeid") : $object->fk_type)); print''; - // Date start subscription - print ''; - print ''; + print ''; - // Date end subscription - print ''; - print ''; + print ''; - // Amount - print ''; - // Label - print ''; // Bank line @@ -234,11 +234,11 @@ if ($user->rights->adherent->cotisation->creer && $action == 'edit') { dol_fiche_end(); - print '
'; - print ''; + print '
'; + print ''; print '       '; print ''; - print '
'; + print '
'; print ''; print "\n"; @@ -251,69 +251,69 @@ if ($rowid && $action != 'edit') { * ********************************************/ - $result = $object->fetch($rowid); + $result = $object->fetch($rowid); $result = $adh->fetch($object->fk_adherent); $head = subscription_prepare_head($object); dol_fiche_head($head, 'general', $langs->trans("Subscription"), -1, 'payment'); - // Confirmation to delete subscription - if ($action == 'delete') { + // Confirmation to delete subscription + if ($action == 'delete') { //$formquestion=array(); - //$formquestion['text']=''.$langs->trans("ThisWillAlsoDeleteBankRecord").''; + //$formquestion['text']=''.$langs->trans("ThisWillAlsoDeleteBankRecord").''; $text = $langs->trans("ConfirmDeleteSubscription"); if (!empty($conf->banque->enabled) && !empty($conf->global->ADHERENT_BANK_USE)) $text .= '
'.img_warning().' '.$langs->trans("ThisWillAlsoDeleteBankRecord"); print $form->formconfirm($_SERVER["PHP_SELF"]."?rowid=".$object->id, $langs->trans("DeleteSubscription"), $text, "confirm_delete", $formquestion, 0, 1); - } + } - print ''; - print ''; + print ''; + print ''; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - dol_banner_tab($object, 'rowid', $linkback, 1); + dol_banner_tab($object, 'rowid', $linkback, 1); - print '
'; + print '
'; - print '
'; + print '
'; - print '
'.$langs->trans("Ref").'
'.$langs->trans("Ref").''; print $form->showrefnav($object, 'rowid', $linkback, 1); print '
'.$langs->trans("DateSubscription").''; + // Date start subscription + print '
'.$langs->trans("DateSubscription").''; print $form->selectDate($object->dateh, 'datesub', 1, 1, 0, 'update', 1); print '
'.$langs->trans("DateEndSubscription").''; + // Date end subscription + print '
'.$langs->trans("DateEndSubscription").''; print $form->selectDate($object->datef, 'datesubend', 0, 0, 0, 'update', 1); print '
'.$langs->trans("Amount").''; + // Amount + print '
'.$langs->trans("Amount").''; print '
'.$langs->trans("Label").''; + // Label + print '
'.$langs->trans("Label").''; print '
'; + print '
'; - // Member - $adh->ref = $adh->getFullName($langs); - print ''; - print ''; - print ''; + // Member + $adh->ref = $adh->getFullName($langs); + print ''; + print ''; + print ''; - // Type - print ''; - print ''; - print ''; + // Type + print ''; + print ''; + print ''; - // Date subscription - print ''; + // Date subscription + print ''; print ''; - print ''; + print ''; - // Date end subscription - print ''; + // Date end subscription + print ''; print ''; - print ''; + print ''; - // Amount - print ''; + // Amount + print ''; - // Label - print ''; + // Label + print ''; // Bank line if (!empty($conf->banque->enabled)) { @@ -330,20 +330,20 @@ if ($rowid && $action != 'edit') { } } - print "
'.$langs->trans("Member").''.$adh->getNomUrl(1, 0, 'subscription').'
'.$langs->trans("Member").''.$adh->getNomUrl(1, 0, 'subscription').'
'.$langs->trans("Type").''; - if ($object->fk_type > 0 || $adh->typeid > 0) { - $typeid = ($object->fk_type > 0 ? $object->fk_type : $adh->typeid); - $adht->fetch($typeid); - print $adht->getNomUrl(1); - } else { - print $langs->trans("NoType"); - } - print '
'.$langs->trans("Type").''; + if ($object->fk_type > 0 || $adh->typeid > 0) { + $typeid = ($object->fk_type > 0 ? $object->fk_type : $adh->typeid); + $adht->fetch($typeid); + print $adht->getNomUrl(1); + } else { + print $langs->trans("NoType"); + } + print '
'.$langs->trans("DateSubscription").''.dol_print_date($object->dateh, 'day').'
'.$langs->trans("DateEndSubscription").''.dol_print_date($object->datef, 'day').'
'.$langs->trans("Amount").''.price($object->amount).'
'.$langs->trans("Amount").''.price($object->amount).'
'.$langs->trans("Label").''.$object->note.'
'.$langs->trans("Label").''.$object->note.'
\n"; - print ''; + print "
\n"; + print '
'; - print ''; + print ''; - dol_fiche_end(); + dol_fiche_end(); - /* + /* * Barre d'actions * */ - print '
'; + print '
'; - if ($user->rights->adherent->cotisation->creer) { + if ($user->rights->adherent->cotisation->creer) { if (!$bankline->rappro) { print '"; } else { @@ -351,19 +351,19 @@ if ($rowid && $action != 'edit') { } } - // Delete - if ($user->rights->adherent->cotisation->creer) { - print '\n"; - } + // Delete + if ($user->rights->adherent->cotisation->creer) { + print '\n"; + } - print '
'; + print '
'; - print '
'; - print ''; // ancre + print '
'; + print ''; // ancre - // Documents generes - /* + // Documents generes + /* $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->facture->dir_output . '/' . dol_sanitizeFileName($object->ref); $urlsource = $_SERVER['PHP_SELF'] . '?facid=' . $object->id; @@ -375,23 +375,23 @@ if ($rowid && $action != 'edit') { */ // Show links to link elements //$linktoelem = $form->showLinkToObjectBlock($object, null, array('subscription')); - $somethingshown = $form->showLinkedObjectBlock($object, ''); + $somethingshown = $form->showLinkedObjectBlock($object, ''); - // Show links to link elements - /*$linktoelem = $form->showLinkToObjectBlock($object,array('order')); + // Show links to link elements + /*$linktoelem = $form->showLinkToObjectBlock($object,array('order')); if ($linktoelem) print ($somethingshown?'':'
').$linktoelem; */ - print '
'; + print '
'; - // List of actions on element - /* + // List of actions on element + /* include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; $formactions = new FormActions($db); $somethingshown = $formactions->showactions($object, 'invoice', $socid, 1); */ - print '
'; + print '
'; } // End of page diff --git a/htdocs/admin/defaultvalues.php b/htdocs/admin/defaultvalues.php index 17fa15af382..6e172656930 100644 --- a/htdocs/admin/defaultvalues.php +++ b/htdocs/admin/defaultvalues.php @@ -83,17 +83,17 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $defaulturl = ''; - $defaultkey = ''; - $defaultvalue = ''; - $toselect = ''; - $search_array_options = array(); + $defaulturl = ''; + $defaultkey = ''; + $defaultvalue = ''; + $toselect = ''; + $search_array_options = array(); } if ($action == 'setMAIN_ENABLE_DEFAULT_VALUES') { - if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 1, 'chaine', 0, '', $conf->entity); - else dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 0, 'chaine', 0, '', $conf->entity); + if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 1, 'chaine', 0, '', $conf->entity); + else dolibarr_set_const($db, 'MAIN_ENABLE_DEFAULT_VALUES', 0, 'chaine', 0, '', $conf->entity); } if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('actionmodify')) @@ -102,57 +102,57 @@ if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('ac if (($action == 'add' || (GETPOST('add') && $action != 'update'))) { - if (empty($defaulturl)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors'); - $error++; - } - if (empty($defaultkey)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors'); - $error++; - } + if (empty($defaulturl)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors'); + $error++; + } + if (empty($defaultkey)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors'); + $error++; + } } if (GETPOST('actionmodify')) { - if (empty($urlpage)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors'); - $error++; - } - if (empty($key)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors'); - $error++; - } + if (empty($urlpage)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Url")), null, 'errors'); + $error++; + } + if (empty($key)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Field")), null, 'errors'); + $error++; + } } if (!$error) { - $db->begin(); + $db->begin(); - if ($action == 'add' || (GETPOST('add') && $action != 'update')) - { - $sql = "INSERT INTO ".MAIN_DB_PREFIX."default_values(type, user_id, page, param, value, entity) VALUES ('".$db->escape($mode)."', 0, '".$db->escape($defaulturl)."','".$db->escape($defaultkey)."','".$db->escape($defaultvalue)."', ".$db->escape($conf->entity).")"; - } - if (GETPOST('actionmodify')) - { - $sql = "UPDATE ".MAIN_DB_PREFIX."default_values SET page = '".$db->escape($urlpage)."', param = '".$db->escape($key)."', value = '".$db->escape($value)."'"; - $sql .= " WHERE rowid = ".$id; - } + if ($action == 'add' || (GETPOST('add') && $action != 'update')) + { + $sql = "INSERT INTO ".MAIN_DB_PREFIX."default_values(type, user_id, page, param, value, entity) VALUES ('".$db->escape($mode)."', 0, '".$db->escape($defaulturl)."','".$db->escape($defaultkey)."','".$db->escape($defaultvalue)."', ".$db->escape($conf->entity).")"; + } + if (GETPOST('actionmodify')) + { + $sql = "UPDATE ".MAIN_DB_PREFIX."default_values SET page = '".$db->escape($urlpage)."', param = '".$db->escape($key)."', value = '".$db->escape($value)."'"; + $sql .= " WHERE rowid = ".$id; + } $result = $db->query($sql); if ($result > 0) { - $db->commit(); + $db->commit(); setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $action = ""; $defaulturl = ''; $defaultkey = ''; $defaultvalue = ''; } else { - $db->rollback(); - setEventMessages($db->lasterror(), null, 'errors'); + $db->rollback(); + setEventMessages($db->lasterror(), null, 'errors'); $action = ''; } } @@ -189,15 +189,15 @@ $param = '&mode='.$mode; $enabledisablehtml .= $langs->trans("EnableDefaultValues").' '; if (empty($conf->global->MAIN_ENABLE_DEFAULT_VALUES)) { - // Button off, click to enable - $enabledisablehtml .= ''; - $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); - $enabledisablehtml .= ''; + // Button off, click to enable + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); + $enabledisablehtml .= ''; } else { - // Button on, click to disable - $enabledisablehtml .= ''; - $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); - $enabledisablehtml .= ''; + // Button on, click to disable + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); + $enabledisablehtml .= ''; } print load_fiche_titre($langs->trans("DefaultValues"), $enabledisablehtml, 'title_setup'); @@ -228,7 +228,7 @@ dol_fiche_head($head, $mode, '', -1, ''); if ($mode == 'sortorder') { - print info_admin($langs->trans("WarningSettingSortOrder")).'
'; + print info_admin($langs->trans("WarningSettingSortOrder")).'
'; } if ($mode == 'mandatory') { @@ -253,30 +253,30 @@ print_liste_field_titre($texturl, $_SERVER["PHP_SELF"], 'page,param', '', $param $texthelp = $langs->trans("TheKeyIsTheNameOfHtmlField"); if ($mode != 'sortorder') { - $textkey = $form->textwithpicto($langs->trans("Field"), $texthelp); + $textkey = $form->textwithpicto($langs->trans("Field"), $texthelp); } else { - $texthelp = 'field or alias.field'; - $textkey = $form->textwithpicto($langs->trans("Field"), $texthelp); + $texthelp = 'field or alias.field'; + $textkey = $form->textwithpicto($langs->trans("Field"), $texthelp); } print_liste_field_titre($textkey, $_SERVER["PHP_SELF"], 'param', '', $param, '', $sortfield, $sortorder); // Value if ($mode != 'focus' && $mode != 'mandatory') { - if ($mode != 'sortorder') - { - $substitutionarray = getCommonSubstitutionArray($langs, 2, array('object', 'objectamount')); // Must match list into GETPOST + if ($mode != 'sortorder') + { + $substitutionarray = getCommonSubstitutionArray($langs, 2, array('object', 'objectamount')); // Must match list into GETPOST unset($substitutionarray['__USER_SIGNATURE__']); - $texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'
'; - foreach ($substitutionarray as $key => $val) - { - $texthelp .= $key.' -> '.$val.'
'; - } - $textvalue = $form->textwithpicto($langs->trans("Value"), $texthelp, 1, 'help', '', 0, 2, 'subsitutiontooltip'); - } else { - $texthelp = 'ASC or DESC'; - $textvalue = $form->textwithpicto($langs->trans("SortOrder"), $texthelp); - } - print_liste_field_titre($textvalue, $_SERVER["PHP_SELF"], 'value', '', $param, '', $sortfield, $sortorder); + $texthelp = $langs->trans("FollowingConstantsWillBeSubstituted").'
'; + foreach ($substitutionarray as $key => $val) + { + $texthelp .= $key.' -> '.$val.'
'; + } + $textvalue = $form->textwithpicto($langs->trans("Value"), $texthelp, 1, 'help', '', 0, 2, 'subsitutiontooltip'); + } else { + $texthelp = 'ASC or DESC'; + $textvalue = $form->textwithpicto($langs->trans("SortOrder"), $texthelp); + } + print_liste_field_titre($textvalue, $_SERVER["PHP_SELF"], 'value', '', $param, '', $sortfield, $sortorder); } // Entity if (!empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,page', '', $param, '', $sortfield, $sortorder); @@ -301,9 +301,9 @@ print ''; // Value if ($mode != 'focus' && $mode != 'mandatory') { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } // Limit to superadmin if (!empty($conf->multicompany->enabled) && !$user->entity) @@ -361,32 +361,32 @@ if ($result) // Value if ($mode != 'focus' && $mode != 'mandatory') { - print ''; - /*print ''; + print ''; + /*print ''; print ''; print ''; print ''; */ - if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print dol_escape_htmltag($obj->value); - else print ''; - print ''; + if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print dol_escape_htmltag($obj->value); + else print ''; + print ''; } - print ''; + print ''; // Actions print ''; if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) { - print ''.img_edit().''; - print '   '; - print ''.img_delete().''; + print ''.img_edit().''; + print '   '; + print ''.img_delete().''; } else { - print ''; - print ''; - print '
'; - print ''; - print ''; + print ''; + print ''; + print '
'; + print ''; + print ''; } print ''; @@ -395,7 +395,7 @@ if ($result) $i++; } } else { - dol_print_error($db); + dol_print_error($db); } print ''; diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index e40a84db0ec..6e9c63ca6cf 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -511,7 +511,7 @@ $tabhelp[23] = array('revenuestamp_type'=>'FixedOrPercent'); $tabhelp[24] = array('code'=>$langs->trans("EnterAnyCode")); $tabhelp[25] = array('code'=>$langs->trans('EnterAnyCode')); //$tabhelp[26] = array('code'=>$langs->trans("EnterAnyCode")); -$tabhelp[27] = array('code'=>$langs->trans("EnterAnyCode"),'picto'=>$langs->trans("PictoHelp")); +$tabhelp[27] = array('code'=>$langs->trans("EnterAnyCode"), 'picto'=>$langs->trans("PictoHelp")); $tabhelp[28] = array('affect'=>$langs->trans("FollowedByACounter"), 'delay'=>$langs->trans("MinimumNoticePeriod"), 'newbymonth'=>$langs->trans("NbAddedAutomatically")); $tabhelp[29] = array('code'=>$langs->trans("EnterAnyCode"), 'percent'=>$langs->trans("OpportunityPercent"), 'position'=>$langs->trans("PositionIntoComboList")); $tabhelp[30] = array('code'=>$langs->trans("EnterAnyCode"), 'name'=>$langs->trans("LabelName"), 'paper_size'=>$langs->trans("LabelPaperSize")); @@ -524,7 +524,7 @@ $tabhelp[36] = array('range_ik'=>$langs->trans('PrevRangeToThisRange')); $tabhelp[37] = array('code'=>$langs->trans("EnterAnyCode"), 'unit_type' => $langs->trans('MeasuringUnitTypeDesc'), 'scale' => $langs->trans('MeasuringScaleDesc')); $tabhelp[38] = array('code'=>$langs->trans("EnterAnyCode"), 'url' => $langs->trans('UrlSocialNetworksDesc'), 'icon' => $langs->trans('FafaIconSocialNetworksDesc')); $tabhelp[39] = array('code'=>$langs->trans("EnterAnyCode")); -$tabhelp[40] = array('code'=>$langs->trans("EnterAnyCode"),'picto'=>$langs->trans("PictoHelp")); +$tabhelp[40] = array('code'=>$langs->trans("EnterAnyCode"), 'picto'=>$langs->trans("PictoHelp")); // List of check for fields (NOT USED YET) $tabfieldcheck = array(); @@ -576,9 +576,9 @@ complete_dictionary_with_modules($taborder, $tabname, $tablib, $tabsql, $tabsqls // Defaut sortorder if (empty($sortfield)) { - $tmp1 = explode(',', $tabsqlsort[$id]); - $tmp2 = explode(' ', $tmp1[0]); - $sortfield = preg_replace('/^.*\./', '', $tmp2[0]); + $tmp1 = explode(',', $tabsqlsort[$id]); + $tmp2 = explode(' ', $tmp1[0]); + $sortfield = preg_replace('/^.*\./', '', $tmp2[0]); } // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") @@ -586,27 +586,27 @@ $elementList = array(); $sourceList = array(); if ($id == 11) { - $elementList = array( - '' => '', - 'societe' => $langs->trans('ThirdParty'), - // 'proposal' => $langs->trans('Proposal'), - // 'order' => $langs->trans('Order'), - // 'invoice' => $langs->trans('Bill'), - 'supplier_proposal' => $langs->trans('SupplierProposal'), - 'order_supplier' => $langs->trans('SupplierOrder'), - 'invoice_supplier' => $langs->trans('SupplierBill'), - // 'intervention' => $langs->trans('InterventionCard'), - // 'contract' => $langs->trans('Contract'), - 'project' => $langs->trans('Project'), - 'project_task' => $langs->trans('Task'), - 'agenda' => $langs->trans('Agenda'), - 'dolresource' => $langs->trans('Resource'), - // old deprecated - 'propal' => $langs->trans('Proposal'), - 'commande' => $langs->trans('Order'), - 'facture' => $langs->trans('Bill'), - 'fichinter' => $langs->trans('InterventionCard'), - 'contrat' => $langs->trans('Contract'), + $elementList = array( + '' => '', + 'societe' => $langs->trans('ThirdParty'), + // 'proposal' => $langs->trans('Proposal'), + // 'order' => $langs->trans('Order'), + // 'invoice' => $langs->trans('Bill'), + 'supplier_proposal' => $langs->trans('SupplierProposal'), + 'order_supplier' => $langs->trans('SupplierOrder'), + 'invoice_supplier' => $langs->trans('SupplierBill'), + // 'intervention' => $langs->trans('InterventionCard'), + // 'contract' => $langs->trans('Contract'), + 'project' => $langs->trans('Project'), + 'project_task' => $langs->trans('Task'), + 'agenda' => $langs->trans('Agenda'), + 'dolresource' => $langs->trans('Resource'), + // old deprecated + 'propal' => $langs->trans('Proposal'), + 'commande' => $langs->trans('Order'), + 'facture' => $langs->trans('Bill'), + 'fichinter' => $langs->trans('InterventionCard'), + 'contrat' => $langs->trans('Contract'), ); if (!empty($conf->global->MAIN_SUPPORT_SHARED_CONTACT_BETWEEN_THIRDPARTIES)) $elementList["societe"] = $langs->trans('ThirdParty'); @@ -642,329 +642,329 @@ if ($id == 10) if (GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter_x', 'alpha')) { - $search_country_id = ''; - $search_code = ''; + $search_country_id = ''; + $search_code = ''; } // Actions add or modify an entry into a dictionary if (GETPOST('actionadd') || GETPOST('actionmodify')) { - $listfield = explode(',', str_replace(' ', '', $tabfield[$id])); - $listfieldinsert = explode(',', $tabfieldinsert[$id]); - $listfieldmodify = explode(',', $tabfieldinsert[$id]); - $listfieldvalue = explode(',', $tabfieldvalue[$id]); + $listfield = explode(',', str_replace(' ', '', $tabfield[$id])); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); - // Check that all fields are filled - $ok = 1; - foreach ($listfield as $f => $value) - { - // Discard check of mandatory fields for country for some tables - if ($value == 'country_id' && in_array($tablib[$id], array('DictionaryPublicHolidays', 'DictionaryVAT', 'DictionaryRegion', 'DictionaryCompanyType', 'DictionaryHolidayTypes', 'DictionaryRevenueStamp', 'DictionaryAccountancysystem', 'DictionaryAccountancyCategory'))) continue; // For some pages, country is not mandatory - if ($value == 'country' && in_array($tablib[$id], array('DictionaryPublicHolidays', 'DictionaryCanton', 'DictionaryCompanyType', 'DictionaryRevenueStamp'))) continue; // For some pages, country is not mandatory - // Discard check of mandatory fiedls for other fields - if ($value == 'localtax1' && empty($_POST['localtax1_type'])) continue; - if ($value == 'localtax2' && empty($_POST['localtax2_type'])) continue; - if ($value == 'color' && empty($_POST['color'])) continue; + // Check that all fields are filled + $ok = 1; + foreach ($listfield as $f => $value) + { + // Discard check of mandatory fields for country for some tables + if ($value == 'country_id' && in_array($tablib[$id], array('DictionaryPublicHolidays', 'DictionaryVAT', 'DictionaryRegion', 'DictionaryCompanyType', 'DictionaryHolidayTypes', 'DictionaryRevenueStamp', 'DictionaryAccountancysystem', 'DictionaryAccountancyCategory'))) continue; // For some pages, country is not mandatory + if ($value == 'country' && in_array($tablib[$id], array('DictionaryPublicHolidays', 'DictionaryCanton', 'DictionaryCompanyType', 'DictionaryRevenueStamp'))) continue; // For some pages, country is not mandatory + // Discard check of mandatory fiedls for other fields + if ($value == 'localtax1' && empty($_POST['localtax1_type'])) continue; + if ($value == 'localtax2' && empty($_POST['localtax2_type'])) continue; + if ($value == 'color' && empty($_POST['color'])) continue; if ($value == 'formula' && empty($_POST['formula'])) continue; if ($value == 'dayrule' && empty($_POST['dayrule'])) continue; if ($value == 'sortorder') continue; // For a column name 'sortorder', we use the field name 'position' if ((!isset($_POST[$value]) || $_POST[$value] == '') - && (!in_array($listfield[$f], array('decalage', 'module', 'accountancy_code', 'accountancy_code_sell', 'accountancy_code_buy', 'tracking', 'picto')) // Fields that are not mandatory - && (!($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 - ) + && (!in_array($listfield[$f], array('decalage', 'module', 'accountancy_code', 'accountancy_code_sell', 'accountancy_code_buy', 'tracking', 'picto')) // Fields that are not mandatory + && (!($id == 10 && $listfield[$f] == 'code')) // Code is mandatory fir table 10 + ) ) { - $ok = 0; - $fieldnamekey = $listfield[$f]; - // We take translate key of field - if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey = 'Label'; - if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; - if ($fieldnamekey == 'nbjour') $fieldnamekey = 'NbOfDays'; - if ($fieldnamekey == 'decalage') $fieldnamekey = 'Offset'; - if ($fieldnamekey == 'module') $fieldnamekey = 'Module'; - if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; - if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; - if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; - if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; - if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; - if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode'; - if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible'; - if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder'; + $ok = 0; + $fieldnamekey = $listfield[$f]; + // We take translate key of field + if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) $fieldnamekey = 'Label'; + if ($fieldnamekey == 'libelle_facture') $fieldnamekey = 'LabelOnDocuments'; + if ($fieldnamekey == 'nbjour') $fieldnamekey = 'NbOfDays'; + if ($fieldnamekey == 'decalage') $fieldnamekey = 'Offset'; + if ($fieldnamekey == 'module') $fieldnamekey = 'Module'; + if ($fieldnamekey == 'code') $fieldnamekey = 'Code'; + if ($fieldnamekey == 'note') $fieldnamekey = 'Note'; + if ($fieldnamekey == 'taux') $fieldnamekey = 'Rate'; + if ($fieldnamekey == 'type') $fieldnamekey = 'Type'; + if ($fieldnamekey == 'position') $fieldnamekey = 'Position'; + if ($fieldnamekey == 'unicode') $fieldnamekey = 'Unicode'; + if ($fieldnamekey == 'deductible') $fieldnamekey = 'Deductible'; + if ($fieldnamekey == 'sortorder') $fieldnamekey = 'SortOrder'; if ($fieldnamekey == 'category_type') $fieldnamekey = 'Calculated'; if ($fieldnamekey == 'revenuestamp_type') $fieldnamekey = 'TypeOfRevenueStamp'; if ($fieldnamekey == 'use_default') $fieldnamekey = 'UseByDefault'; - setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); - } - } - // Other checks - if (GETPOST('actionadd') && $tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"], array('system', 'systemauto'))) { - $ok = 0; - setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); - } - if (GETPOSTISSET("code")) - { - if (GETPOST("code") == '0') - { - $ok = 0; - setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); - } - /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); + } + } + // Other checks + if (GETPOST('actionadd') && $tabname[$id] == MAIN_DB_PREFIX."c_actioncomm" && isset($_POST["type"]) && in_array($_POST["type"], array('system', 'systemauto'))) { + $ok = 0; + setEventMessages($langs->transnoentities('ErrorReservedTypeSystemSystemAuto'), null, 'errors'); + } + if (GETPOSTISSET("code")) + { + if (GETPOST("code") == '0') + { + $ok = 0; + setEventMessages($langs->transnoentities('ErrorCodeCantContainZero'), null, 'errors'); + } + /*if (!is_numeric($_POST['code'])) // disabled, code may not be in numeric base { $ok = 0; $msg .= $langs->transnoentities('ErrorFieldFormat', $langs->transnoentities('Code')).'
'; }*/ - } - if (GETPOSTISSET("country") && ($_POST["country"] == '0') && ($id != 2)) - { - if (in_array($tablib[$id], array('DictionaryCompanyType', 'DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries - { - $_POST["country"] = ''; - } else { - $ok = 0; - setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("Country")), null, 'errors'); - } - } - if ($id == 3 && !is_numeric($_POST["code"])) - { - $ok = 0; - setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric", $langs->transnoentities("Code")), null, 'errors'); - } + } + if (GETPOSTISSET("country") && ($_POST["country"] == '0') && ($id != 2)) + { + if (in_array($tablib[$id], array('DictionaryCompanyType', 'DictionaryHolidayTypes'))) // Field country is no mandatory for such dictionaries + { + $_POST["country"] = ''; + } else { + $ok = 0; + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("Country")), null, 'errors'); + } + } + if ($id == 3 && !is_numeric($_POST["code"])) + { + $ok = 0; + setEventMessages($langs->transnoentities("ErrorFieldMustBeANumeric", $langs->transnoentities("Code")), null, 'errors'); + } // Clean some parameters - if ((!empty($_POST["localtax1_type"]) || ($_POST['localtax1_type'] == '0')) && empty($_POST["localtax1"])) $_POST["localtax1"] = '0'; // If empty, we force to 0 - if ((!empty($_POST["localtax2_type"]) || ($_POST['localtax2_type'] == '0')) && empty($_POST["localtax2"])) $_POST["localtax2"] = '0'; // If empty, we force to 0 + if ((!empty($_POST["localtax1_type"]) || ($_POST['localtax1_type'] == '0')) && empty($_POST["localtax1"])) $_POST["localtax1"] = '0'; // If empty, we force to 0 + if ((!empty($_POST["localtax2_type"]) || ($_POST['localtax2_type'] == '0')) && empty($_POST["localtax2"])) $_POST["localtax2"] = '0'; // If empty, we force to 0 if ($_POST["accountancy_code"] <= 0) $_POST["accountancy_code"] = ''; // If empty, we force to null if ($_POST["accountancy_code_sell"] <= 0) $_POST["accountancy_code_sell"] = ''; // If empty, we force to null if ($_POST["accountancy_code_buy"] <= 0) $_POST["accountancy_code_buy"] = ''; // If empty, we force to null - if ($id == 10 && isset($_POST["code"])) // Spaces are not allowed into code - { - $_POST["code"] = preg_replace('/\s/', '', $_POST["code"]); - } + if ($id == 10 && isset($_POST["code"])) // Spaces are not allowed into code + { + $_POST["code"] = preg_replace('/\s/', '', $_POST["code"]); + } - // If check ok and action add, add the line - if ($ok && GETPOST('actionadd')) - { - if ($tabrowid[$id]) - { - // Get free id for insert - $newid = 0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid = ($obj->newid + 1); - } else { - dol_print_error($db); - } - } + // If check ok and action add, add the line + if ($ok && GETPOST('actionadd')) + { + if ($tabrowid[$id]) + { + // Get free id for insert + $newid = 0; + $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + $newid = ($obj->newid + 1); + } else { + dol_print_error($db); + } + } - // Add new entry - $sql = "INSERT INTO ".$tabname[$id]." ("; - // List of fields - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) - $sql .= $tabrowid[$id].","; - $sql .= $tabfieldinsert[$id]; - $sql .= ",active)"; - $sql .= " VALUES("; + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $tabrowid[$id].","; + $sql .= $tabfieldinsert[$id]; + $sql .= ",active)"; + $sql .= " VALUES("; - // List of values - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) - $sql .= $newid.","; - $i = 0; - foreach ($listfieldinsert as $f => $value) - { - $keycode = $listfieldvalue[$i]; - if (empty($keycode)) $keycode = $value; + // List of values + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $newid.","; + $i = 0; + foreach ($listfieldinsert as $f => $value) + { + $keycode = $listfieldvalue[$i]; + if (empty($keycode)) $keycode = $value; - if ($value == 'price' || preg_match('/^amount/i', $value) || $value == 'taux') { - $_POST[$keycode] = price2num($_POST[$keycode], 'MU'); - } elseif ($value == 'entity') { - $_POST[$keycode] = getEntity($tabname[$id]); - } + if ($value == 'price' || preg_match('/^amount/i', $value) || $value == 'taux') { + $_POST[$keycode] = price2num($_POST[$keycode], 'MU'); + } elseif ($value == 'entity') { + $_POST[$keycode] = getEntity($tabname[$id]); + } - if ($i) $sql .= ","; + if ($i) $sql .= ","; - if ($keycode == 'sortorder') // For column name 'sortorder', we use the field name 'position' - { - $sql .= "'".(int) GETPOST('position', 'int')."'"; - } elseif ($_POST[$keycode] == '' && !($keycode == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = '' - elseif ($keycode == 'content') { - $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; - } elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { - $sql .= (int) GETPOST($keycode, 'int'); - } else { - $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; - } + if ($keycode == 'sortorder') // For column name 'sortorder', we use the field name 'position' + { + $sql .= "'".(int) GETPOST('position', 'int')."'"; + } elseif ($_POST[$keycode] == '' && !($keycode == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = '' + elseif ($keycode == 'content') { + $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; + } elseif (in_array($keycode, array('joinfile', 'private', 'position', 'scale'))) { + $sql .= (int) GETPOST($keycode, 'int'); + } else { + $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; + } - $i++; - } - $sql .= ",1)"; + $i++; + } + $sql .= ",1)"; - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - $_POST = array('id'=>$id); // Clean $_POST array, we keep only - } else { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } else { - dol_print_error($db); - } - } - } + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + $_POST = array('id'=>$id); // Clean $_POST array, we keep only + } else { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } else { + dol_print_error($db); + } + } + } - // If verif ok and action modify, modify the line - if ($ok && GETPOST('actionmodify')) - { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + // If verif ok and action modify, modify the line + if ($ok && GETPOST('actionmodify')) + { + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) - { - $sql .= $tabrowid[$id]."="; - $sql .= "'".$db->escape($rowid)."', "; - } - $i = 0; - foreach ($listfieldmodify as $field) - { - $keycode = $listfieldvalue[$i]; - if (empty($keycode)) $keycode = $field; + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) + { + $sql .= $tabrowid[$id]."="; + $sql .= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + $keycode = $listfieldvalue[$i]; + if (empty($keycode)) $keycode = $field; - if ($field == 'price' || preg_match('/^amount/i', $field) || $field == 'taux') { - $_POST[$keycode] = price2num($_POST[$keycode], 'MU'); - } elseif ($field == 'entity') { - $_POST[$keycode] = getEntity($tabname[$id]); - } + if ($field == 'price' || preg_match('/^amount/i', $field) || $field == 'taux') { + $_POST[$keycode] = price2num($_POST[$keycode], 'MU'); + } elseif ($field == 'entity') { + $_POST[$keycode] = getEntity($tabname[$id]); + } - if ($i) $sql .= ","; - $sql .= $field."="; - if ($listfieldvalue[$i] == 'sortorder') // For column name 'sortorder', we use the field name 'position' - { - $sql .= (int) GETPOST('position', 'int'); - } elseif ($_POST[$keycode] == '' && !($keycode == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = '' - elseif ($keycode == 'content') { - $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; - } elseif (in_array($keycode, array('private', 'position', 'scale'))) { - $sql .= (int) GETPOST($keycode, 'int'); - } else { - $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; - } + if ($i) $sql .= ","; + $sql .= $field."="; + if ($listfieldvalue[$i] == 'sortorder') // For column name 'sortorder', we use the field name 'position' + { + $sql .= (int) GETPOST('position', 'int'); + } elseif ($_POST[$keycode] == '' && !($keycode == 'code' && $id == 10)) $sql .= "null"; // For vat, we want/accept code = '' + elseif ($keycode == 'content') { + $sql .= "'".$db->escape(GETPOST($keycode, 'restricthtml'))."'"; + } elseif (in_array($keycode, array('private', 'position', 'scale'))) { + $sql .= (int) GETPOST($keycode, 'int'); + } else { + $sql .= "'".$db->escape(GETPOST($keycode, 'nohtml'))."'"; + } - $i++; - } - $sql .= " WHERE ".$rowidcol." = ".(int) $db->escape($rowid); - if (in_array('entity', $listfieldmodify)) $sql .= " AND entity = '".getEntity($tabname[$id])."'"; + $i++; + } + $sql .= " WHERE ".$rowidcol." = ".(int) $db->escape($rowid); + if (in_array('entity', $listfieldmodify)) $sql .= " AND entity = '".getEntity($tabname[$id])."'"; - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if (!$resql) - { - setEventMessages($db->error(), null, 'errors'); - } - } - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if (!$resql) + { + setEventMessages($db->error(), null, 'errors'); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if (GETPOST('actioncancel')) { - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $sql = "DELETE FROM ".$tabname[$id]." WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + $sql = "DELETE FROM ".$tabname[$id]." WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - dol_syslog("delete", LOG_DEBUG); - $result = $db->query($sql); - if (!$result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } else { - dol_print_error($db); - } - } + dol_syslog("delete", LOG_DEBUG); + $result = $db->query($sql); + if (!$result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } else { + dol_print_error($db); + } + } } // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET active = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // favorite if ($action == 'activate_favorite') { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 1 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable favorite if ($action == 'disable_favorite') { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } elseif ($code) { - $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE ".$rowidcol."='".$db->escape($rowid)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } elseif ($code) { + $sql = "UPDATE ".$tabname[$id]." SET favorite = 0 WHERE code='".dol_escape_htmltag($code)."'".($entity != '' ? " AND entity = ".(int) $entity : ''); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } @@ -982,28 +982,28 @@ llxHeader('', $title); $linkback = ''; if ($id) { - $title .= ' - '.$langs->trans($tablib[$id]); - $linkback = ''.$langs->trans("BackToDictionaryList").''; + $title .= ' - '.$langs->trans($tablib[$id]); + $linkback = ''.$langs->trans("BackToDictionaryList").''; } $titlepicto = 'title_setup'; if ($id == 10 && GETPOST('from') == 'accountancy') { - $title = $langs->trans("MenuVatAccounts"); - $titlepicto = 'accountancy'; + $title = $langs->trans("MenuVatAccounts"); + $titlepicto = 'accountancy'; } if ($id == 7 && GETPOST('from') == 'accountancy') { - $title = $langs->trans("MenuTaxAccounts"); - $titlepicto = 'accountancy'; + $title = $langs->trans("MenuTaxAccounts"); + $titlepicto = 'accountancy'; } print load_fiche_titre($title, $linkback, $titlepicto); if (empty($id)) { - print ''.$langs->trans("DictionaryDesc"); - print " ".$langs->trans("OnlyActiveElementsAreShown")."
\n"; - print '

'; + print ''.$langs->trans("DictionaryDesc"); + print " ".$langs->trans("OnlyActiveElementsAreShown")."
\n"; + print '

'; } @@ -1020,7 +1020,7 @@ if (GETPOST('from')) $paramwithsearch .= '&from='.urlencode(GETPOST('from', 'alp // Confirmation of the deletion of the line if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'rowid='.urlencode($rowid).'&code='.urlencode($code).$paramwithsearch, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'rowid='.urlencode($rowid).'&code='.urlencode($code).$paramwithsearch, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_delete', '', 0, 1); } //var_dump($elementList); @@ -1029,126 +1029,126 @@ if ($action == 'delete') */ if ($id) { - // Complete search values request with sort criteria - $sql = $tabsql[$id]; + // Complete search values request with sort criteria + $sql = $tabsql[$id]; - if (!preg_match('/ WHERE /', $sql)) $sql .= " WHERE 1 = 1"; - if ($search_country_id > 0) $sql .= " AND c.rowid = ".$search_country_id; - if ($search_code != '' && $id == 9) $sql .= natural_search("code_iso", $search_code); - elseif ($search_code != '' && $id == 28) $sql .= natural_search("h.code", $search_code); - elseif ($search_code != '' && $id == 32) $sql .= natural_search("a.code", $search_code); - elseif ($search_code != '' && $id == 3) $sql .= natural_search("r.code_region", $search_code); - elseif ($search_code != '' && $id != 9) $sql .= natural_search("code", $search_code); + if (!preg_match('/ WHERE /', $sql)) $sql .= " WHERE 1 = 1"; + if ($search_country_id > 0) $sql .= " AND c.rowid = ".$search_country_id; + if ($search_code != '' && $id == 9) $sql .= natural_search("code_iso", $search_code); + elseif ($search_code != '' && $id == 28) $sql .= natural_search("h.code", $search_code); + elseif ($search_code != '' && $id == 32) $sql .= natural_search("a.code", $search_code); + elseif ($search_code != '' && $id == 3) $sql .= natural_search("r.code_region", $search_code); + elseif ($search_code != '' && $id != 9) $sql .= natural_search("code", $search_code); - if ($sortfield) - { - // If sort order is "country", we use country_code instead - if ($sortfield == 'country') $sortfield = 'country_code'; - $sql .= " ORDER BY ".$db->escape($sortfield); - if ($sortorder) - { - $sql .= " ".strtoupper($db->escape($sortorder)); - } - $sql .= ", "; - // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value - $tabsqlsort[$id] = preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i', '', $tabsqlsort[$id]); - $tabsqlsort[$id] = preg_replace('/([a-z]+\.)?'.$sortfield.',/i', '', $tabsqlsort[$id]); - } else { - $sql .= " ORDER BY "; - } - $sql .= $tabsqlsort[$id]; - $sql .= $db->plimit($listlimit + 1, $offset); - //print $sql; + if ($sortfield) + { + // If sort order is "country", we use country_code instead + if ($sortfield == 'country') $sortfield = 'country_code'; + $sql .= " ORDER BY ".$db->escape($sortfield); + if ($sortorder) + { + $sql .= " ".strtoupper($db->escape($sortorder)); + } + $sql .= ", "; + // Clear the required sort criteria for the tabsqlsort to be able to force it with selected value + $tabsqlsort[$id] = preg_replace('/([a-z]+\.)?'.$sortfield.' '.$sortorder.',/i', '', $tabsqlsort[$id]); + $tabsqlsort[$id] = preg_replace('/([a-z]+\.)?'.$sortfield.',/i', '', $tabsqlsort[$id]); + } else { + $sql .= " ORDER BY "; + } + $sql .= $tabsqlsort[$id]; + $sql .= $db->plimit($listlimit + 1, $offset); + //print $sql; - if (empty($tabfield[$id])) - { - dol_print_error($db, 'The table with id '.$id.' has no array tabfield defined'); - exit; - } - $fieldlist = explode(',', $tabfield[$id]); + if (empty($tabfield[$id])) + { + dol_print_error($db, 'The table with id '.$id.' has no array tabfield defined'); + exit; + } + $fieldlist = explode(',', $tabfield[$id]); - print '
'; - print ''; - print ''; + print ''; + print ''; + print ''; - if ($id == 10 && empty($conf->global->FACTURE_TVAOPTION)) - { - print info_admin($langs->trans("VATIsUsedIsOff", $langs->transnoentities("Setup"), $langs->transnoentities("CompanyFoundation"))); - print "
\n"; - } + if ($id == 10 && empty($conf->global->FACTURE_TVAOPTION)) + { + print info_admin($langs->trans("VATIsUsedIsOff", $langs->transnoentities("Setup"), $langs->transnoentities("CompanyFoundation"))); + print "
\n"; + } - // Form to add a new line - if ($tabname[$id]) - { - $alabelisused = 0; - $withentity = null; + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused = 0; + $withentity = null; - $fieldlist = explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); - print '
'; - print ''; + print '
'; + print '
'; - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { - if ($fieldlist[$field] == 'entity') { - $withentity = getEntity($tabname[$id]); - continue; - } + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + if ($fieldlist[$field] == 'entity') { + $withentity = getEntity($tabname[$id]); + continue; + } - // Define field friendly name from its technical name - $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow = $langs->trans($valuetoshow); // try to translate - $class = ''; + // Define field friendly name from its technical name + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + $class = ''; - if ($fieldlist[$field] == 'pos') { $valuetoshow = $langs->trans("Position"); $class = 'maxwidth100'; } - if ($fieldlist[$field] == 'source') { $valuetoshow = $langs->trans("Contact"); } - if ($fieldlist[$field] == 'price') { $valuetoshow = $langs->trans("PriceUHT"); } - if ($fieldlist[$field] == 'taux') { + if ($fieldlist[$field] == 'pos') { $valuetoshow = $langs->trans("Position"); $class = 'maxwidth100'; } + if ($fieldlist[$field] == 'source') { $valuetoshow = $langs->trans("Contact"); } + if ($fieldlist[$field] == 'price') { $valuetoshow = $langs->trans("PriceUHT"); } + if ($fieldlist[$field] == 'taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow = $langs->trans("Rate"); else $valuetoshow = $langs->trans("Amount"); $class = 'center'; - } - if ($fieldlist[$field] == 'localtax1_type') { $valuetoshow = $langs->trans("UseLocalTax")." 2"; $class = "center"; $sortable = 0; } - if ($fieldlist[$field] == 'localtax1') { $valuetoshow = $langs->trans("Rate")." 2"; $class = "center"; } - if ($fieldlist[$field] == 'localtax2_type') { $valuetoshow = $langs->trans("UseLocalTax")." 3"; $class = "center"; $sortable = 0; } - if ($fieldlist[$field] == 'localtax2') { $valuetoshow = $langs->trans("Rate")." 3"; $class = "center"; } - if ($fieldlist[$field] == 'organization') { $valuetoshow = $langs->trans("Organization"); } - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($fieldlist[$field] == 'type') { + } + if ($fieldlist[$field] == 'localtax1_type') { $valuetoshow = $langs->trans("UseLocalTax")." 2"; $class = "center"; $sortable = 0; } + if ($fieldlist[$field] == 'localtax1') { $valuetoshow = $langs->trans("Rate")." 2"; $class = "center"; } + if ($fieldlist[$field] == 'localtax2_type') { $valuetoshow = $langs->trans("UseLocalTax")." 3"; $class = "center"; $sortable = 0; } + if ($fieldlist[$field] == 'localtax2') { $valuetoshow = $langs->trans("Rate")." 3"; $class = "center"; } + if ($fieldlist[$field] == 'organization') { $valuetoshow = $langs->trans("Organization"); } + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } + if ($fieldlist[$field] == 'type') { if ($tabname[$id] == MAIN_DB_PREFIX."c_paiement") $valuetoshow = $form->textwithtooltip($langs->trans("Type"), $langs->trans("TypePaymentDesc"), 2, 1, img_help(1, '')); else $valuetoshow = $langs->trans("Type"); - } - if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); $class = 'maxwidth100'; } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') - { - $valuetoshow = $form->textwithtooltip($langs->trans("Label"), $langs->trans("LabelUsedByDefault"), 2, 1, img_help(1, '')); - } - if ($fieldlist[$field] == 'libelle_facture') { - $valuetoshow = $form->textwithtooltip($langs->trans("LabelOnDocuments"), $langs->trans("LabelUsedByDefault"), 2, 1, img_help(1, '')); - } - if ($fieldlist[$field] == 'country') { - if (in_array('region_id', $fieldlist)) { print ''; continue; } // For region page, we do not show the country input - $valuetoshow = $langs->trans("Country"); - } - if ($fieldlist[$field] == 'recuperableonly') { $valuetoshow = $langs->trans("NPR"); $class = "center"; } - if ($fieldlist[$field] == 'nbjour') { $valuetoshow = $langs->trans("NbOfDays"); } - if ($fieldlist[$field] == 'type_cdr') { $valuetoshow = $langs->trans("AtEndOfMonth"); $class = "center"; } - if ($fieldlist[$field] == 'decalage') { $valuetoshow = $langs->trans("Offset"); } - if ($fieldlist[$field] == 'width' || $fieldlist[$field] == 'nx') { $valuetoshow = $langs->trans("Width"); } - if ($fieldlist[$field] == 'height' || $fieldlist[$field] == 'ny') { $valuetoshow = $langs->trans("Height"); } - if ($fieldlist[$field] == 'unit' || $fieldlist[$field] == 'metric') { $valuetoshow = $langs->trans("MeasuringUnit"); } - if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $valuetoshow = ''; } - if ($fieldlist[$field] == 'accountancy_code') { $valuetoshow = $langs->trans("AccountancyCode"); } - if ($fieldlist[$field] == 'accountancy_code_sell') { $valuetoshow = $langs->trans("AccountancyCodeSell"); } - if ($fieldlist[$field] == 'accountancy_code_buy') { $valuetoshow = $langs->trans("AccountancyCodeBuy"); } - if ($fieldlist[$field] == 'pcg_version' || $fieldlist[$field] == 'fk_pcg_version') { $valuetoshow = $langs->trans("Pcg_version"); } - if ($fieldlist[$field] == 'account_parent') { $valuetoshow = $langs->trans("Accountparent"); } - if ($fieldlist[$field] == 'pcg_type') { $valuetoshow = $langs->trans("Pcg_type"); } - if ($fieldlist[$field] == 'pcg_subtype') { $valuetoshow = $langs->trans("Pcg_subtype"); } - if ($fieldlist[$field] == 'sortorder') { $valuetoshow = $langs->trans("SortOrder"); } - if ($fieldlist[$field] == 'short_label') { $valuetoshow = $langs->trans("ShortLabel"); } + } + if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); $class = 'maxwidth100'; } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') + { + $valuetoshow = $form->textwithtooltip($langs->trans("Label"), $langs->trans("LabelUsedByDefault"), 2, 1, img_help(1, '')); + } + if ($fieldlist[$field] == 'libelle_facture') { + $valuetoshow = $form->textwithtooltip($langs->trans("LabelOnDocuments"), $langs->trans("LabelUsedByDefault"), 2, 1, img_help(1, '')); + } + if ($fieldlist[$field] == 'country') { + if (in_array('region_id', $fieldlist)) { print ''; continue; } // For region page, we do not show the country input + $valuetoshow = $langs->trans("Country"); + } + if ($fieldlist[$field] == 'recuperableonly') { $valuetoshow = $langs->trans("NPR"); $class = "center"; } + if ($fieldlist[$field] == 'nbjour') { $valuetoshow = $langs->trans("NbOfDays"); } + if ($fieldlist[$field] == 'type_cdr') { $valuetoshow = $langs->trans("AtEndOfMonth"); $class = "center"; } + if ($fieldlist[$field] == 'decalage') { $valuetoshow = $langs->trans("Offset"); } + if ($fieldlist[$field] == 'width' || $fieldlist[$field] == 'nx') { $valuetoshow = $langs->trans("Width"); } + if ($fieldlist[$field] == 'height' || $fieldlist[$field] == 'ny') { $valuetoshow = $langs->trans("Height"); } + if ($fieldlist[$field] == 'unit' || $fieldlist[$field] == 'metric') { $valuetoshow = $langs->trans("MeasuringUnit"); } + if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $valuetoshow = ''; } + if ($fieldlist[$field] == 'accountancy_code') { $valuetoshow = $langs->trans("AccountancyCode"); } + if ($fieldlist[$field] == 'accountancy_code_sell') { $valuetoshow = $langs->trans("AccountancyCodeSell"); } + if ($fieldlist[$field] == 'accountancy_code_buy') { $valuetoshow = $langs->trans("AccountancyCodeBuy"); } + if ($fieldlist[$field] == 'pcg_version' || $fieldlist[$field] == 'fk_pcg_version') { $valuetoshow = $langs->trans("Pcg_version"); } + if ($fieldlist[$field] == 'account_parent') { $valuetoshow = $langs->trans("Accountparent"); } + if ($fieldlist[$field] == 'pcg_type') { $valuetoshow = $langs->trans("Pcg_type"); } + if ($fieldlist[$field] == 'pcg_subtype') { $valuetoshow = $langs->trans("Pcg_subtype"); } + if ($fieldlist[$field] == 'sortorder') { $valuetoshow = $langs->trans("SortOrder"); } + if ($fieldlist[$field] == 'short_label') { $valuetoshow = $langs->trans("ShortLabel"); } if ($fieldlist[$field] == 'range_account') { $valuetoshow = $langs->trans("Range"); } if ($fieldlist[$field] == 'sens') { $valuetoshow = $langs->trans("Sens"); } if ($fieldlist[$field] == 'category_type') { $valuetoshow = $langs->trans("Calculated"); } @@ -1172,197 +1172,197 @@ if ($id) if ($fieldlist[$field] == 'revenuestamp_type') { $valuetoshow = $langs->trans('TypeOfRevenueStamp'); } if ($fieldlist[$field] == 'use_default') { $valuetoshow = $langs->trans('Default'); } - if ($id == 2) // Special case for state page - { - if ($fieldlist[$field] == 'region_id') { $valuetoshow = ' '; $showfield = 1; } - if ($fieldlist[$field] == 'region') { $valuetoshow = $langs->trans("Country").'/'.$langs->trans("Region"); $showfield = 1; } - } + if ($id == 2) // Special case for state page + { + if ($fieldlist[$field] == 'region_id') { $valuetoshow = ' '; $showfield = 1; } + if ($fieldlist[$field] == 'region') { $valuetoshow = $langs->trans("Country").'/'.$langs->trans("Region"); $showfield = 1; } + } - if ($valuetoshow != '') - { - print ''; - if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; - elseif (!empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); - else print $valuetoshow; - print ''; - } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; - } + if ($valuetoshow != '') + { + print ''; + if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; + elseif (!empty($tabhelp[$id][$value])) print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); + else print $valuetoshow; + print ''; + } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; + } - if ($id == 4) print ''; - print ''; - print ''; - print ''; - print ''; + if ($id == 4) print ''; + print ''; + print ''; + print ''; + print ''; - // Line to enter new values - print ''; - print ''; + // Line to enter new values + print ''; + print ''; - $obj = new stdClass(); - // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val) != '') - $obj->$val = GETPOST($val); - } - } + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd')) + { + foreach ($fieldlist as $key=>$val) + { + if (GETPOST($val) != '') + $obj->$val = GETPOST($val); + } + } - $tmpaction = 'create'; - $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + $tmpaction = 'create'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('createDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; - if ($id == 3) unset($fieldlist[2]); // Remove field ??? if dictionary Regions + if ($id == 3) unset($fieldlist[2]); // Remove field ??? if dictionary Regions - if (empty($reshook)) - { - fieldList($fieldlist, $obj, $tabname[$id], 'add'); - } + if (empty($reshook)) + { + fieldList($fieldlist, $obj, $tabname[$id], 'add'); + } - if ($id == 4) print ''; - print ''; - print ""; + if ($id == 4) print ''; + print ''; + print ""; - $colspan = count($fieldlist) + 3; - if ($id == 4) $colspan++; + $colspan = count($fieldlist) + 3; + if ($id == 4) $colspan++; - print '
  '; - print ''; - if (!is_null($withentity)) - print ''; - print '
'; + print ''; + if (!is_null($withentity)) + print ''; + print '
'; - if ($action != 'edit') - { - print ''; - } - print '
'; + if ($action != 'edit') + { + print ''; + } + print '
'; + print ''; print '
'; - } + } - print '
'; + print ''; - print '
'; + print '
'; - print '
'; - print ''; - print ''; + print ''; + print ''; + print ''; - // List of available record in database - dol_syslog("htdocs/admin/dict", LOG_DEBUG); + // List of available record in database + dol_syslog("htdocs/admin/dict", LOG_DEBUG); - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; - // There is several pages - if ($num > $listlimit || $page) - { - print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); - print '
'; - } + // There is several pages + if ($num > $listlimit || $page) + { + print_fleche_navigation($page, $_SERVER["PHP_SELF"], $paramwithsearch, ($num > $listlimit), ''); + print '
'; + } - print '
'; - print ''; + print '
'; + print '
'; - // Title line with search input fields - print ''; - $filterfound = 0; - foreach ($fieldlist as $field => $value) - { - if ($fieldlist[$field] == 'entity') continue; + // Title line with search input fields + print ''; + $filterfound = 0; + foreach ($fieldlist as $field => $value) + { + if ($fieldlist[$field] == 'entity') continue; - $showfield = 1; // By default + $showfield = 1; // By default - if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; } + if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; } - if ($showfield) - { - if ($value == 'country') - { - print ''; - $filterfound++; - } elseif ($value == 'code') - { - print ''; - $filterfound++; - } else { - print ''; - } - } - } - if ($id == 4) print ''; - print ''; - print ''; - print ''; + if ($showfield) + { + if ($value == 'country') + { + print ''; + $filterfound++; + } elseif ($value == 'code') + { + print ''; + $filterfound++; + } else { + print ''; + } + } + } + if ($id == 4) print ''; + print ''; + print ''; + print ''; - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - if ($fieldlist[$field] == 'entity') continue; + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + if ($fieldlist[$field] == 'entity') continue; - // Determines the name of the field in relation to the possible names - // in data dictionaries - $showfield = 1; // By defaut - $cssprefix = ''; - $sortable = 1; - $valuetoshow = ucfirst($fieldlist[$field]); // By defaut - $valuetoshow = $langs->trans($valuetoshow); // try to translate + // Determines the name of the field in relation to the possible names + // in data dictionaries + $showfield = 1; // By defaut + $cssprefix = ''; + $sortable = 1; + $valuetoshow = ucfirst($fieldlist[$field]); // By defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate - // Special cases - if ($fieldlist[$field] == 'source') { $valuetoshow = $langs->trans("Contact"); } - if ($fieldlist[$field] == 'price') { $valuetoshow = $langs->trans("PriceUHT"); } - if ($fieldlist[$field] == 'taux') { + // Special cases + if ($fieldlist[$field] == 'source') { $valuetoshow = $langs->trans("Contact"); } + if ($fieldlist[$field] == 'price') { $valuetoshow = $langs->trans("PriceUHT"); } + if ($fieldlist[$field] == 'taux') { if ($tabname[$id] != MAIN_DB_PREFIX."c_revenuestamp") $valuetoshow = $langs->trans("Rate"); else $valuetoshow = $langs->trans("Amount"); $cssprefix = 'center '; - } - if ($fieldlist[$field] == 'localtax1_type') { $valuetoshow = $langs->trans("UseLocalTax")." 2"; $cssprefix = "center "; $sortable = 0; } - if ($fieldlist[$field] == 'localtax1') { $valuetoshow = $langs->trans("Rate")." 2"; $cssprefix = "center "; $sortable = 0; } - if ($fieldlist[$field] == 'localtax2_type') { $valuetoshow = $langs->trans("UseLocalTax")." 3"; $cssprefix = "center "; $sortable = 0; } - if ($fieldlist[$field] == 'localtax2') { $valuetoshow = $langs->trans("Rate")." 3"; $cssprefix = "center "; $sortable = 0; } - if ($fieldlist[$field] == 'organization') { $valuetoshow = $langs->trans("Organization"); } - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } - if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field] == 'position') { $cssprefix = 'right '; } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Label"); } - if ($fieldlist[$field] == 'libelle_facture') { $valuetoshow = $langs->trans("LabelOnDocuments"); } - if ($fieldlist[$field] == 'country') { $valuetoshow = $langs->trans("Country"); } - if ($fieldlist[$field] == 'recuperableonly') { $valuetoshow = $langs->trans("NPR"); $cssprefix = "center "; } - if ($fieldlist[$field] == 'nbjour') { $valuetoshow = $langs->trans("NbOfDays"); } - if ($fieldlist[$field] == 'type_cdr') { $valuetoshow = $langs->trans("AtEndOfMonth"); $cssprefix = "center "; } - if ($fieldlist[$field] == 'decalage') { $valuetoshow = $langs->trans("Offset"); } - if ($fieldlist[$field] == 'width' || $fieldlist[$field] == 'nx') { $valuetoshow = $langs->trans("Width"); } - if ($fieldlist[$field] == 'height' || $fieldlist[$field] == 'ny') { $valuetoshow = $langs->trans("Height"); } - if ($fieldlist[$field] == 'unit' || $fieldlist[$field] == 'metric') { $valuetoshow = $langs->trans("MeasuringUnit"); } - if ($fieldlist[$field] == 'accountancy_code') { $valuetoshow = $langs->trans("AccountancyCode"); } - if ($fieldlist[$field] == 'accountancy_code_sell') { $valuetoshow = $langs->trans("AccountancyCodeSell"); $sortable = 0; } - if ($fieldlist[$field] == 'accountancy_code_buy') { $valuetoshow = $langs->trans("AccountancyCodeBuy"); $sortable = 0; } + } + if ($fieldlist[$field] == 'localtax1_type') { $valuetoshow = $langs->trans("UseLocalTax")." 2"; $cssprefix = "center "; $sortable = 0; } + if ($fieldlist[$field] == 'localtax1') { $valuetoshow = $langs->trans("Rate")." 2"; $cssprefix = "center "; $sortable = 0; } + if ($fieldlist[$field] == 'localtax2_type') { $valuetoshow = $langs->trans("UseLocalTax")." 3"; $cssprefix = "center "; $sortable = 0; } + if ($fieldlist[$field] == 'localtax2') { $valuetoshow = $langs->trans("Rate")." 3"; $cssprefix = "center "; $sortable = 0; } + if ($fieldlist[$field] == 'organization') { $valuetoshow = $langs->trans("Organization"); } + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } + if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } + if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } + if ($fieldlist[$field] == 'position') { $cssprefix = 'right '; } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Label"); } + if ($fieldlist[$field] == 'libelle_facture') { $valuetoshow = $langs->trans("LabelOnDocuments"); } + if ($fieldlist[$field] == 'country') { $valuetoshow = $langs->trans("Country"); } + if ($fieldlist[$field] == 'recuperableonly') { $valuetoshow = $langs->trans("NPR"); $cssprefix = "center "; } + if ($fieldlist[$field] == 'nbjour') { $valuetoshow = $langs->trans("NbOfDays"); } + if ($fieldlist[$field] == 'type_cdr') { $valuetoshow = $langs->trans("AtEndOfMonth"); $cssprefix = "center "; } + if ($fieldlist[$field] == 'decalage') { $valuetoshow = $langs->trans("Offset"); } + if ($fieldlist[$field] == 'width' || $fieldlist[$field] == 'nx') { $valuetoshow = $langs->trans("Width"); } + if ($fieldlist[$field] == 'height' || $fieldlist[$field] == 'ny') { $valuetoshow = $langs->trans("Height"); } + if ($fieldlist[$field] == 'unit' || $fieldlist[$field] == 'metric') { $valuetoshow = $langs->trans("MeasuringUnit"); } + if ($fieldlist[$field] == 'accountancy_code') { $valuetoshow = $langs->trans("AccountancyCode"); } + if ($fieldlist[$field] == 'accountancy_code_sell') { $valuetoshow = $langs->trans("AccountancyCodeSell"); $sortable = 0; } + if ($fieldlist[$field] == 'accountancy_code_buy') { $valuetoshow = $langs->trans("AccountancyCodeBuy"); $sortable = 0; } if ($fieldlist[$field] == 'fk_pcg_version') { $valuetoshow = $langs->trans("Pcg_version"); } - if ($fieldlist[$field] == 'account_parent') { $valuetoshow = $langs->trans("Accountsparent"); } - if ($fieldlist[$field] == 'pcg_type') { $valuetoshow = $langs->trans("Pcg_type"); } - if ($fieldlist[$field] == 'pcg_subtype') { $valuetoshow = $langs->trans("Pcg_subtype"); } - if ($fieldlist[$field] == 'sortorder') { $valuetoshow = $langs->trans("SortOrder"); } - if ($fieldlist[$field] == 'short_label') { $valuetoshow = $langs->trans("ShortLabel"); } + if ($fieldlist[$field] == 'account_parent') { $valuetoshow = $langs->trans("Accountsparent"); } + if ($fieldlist[$field] == 'pcg_type') { $valuetoshow = $langs->trans("Pcg_type"); } + if ($fieldlist[$field] == 'pcg_subtype') { $valuetoshow = $langs->trans("Pcg_subtype"); } + if ($fieldlist[$field] == 'sortorder') { $valuetoshow = $langs->trans("SortOrder"); } + if ($fieldlist[$field] == 'short_label') { $valuetoshow = $langs->trans("ShortLabel"); } if ($fieldlist[$field] == 'range_account') { $valuetoshow = $langs->trans("Range"); } if ($fieldlist[$field] == 'sens') { $valuetoshow = $langs->trans("Sens"); } if ($fieldlist[$field] == 'category_type') { $valuetoshow = $langs->trans("Calculated"); } @@ -1388,198 +1388,198 @@ if ($id) if ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; } - // Show field title - if ($showfield) - { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, $cssprefix); - } - } + // Show field title + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), $param, '', $sortfield, $sortorder, $cssprefix); + } + } // Favorite - Only activated on country dictionary - if ($id == 4) print getTitleFieldOfList($langs->trans("Favorite"), 0, $_SERVER["PHP_SELF"], "favorite", ($page ? 'page='.$page.'&' : ''), $param, 'align="center"', $sortfield, $sortorder); + if ($id == 4) print getTitleFieldOfList($langs->trans("Favorite"), 0, $_SERVER["PHP_SELF"], "favorite", ($page ? 'page='.$page.'&' : ''), $param, 'align="center"', $sortfield, $sortorder); print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "active", ($page ? 'page='.$page.'&' : ''), $param, 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; - if ($num) - { - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); - //print_r($obj); - print ''; - if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) - { - $tmpaction = 'edit'; - $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + if ($num) + { + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) + { + $tmpaction = 'edit'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('editDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; - // Show fields - if (empty($reshook)) { - $withentity = fieldList($fieldlist, $obj, $tabname[$id], 'edit'); - } + // Show fields + if (empty($reshook)) { + $withentity = fieldList($fieldlist, $obj, $tabname[$id], 'edit'); + } - print ''; - } else { - $tmpaction = 'view'; - $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + print ''; + } else { + $tmpaction = 'view'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('viewDictionaryFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) - { - $withentity = null; + if (empty($reshook)) + { + $withentity = null; - foreach ($fieldlist as $field => $value) - { - //var_dump($fieldlist); - $class = ''; - $showfield = 1; - $valuetoshow = $obj->{$fieldlist[$field]}; + foreach ($fieldlist as $field => $value) + { + //var_dump($fieldlist); + $class = ''; + $showfield = 1; + $valuetoshow = $obj->{$fieldlist[$field]}; - if ($fieldlist[$field] == 'entity') { - $withentity = $valuetoshow; - continue; - } + if ($fieldlist[$field] == 'entity') { + $withentity = $valuetoshow; + continue; + } - if ($value == 'element') - { - $valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow; - } elseif ($value == 'source') - { - $valuetoshow = isset($sourceList[$valuetoshow]) ? $sourceList[$valuetoshow] : $valuetoshow; - } elseif ($valuetoshow == 'all') { - $valuetoshow = $langs->trans('All'); - } elseif ($fieldlist[$field] == 'country') { - if (empty($obj->country_code)) - { - $valuetoshow = '-'; - } else { - $key = $langs->trans("Country".strtoupper($obj->country_code)); - $valuetoshow = ($key != "Country".strtoupper($obj->country_code) ? $obj->country_code." - ".$key : $obj->country); - } - } elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - $valuetoshow = yn($valuetoshow); - $class = "center"; - } elseif ($fieldlist[$field] == 'type_cdr') { - if (empty($valuetoshow)) $valuetoshow = $langs->trans('None'); - elseif ($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); - elseif ($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); - $class = "center"; - } elseif ($fieldlist[$field] == 'price' || preg_match('/^amount/i', $fieldlist[$field])) { - $valuetoshow = price($valuetoshow); - } - if ($value == 'private') - { - $valuetoshow = yn($elementList[$valuetoshow]); - } elseif ($fieldlist[$field] == 'libelle_facture') { - $langs->load("bills"); - $key = $langs->trans("PaymentCondition".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "PaymentCondition".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - $valuetoshow = nl2br($valuetoshow); - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_country') { - $key = $langs->trans("Country".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "Country".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_availability') { - $langs->load("propal"); - $key = $langs->trans("AvailabilityType".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "AvailabilityType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_actioncomm') { - $key = $langs->trans("Action".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "Action".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif (!empty($obj->code_iso) && $fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_currencies') { - $key = $langs->trans("Currency".strtoupper($obj->code_iso)); - $valuetoshow = ($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_typent') { - $key = $langs->trans(strtoupper($obj->code)); - $valuetoshow = ($key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_prospectlevel') { - $key = $langs->trans(strtoupper($obj->code)); - $valuetoshow = ($key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_civility') { - $key = $langs->trans("Civility".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "Civility".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_contact') { - $langs->load('agenda'); - $key = $langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_payment_term') { - $langs->load("bills"); - $key = $langs->trans("PaymentConditionShort".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_paiement') { - $langs->load("bills"); - $key = $langs->trans("PaymentType".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "PaymentType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'type' && $tabname[$id] == MAIN_DB_PREFIX.'c_paiement') { - $payment_type_list = array(0=>$langs->trans('PaymentTypeCustomer'), 1=>$langs->trans('PaymentTypeSupplier'), 2=>$langs->trans('PaymentTypeBoth')); - $valuetoshow = $payment_type_list[$valuetoshow]; - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_input_reason') { - $key = $langs->trans("DemandReasonType".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "DemandReasonType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_input_method') { - $langs->load("orders"); - $key = $langs->trans($obj->code); - $valuetoshow = ($obj->code && $key != $obj->code) ? $key : $obj->{$fieldlist[$field]}; - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_shipment_mode') { - $langs->load("sendings"); - $key = $langs->trans("SendingMethod".strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != "SendingMethod".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_paper_format') - { - $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') - { - $langs->load('trips'); - $key = $langs->trans(strtoupper($obj->code)); - $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { - $showfield = 0; - } elseif ($fieldlist[$field] == 'unicode') { - $valuetoshow = $langs->getCurrencySymbol($obj->code, 1); - } elseif ($fieldlist[$field] == 'label' && $tabname[$_GET["id"]] == MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'short_label' && $tabname[$_GET["id"]] == MAIN_DB_PREFIX.'c_units') { - $langs->load("products"); - $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); - } elseif (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) - { - $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); - $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); - } elseif ($fieldlist[$field] == 'localtax1' || $fieldlist[$field] == 'localtax2') { - $class = "center"; + if ($value == 'element') + { + $valuetoshow = isset($elementList[$valuetoshow]) ? $elementList[$valuetoshow] : $valuetoshow; + } elseif ($value == 'source') + { + $valuetoshow = isset($sourceList[$valuetoshow]) ? $sourceList[$valuetoshow] : $valuetoshow; + } elseif ($valuetoshow == 'all') { + $valuetoshow = $langs->trans('All'); + } elseif ($fieldlist[$field] == 'country') { + if (empty($obj->country_code)) + { + $valuetoshow = '-'; + } else { + $key = $langs->trans("Country".strtoupper($obj->country_code)); + $valuetoshow = ($key != "Country".strtoupper($obj->country_code) ? $obj->country_code." - ".$key : $obj->country); + } + } elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { + $valuetoshow = yn($valuetoshow); + $class = "center"; + } elseif ($fieldlist[$field] == 'type_cdr') { + if (empty($valuetoshow)) $valuetoshow = $langs->trans('None'); + elseif ($valuetoshow == 1) $valuetoshow = $langs->trans('AtEndOfMonth'); + elseif ($valuetoshow == 2) $valuetoshow = $langs->trans('CurrentNext'); + $class = "center"; + } elseif ($fieldlist[$field] == 'price' || preg_match('/^amount/i', $fieldlist[$field])) { + $valuetoshow = price($valuetoshow); + } + if ($value == 'private') + { + $valuetoshow = yn($elementList[$valuetoshow]); + } elseif ($fieldlist[$field] == 'libelle_facture') { + $langs->load("bills"); + $key = $langs->trans("PaymentCondition".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "PaymentCondition".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + $valuetoshow = nl2br($valuetoshow); + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_country') { + $key = $langs->trans("Country".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "Country".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_availability') { + $langs->load("propal"); + $key = $langs->trans("AvailabilityType".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "AvailabilityType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_actioncomm') { + $key = $langs->trans("Action".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "Action".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif (!empty($obj->code_iso) && $fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_currencies') { + $key = $langs->trans("Currency".strtoupper($obj->code_iso)); + $valuetoshow = ($obj->code_iso && $key != "Currency".strtoupper($obj->code_iso) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_typent') { + $key = $langs->trans(strtoupper($obj->code)); + $valuetoshow = ($key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_prospectlevel') { + $key = $langs->trans(strtoupper($obj->code)); + $valuetoshow = ($key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_civility') { + $key = $langs->trans("Civility".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "Civility".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_contact') { + $langs->load('agenda'); + $key = $langs->trans("TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "TypeContact_".$obj->element."_".$obj->source."_".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_payment_term') { + $langs->load("bills"); + $key = $langs->trans("PaymentConditionShort".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "PaymentConditionShort".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_paiement') { + $langs->load("bills"); + $key = $langs->trans("PaymentType".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "PaymentType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'type' && $tabname[$id] == MAIN_DB_PREFIX.'c_paiement') { + $payment_type_list = array(0=>$langs->trans('PaymentTypeCustomer'), 1=>$langs->trans('PaymentTypeSupplier'), 2=>$langs->trans('PaymentTypeBoth')); + $valuetoshow = $payment_type_list[$valuetoshow]; + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_input_reason') { + $key = $langs->trans("DemandReasonType".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "DemandReasonType".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_input_method') { + $langs->load("orders"); + $key = $langs->trans($obj->code); + $valuetoshow = ($obj->code && $key != $obj->code) ? $key : $obj->{$fieldlist[$field]}; + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_shipment_mode') { + $langs->load("sendings"); + $key = $langs->trans("SendingMethod".strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != "SendingMethod".strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'libelle' && $tabname[$id] == MAIN_DB_PREFIX.'c_paper_format') + { + $key = $langs->trans('PaperFormat'.strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != 'PaperFormat'.strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'label' && $tabname[$id] == MAIN_DB_PREFIX.'c_type_fees') + { + $langs->load('trips'); + $key = $langs->trans(strtoupper($obj->code)); + $valuetoshow = ($obj->code && $key != strtoupper($obj->code) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { + $showfield = 0; + } elseif ($fieldlist[$field] == 'unicode') { + $valuetoshow = $langs->getCurrencySymbol($obj->code, 1); + } elseif ($fieldlist[$field] == 'label' && $tabname[$_GET["id"]] == MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'short_label' && $tabname[$_GET["id"]] == MAIN_DB_PREFIX.'c_units') { + $langs->load("products"); + $valuetoshow = $langs->trans($obj->{$fieldlist[$field]}); + } elseif (($fieldlist[$field] == 'unit') && ($tabname[$id] == MAIN_DB_PREFIX.'c_paper_format')) + { + $key = $langs->trans('SizeUnit'.strtolower($obj->unit)); + $valuetoshow = ($obj->code && $key != 'SizeUnit'.strtolower($obj->unit) ? $key : $obj->{$fieldlist[$field]}); + } elseif ($fieldlist[$field] == 'localtax1' || $fieldlist[$field] == 'localtax2') { + $class = "center"; } elseif ($fieldlist[$field] == 'localtax1_type') { - if ($obj->localtax1 != 0) - $valuetoshow = $localtax_typeList[$valuetoshow]; - else $valuetoshow = ''; - $class = "center"; + if ($obj->localtax1 != 0) + $valuetoshow = $localtax_typeList[$valuetoshow]; + else $valuetoshow = ''; + $class = "center"; } elseif ($fieldlist[$field] == 'localtax2_type') { - if ($obj->localtax2 != 0) - $valuetoshow = $localtax_typeList[$valuetoshow]; - else $valuetoshow = ''; - $class = "center"; + if ($obj->localtax2 != 0) + $valuetoshow = $localtax_typeList[$valuetoshow]; + else $valuetoshow = ''; + $class = "center"; } elseif ($fieldlist[$field] == 'taux') { - $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); - $class = "center"; + $valuetoshow = price($valuetoshow, 0, $langs, 0, 0); + $class = "center"; } elseif (in_array($fieldlist[$field], array('recuperableonly'))) { $class = "center"; } elseif ($fieldlist[$field] == 'accountancy_code' || $fieldlist[$field] == 'accountancy_code_sell' || $fieldlist[$field] == 'accountancy_code_buy') { - $valuetoshow = length_accountg($valuetoshow); - } elseif ($fieldlist[$field] == 'fk_tva') + $valuetoshow = length_accountg($valuetoshow); + } elseif ($fieldlist[$field] == 'fk_tva') { foreach ($form->cache_vatrates as $key => $Tab) { @@ -1604,49 +1604,49 @@ if ($id) } elseif ($fieldlist[$field] == 'code' && $id == 3) { $valuetoshow = $obj->state_code; } - $class .= ($class ? ' ' : '').'tddict'; - if ($fieldlist[$field] == 'note' && $id == 10) $class .= ' tdoverflowmax200'; - if ($fieldlist[$field] == 'tracking') $class .= ' tdoverflowauto'; - if ($fieldlist[$field] == 'position') $class .= ' right'; - if ($fieldlist[$field] == 'localtax1_type') $class .= ' nowrap'; - if ($fieldlist[$field] == 'localtax2_type') $class .= ' nowrap'; - // Show value for field + $class .= ($class ? ' ' : '').'tddict'; + if ($fieldlist[$field] == 'note' && $id == 10) $class .= ' tdoverflowmax200'; + if ($fieldlist[$field] == 'tracking') $class .= ' tdoverflowauto'; + if ($fieldlist[$field] == 'position') $class .= ' right'; + if ($fieldlist[$field] == 'localtax1_type') $class .= ' nowrap'; + if ($fieldlist[$field] == 'localtax2_type') $class .= ' nowrap'; + // Show value for field if ($showfield) print ''; - } - } + } + } - // Can an entry be erased or disabled ? - // all true by default - $iserasable = 1; - $canbedisabled = 1; - $canbemodified = 1; - if (isset($obj->code) && $id != 10) - { - if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i', $obj->code))) { $iserasable = 0; $canbedisabled = 0; } elseif ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } elseif ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } - } + // Can an entry be erased or disabled ? + // all true by default + $iserasable = 1; + $canbedisabled = 1; + $canbemodified = 1; + if (isset($obj->code) && $id != 10) + { + if (($obj->code == '0' || $obj->code == '' || preg_match('/unknown/i', $obj->code))) { $iserasable = 0; $canbedisabled = 0; } elseif ($obj->code == 'RECEP') { $iserasable = 0; $canbedisabled = 0; } elseif ($obj->code == 'EF0') { $iserasable = 0; $canbedisabled = 0; } + } if ($id == 25 && in_array($obj->code, array('banner', 'blogpost', 'other', 'page'))) { $iserasable = 0; $canbedisabled = 0; if (in_array($obj->code, array('banner'))) $canbedisabled = 1; } - if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable = 0; } - if (in_array($obj->code, array('AC_OTH', 'AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled = 0; $canbedisabled = 0; } - $canbemodified = $iserasable; - if ($obj->code == 'RECEP') $canbemodified = 1; - if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm") $canbemodified = 1; + if (isset($obj->type) && in_array($obj->type, array('system', 'systemauto'))) { $iserasable = 0; } + if (in_array($obj->code, array('AC_OTH', 'AC_OTH_AUTO')) || in_array($obj->type, array('systemauto'))) { $canbedisabled = 0; $canbedisabled = 0; } + $canbemodified = $iserasable; + if ($obj->code == 'RECEP') $canbemodified = 1; + if ($tabname[$id] == MAIN_DB_PREFIX."c_actioncomm") $canbemodified = 1; - // Build Url. The table is id=, the id of line is rowid= - $rowidcol = $tabrowid[$id]; - // If rowidcol not defined - if (empty($rowidcol) || in_array($id, array(6, 7, 8, 13, 17, 19, 27, 32))) $rowidcol = 'rowid'; - $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.((!empty($obj->{$rowidcol}) || $obj->{$rowidcol} == '0') ? $obj->{$rowidcol}:(!empty($obj->code) ?urlencode($obj->code) : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : ''); - if (!empty($param)) $url .= '&'.$param; - if (!is_null($withentity)) $url .= '&entity='.$withentity; - $url .= '&'; + // Build Url. The table is id=, the id of line is rowid= + $rowidcol = $tabrowid[$id]; + // If rowidcol not defined + if (empty($rowidcol) || in_array($id, array(6, 7, 8, 13, 17, 19, 27, 32))) $rowidcol = 'rowid'; + $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.((!empty($obj->{$rowidcol}) || $obj->{$rowidcol} == '0') ? $obj->{$rowidcol}:(!empty($obj->code) ?urlencode($obj->code) : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : ''); + if (!empty($param)) $url .= '&'.$param; + if (!is_null($withentity)) $url .= '&entity='.$withentity; + $url .= '&'; // Favorite // Only activated on country dictionary - if ($id == 4) + if ($id == 4) { print ''; } - // Active - print '"; + // Active + print '"; - // Modify link - if ($canbemodified) print ''; - else print ''; + // Modify link + if ($canbemodified) print ''; + else print ''; - // Delete link - if ($iserasable) - { - print ''; - } else print ''; + // Delete link + if ($iserasable) + { + print ''; + } else print ''; - print "\n"; - } - $i++; - } - } + print "\n"; + } + $i++; + } + } - print '
'; - print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth150 maxwidthonsmartphone'); - print ''; - print ''; - print ''; - print ''; - if ($filterfound) - { - $searchpicto = $form->showFilterAndCheckAddButtons(0); - print $searchpicto; - } - print '
'; + print $form->select_country($search_country_id, 'search_country_id', '', 28, 'maxwidth150 maxwidthonsmartphone'); + print ''; + print ''; + print ''; + print ''; + if ($filterfound) + { + $searchpicto = $form->showFilterAndCheckAddButtons(0); + print $searchpicto; + } + print '
'; - print '
'; - print ''; - print ''; - if (!is_null($withentity)) - print ''; - print ''; - print ''; - print '
'; + print '
'; + print ''; + print ''; + if (!is_null($withentity)) + print ''; + print ''; + print ''; + print '
'.$valuetoshow.''; if ($iserasable) print ''.$actl[$obj->favorite].''; @@ -1654,98 +1654,98 @@ if ($id) print ''; - if ($canbedisabled) print ''.$actl[$obj->active].''; - else { - if (in_array($obj->code, array('AC_OTH', 'AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); - elseif (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); - elseif (isset($obj->type) && in_array($obj->type, array('system')) && !empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); - else print $langs->trans("AlwaysActive"); - } - print "'; + if ($canbedisabled) print ''.$actl[$obj->active].''; + else { + if (in_array($obj->code, array('AC_OTH', 'AC_OTH_AUTO'))) print $langs->trans("AlwaysActive"); + elseif (isset($obj->type) && in_array($obj->type, array('systemauto')) && empty($obj->active)) print $langs->trans("Deprecated"); + elseif (isset($obj->type) && in_array($obj->type, array('system')) && !empty($obj->active) && $obj->code != 'AC_OTH') print $langs->trans("UsedOnlyWithTypeOption"); + else print $langs->trans("AlwaysActive"); + } + print "'.img_edit().' '.img_edit().' '; - if ($user->admin) print ''.img_delete().''; - //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin - print ' '; + if ($user->admin) print ''.img_delete().''; + //else print ''.img_delete().''; // Some dictionary can be edited by other profile than admin + print ' 
'; - print '
'; - } else { - dol_print_error($db); - } + print ''; + print '
'; + } else { + dol_print_error($db); + } - print ''; + print ''; } else { - /* + /* * Show list of dictionary to show */ - $lastlineisempty = false; + $lastlineisempty = false; print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; + print '
'.$langs->trans("Dictionary").''.$langs->trans("Table").'
'; + print ''; + print ''; + print ''; + print ''; - $showemptyline = ''; - foreach ($taborder as $i) - { - if (isset($tabname[$i]) && empty($tabcond[$i])) continue; + $showemptyline = ''; + foreach ($taborder as $i) + { + if (isset($tabname[$i]) && empty($tabcond[$i])) continue; - if ($i) - { - if ($showemptyline) - { - print ''; - $showemptyline = 0; - } + if ($i) + { + if ($showemptyline) + { + print ''; + $showemptyline = 0; + } - $value = $tabname[$i]; - print ''; - print ''; + print ''; - print ''; - $lastlineisempty = false; - } else { - if (!$lastlineisempty) - { - $showemptyline = 1; - $lastlineisempty = true; - } - } - } - print '
'.$langs->trans("Dictionary").''.$langs->trans("Table").'
   
   
'; - if (!empty($tabcond[$i])) - { - print ''.$langs->trans($tablib[$i]).''; - } else { - print $langs->trans($tablib[$i]); - } - print ''; - /*if (empty($tabcond[$i])) + $value = $tabname[$i]; + print '
'; + if (!empty($tabcond[$i])) + { + print ''.$langs->trans($tablib[$i]).''; + } else { + print $langs->trans($tablib[$i]); + } + print ''; + /*if (empty($tabcond[$i])) { print info_admin($langs->trans("DictionaryDisabledSinceNoModuleNeedIt"),1); }*/ - print ''.$tabname[$i].'
'; - print '
'; + print ''; + print ''.$tabname[$i].''; + $lastlineisempty = false; + } else { + if (!$lastlineisempty) + { + $showemptyline = 1; + $lastlineisempty = true; + } + } + } + print ''; + print ''; } print '
'; @@ -1784,14 +1784,14 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') continue; } - if (in_array($fieldlist[$field], array('code', 'libelle', 'type')) && $tabname == MAIN_DB_PREFIX."c_actioncomm" && in_array($obj->type, array('system', 'systemauto'))) - { - $hidden = (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''); - print ''; - print ''; - print $langs->trans($hidden); - print ''; - } elseif ($fieldlist[$field] == 'country') + if (in_array($fieldlist[$field], array('code', 'libelle', 'type')) && $tabname == MAIN_DB_PREFIX."c_actioncomm" && in_array($obj->type, array('system', 'systemauto'))) + { + $hidden = (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''); + print ''; + print ''; + print $langs->trans($hidden); + print ''; + } elseif ($fieldlist[$field] == 'country') { if (in_array('region_id', $fieldlist)) { @@ -1860,8 +1860,8 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') print $form->selectarray($fieldlist[$field], $select_list, (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'2')); print ''; } elseif ($fieldlist[$field] == 'recuperableonly' || $fieldlist[$field] == 'type_cdr' || $fieldlist[$field] == 'deductible' || $fieldlist[$field] == 'category_type') { - if ($fieldlist[$field] == 'type_cdr') print ''; - else print ''; + if ($fieldlist[$field] == 'type_cdr') print ''; + else print ''; if ($fieldlist[$field] == 'type_cdr') { print $form->selectarray($fieldlist[$field], array(0=>$langs->trans('None'), 1=>$langs->trans('AtEndOfMonth'), 2=>$langs->trans('CurrentNext')), (!empty($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:'')); } else { @@ -1875,27 +1875,27 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') print ''; print ''; } elseif (in_array($fieldlist[$field], array('libelle_facture'))) { - print ''; - $transfound = 0; - $transkey = ''; - // Special case for labels - if ($tabname == MAIN_DB_PREFIX.'c_payment_term') - { - $langs->load("bills"); - $transkey = "PaymentCondition".strtoupper($obj->code); - if ($langs->trans($transkey) != $transkey) - { - $transfound = 1; - print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis")); - } - } - if (!$transfound) - { - print ''; - } else { - print ''; - } - print ''; + print ''; + $transfound = 0; + $transkey = ''; + // Special case for labels + if ($tabname == MAIN_DB_PREFIX.'c_payment_term') + { + $langs->load("bills"); + $transkey = "PaymentCondition".strtoupper($obj->code); + if ($langs->trans($transkey) != $transkey) + { + $transfound = 1; + print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis")); + } + } + if (!$transfound) + { + print ''; + } else { + print ''; + } + print ''; } elseif ($fieldlist[$field] == 'price' || preg_match('/^amount/i', $fieldlist[$field])) { print ''; } elseif ($fieldlist[$field] == 'code' && isset($obj->{$fieldlist[$field]})) { @@ -1922,12 +1922,12 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') print ''; if (!empty($conf->accounting->enabled)) { - $fieldname = $fieldlist[$field]; + $fieldname = $fieldlist[$field]; $accountancy_account = (!empty($obj->$fieldname) ? $obj->$fieldname : 0); print $formaccounting->select_account($accountancy_account, '.'.$fieldlist[$field], 1, '', 1, 1, 'maxwidth200 maxwidthonsmartphone'); } else { - $fieldname = $fieldlist[$field]; - print ''; + $fieldname = $fieldlist[$field]; + print ''; } print ''; } elseif ($fieldlist[$field] == 'fk_tva') @@ -1946,12 +1946,12 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') print $form->selectExpenseRanges($obj->fk_range); print ''; } else { - $fieldValue = isset($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''; + $fieldValue = isset($obj->{$fieldlist[$field]}) ? $obj->{$fieldlist[$field]}:''; if ($fieldlist[$field] == 'sortorder') - { - $fieldlist[$field] = 'position'; - } + { + $fieldlist[$field] = 'position'; + } $classtd = ''; $class = ''; if ($fieldlist[$field] == 'code') $class = 'maxwidth100'; @@ -1959,29 +1959,29 @@ function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') if (in_array($fieldlist[$field], array('libelle', 'label', 'tracking'))) $class = 'quatrevingtpercent'; print ''; $transfound = 0; - $transkey = ''; + $transkey = ''; if (in_array($fieldlist[$field], array('label', 'libelle'))) // For label { - // Special case for labels - if ($tabname == MAIN_DB_PREFIX.'c_civility') { - $transkey = "Civility".strtoupper($obj->code); - } - if ($tabname == MAIN_DB_PREFIX.'c_payment_term') { - $langs->load("bills"); - $transkey = "PaymentConditionShort".strtoupper($obj->code); - } - if ($transkey && $langs->trans($transkey) != $transkey) - { - $transfound = 1; - print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis")); - } + // Special case for labels + if ($tabname == MAIN_DB_PREFIX.'c_civility') { + $transkey = "Civility".strtoupper($obj->code); + } + if ($tabname == MAIN_DB_PREFIX.'c_payment_term') { + $langs->load("bills"); + $transkey = "PaymentConditionShort".strtoupper($obj->code); + } + if ($transkey && $langs->trans($transkey) != $transkey) + { + $transfound = 1; + print $form->textwithpicto($langs->trans($transkey), $langs->trans("GoIntoTranslationMenuToChangeThis")); + } } if (!$transfound) { - print ''; + print ''; } else { - print ''; - } + print ''; + } print ''; } } diff --git a/htdocs/admin/ecm_directories_extrafields.php b/htdocs/admin/ecm_directories_extrafields.php index 71029c0fc67..77e21963e4c 100644 --- a/htdocs/admin/ecm_directories_extrafields.php +++ b/htdocs/admin/ecm_directories_extrafields.php @@ -34,7 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!$user->admin) - accessforbidden(); + accessforbidden(); // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'ecm')); @@ -89,9 +89,9 @@ dol_fiche_end(); // Buttons if ($action != 'create' && $action != 'edit') { - print '
'; - print "".$langs->trans("NewAttribute").""; - print "
"; + print '
'; + print "".$langs->trans("NewAttribute").""; + print "
"; } @@ -102,9 +102,9 @@ if ($action != 'create' && $action != 'edit') { /* ************************************************************************** */ if ($action == 'create') { - print '
'; - print load_fiche_titre($langs->trans('NewAttribute')); - require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; + print '
'; + print load_fiche_titre($langs->trans('NewAttribute')); + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; } /* ************************************************************************** */ @@ -113,9 +113,9 @@ if ($action == 'create') { /* */ /* ************************************************************************** */ if ($action == 'edit' && !empty($attrname)) { - print "
"; - print load_fiche_titre($langs->trans("FieldEdition", $attrname)); - require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; + print "
"; + print load_fiche_titre($langs->trans("FieldEdition", $attrname)); + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; } // End of page diff --git a/htdocs/admin/ecm_files_extrafields.php b/htdocs/admin/ecm_files_extrafields.php index 9d747d4f684..aaa507ca7c4 100644 --- a/htdocs/admin/ecm_files_extrafields.php +++ b/htdocs/admin/ecm_files_extrafields.php @@ -34,7 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; if (!$user->admin) - accessforbidden(); + accessforbidden(); // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'ecm')); @@ -89,9 +89,9 @@ dol_fiche_end(); // Buttons if ($action != 'create' && $action != 'edit') { - print '
'; - print "".$langs->trans("NewAttribute").""; - print "
"; + print '
'; + print "".$langs->trans("NewAttribute").""; + print "
"; } @@ -102,9 +102,9 @@ if ($action != 'create' && $action != 'edit') { /* ************************************************************************** */ if ($action == 'create') { - print '
'; - print load_fiche_titre($langs->trans('NewAttribute')); - require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; + print '
'; + print load_fiche_titre($langs->trans('NewAttribute')); + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_add.tpl.php'; } /* ************************************************************************** */ @@ -113,9 +113,9 @@ if ($action == 'create') { /* */ /* ************************************************************************** */ if ($action == 'edit' && !empty($attrname)) { - print "
"; - print load_fiche_titre($langs->trans("FieldEdition", $attrname)); - require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; + print "
"; + print load_fiche_titre($langs->trans("FieldEdition", $attrname)); + require DOL_DOCUMENT_ROOT.'/core/tpl/admin_extrafields_edit.tpl.php'; } // End of page diff --git a/htdocs/admin/menus/index.php b/htdocs/admin/menus/index.php index b7b0060c778..f83507c37aa 100644 --- a/htdocs/admin/menus/index.php +++ b/htdocs/admin/menus/index.php @@ -330,10 +330,10 @@ if ($conf->use_javascript_ajax) $entry .= ''; $buttons = ''.img_edit('default', 0, 'class="menuEdit" id="edit'.$menu['rowid'].'"').' '; - $buttons .= ''.img_edit_add('default').' '; - $buttons .= ''.img_delete('default').' '; - $buttons .= '     '; - $buttons .= ''.img_picto("Up", "1uparrow").''.img_picto("Down", "1downarrow").''; + $buttons .= ''.img_edit_add('default').' '; + $buttons .= ''.img_delete('default').' '; + $buttons .= '     '; + $buttons .= ''.img_picto("Up", "1uparrow").''.img_picto("Down", "1downarrow").''; $data[] = array( 'rowid'=>$menu['rowid'], diff --git a/htdocs/admin/oauthlogintokens.php b/htdocs/admin/oauthlogintokens.php index 2d843a52577..2c8f2070724 100644 --- a/htdocs/admin/oauthlogintokens.php +++ b/htdocs/admin/oauthlogintokens.php @@ -58,50 +58,50 @@ if (!$mode) $mode = 'setup'; if ($action == 'setconst' && $user->admin) { - $error = 0; - $db->begin(); + $error = 0; + $db->begin(); - $setupconstarray = GETPOST('setupdriver', 'array'); + $setupconstarray = GETPOST('setupdriver', 'array'); - foreach ($setupconstarray as $setupconst) { - //print '
'.print_r($setupconst, true).'
'; + foreach ($setupconstarray as $setupconst) { + //print '
'.print_r($setupconst, true).'
'; - $constname = dol_escape_htmltag($setupconst['varname']); - $constvalue = dol_escape_htmltag($setupconst['value']); - $consttype = dol_escape_htmltag($setupconst['type']); - $constnote = dol_escape_htmltag($setupconst['note']); + $constname = dol_escape_htmltag($setupconst['varname']); + $constvalue = dol_escape_htmltag($setupconst['value']); + $consttype = dol_escape_htmltag($setupconst['type']); + $constnote = dol_escape_htmltag($setupconst['note']); - $result = dolibarr_set_const($db, $constname, $constvalue, $consttype, 0, $constnote, $conf->entity); - if (!$result > 0) $error++; - } + $result = dolibarr_set_const($db, $constname, $constvalue, $consttype, 0, $constnote, $conf->entity); + if (!$result > 0) $error++; + } - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null); - } else { - $db->rollback(); - dol_print_error($db); - } - $action = ''; + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null); + } else { + $db->rollback(); + dol_print_error($db); + } + $action = ''; } if ($action == 'setvalue' && $user->admin) { - $db->begin(); + $db->begin(); - $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); - if (!$result > 0) $error++; + $result = dolibarr_set_const($db, $varname, $value, 'chaine', 0, '', $conf->entity); + if (!$result > 0) $error++; - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("SetupSaved"), null); - } else { - $db->rollback(); - dol_print_error($db); - } - $action = ''; + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("SetupSaved"), null); + } else { + $db->rollback(); + dol_print_error($db); + } + $action = ''; } @@ -131,275 +131,275 @@ if (GETPOST('error')) { if ($mode == 'setup' && $user->admin) { - print ''.$langs->trans("OAuthSetupForLogin")."

\n"; + print ''.$langs->trans("OAuthSetupForLogin")."

\n"; - foreach ($list as $key) - { - $supported = 0; - if (in_array($key[0], array_keys($supportedoauth2array))) $supported = 1; - if (!$supported) continue; // show only supported + foreach ($list as $key) + { + $supported = 0; + if (in_array($key[0], array_keys($supportedoauth2array))) $supported = 1; + if (!$supported) continue; // show only supported - $OAUTH_SERVICENAME = 'Unknown'; - if ($key[0] == 'OAUTH_GITHUB_NAME') - { - $OAUTH_SERVICENAME = 'GitHub'; - // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). - // We pass this param list in to 'state' because we need it before and after the redirect. - $shortscope = 'user,public_repo'; - $urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltocheckperms = 'https://github.com/settings/applications/'; - } elseif ($key[0] == 'OAUTH_GOOGLE_NAME') - { - $OAUTH_SERVICENAME = 'Google'; - // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). - // We pass this param list in to 'state' because we need it before and after the redirect. - $shortscope = 'userinfo_email,userinfo_profile,cloud_print'; - if (!empty($conf->global->OAUTH_GSUITE)){ - $shortscope .= ',admin_directory_user'; + $OAUTH_SERVICENAME = 'Unknown'; + if ($key[0] == 'OAUTH_GITHUB_NAME') + { + $OAUTH_SERVICENAME = 'GitHub'; + // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). + // We pass this param list in to 'state' because we need it before and after the redirect. + $shortscope = 'user,public_repo'; + $urltorenew = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = $urlwithroot.'/core/modules/oauth/github_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltocheckperms = 'https://github.com/settings/applications/'; + } elseif ($key[0] == 'OAUTH_GOOGLE_NAME') + { + $OAUTH_SERVICENAME = 'Google'; + // List of keys that will be converted into scopes (from constants 'SCOPE_state_in_uppercase' in file of service). + // We pass this param list in to 'state' because we need it before and after the redirect. + $shortscope = 'userinfo_email,userinfo_profile,cloud_print'; + if (!empty($conf->global->OAUTH_GSUITE)){ + $shortscope .= ',admin_directory_user'; } - //$scope.=',gmail_full'; - $urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltocheckperms = 'https://security.google.com/settings/security/permissions'; - } elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME') - { - $OAUTH_SERVICENAME = 'StripeTest'; - $urltorenew = $urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete = ''; - $urltocheckperms = ''; - } elseif ($key[0] == 'OAUTH_STRIPE_LIVE_NAME') - { - $OAUTH_SERVICENAME = 'StripeLive'; - $urltorenew = $urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); - $urltodelete = ''; - $urltocheckperms = ''; - } else { + //$scope.=',gmail_full'; + $urltorenew = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?shortscope='.$shortscope.'&state='.$shortscope.'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltocheckperms = 'https://security.google.com/settings/security/permissions'; + } elseif ($key[0] == 'OAUTH_STRIPE_TEST_NAME') + { + $OAUTH_SERVICENAME = 'StripeTest'; + $urltorenew = $urlwithroot.'/core/modules/oauth/stripetest_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = ''; + $urltocheckperms = ''; + } elseif ($key[0] == 'OAUTH_STRIPE_LIVE_NAME') + { + $OAUTH_SERVICENAME = 'StripeLive'; + $urltorenew = $urlwithroot.'/core/modules/oauth/stripelive_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/admin/oauthlogintokens.php'); + $urltodelete = ''; + $urltocheckperms = ''; + } else { $urltorenew = ''; $urltodelete = ''; $urltocheckperms = ''; } - // Show value of token - $tokenobj = null; - // Token - require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; - require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; - // Dolibarr storage - $storage = new DoliStorage($db, $conf); - try { - $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); - } catch (Exception $e) - { - // Return an error if token not found - } + // Show value of token + $tokenobj = null; + // Token + require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; + require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php'; + // Dolibarr storage + $storage = new DoliStorage($db, $conf); + try { + $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME); + } catch (Exception $e) + { + // Return an error if token not found + } - // Set other properties - $refreshtoken = false; - $expiredat = ''; + // Set other properties + $refreshtoken = false; + $expiredat = ''; - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if (is_object($tokenobj)) { - $expire = ($tokenobj->getEndOfLife() !== $tokenobj::EOL_NEVER_EXPIRES && $tokenobj->getEndOfLife() !== $tokenobj::EOL_UNKNOWN && time() > ($tokenobj->getEndOfLife() - 30)); - } + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if (is_object($tokenobj)) { + $expire = ($tokenobj->getEndOfLife() !== $tokenobj::EOL_NEVER_EXPIRES && $tokenobj->getEndOfLife() !== $tokenobj::EOL_UNKNOWN && time() > ($tokenobj->getEndOfLife() - 30)); + } - if ($key[1] != '' && $key[2] != '') { - if (is_object($tokenobj)) { - $refreshtoken = $tokenobj->getRefreshToken(); + if ($key[1] != '' && $key[2] != '') { + if (is_object($tokenobj)) { + $refreshtoken = $tokenobj->getRefreshToken(); - $endoflife = $tokenobj->getEndOfLife(); - if ($endoflife == $tokenobj::EOL_NEVER_EXPIRES) - { - $expiredat = $langs->trans("Never"); - } elseif ($endoflife == $tokenobj::EOL_UNKNOWN) - { - $expiredat = $langs->trans("Unknown"); - } else { - $expiredat = dol_print_date($endoflife, "dayhour"); - } - } - } + $endoflife = $tokenobj->getEndOfLife(); + if ($endoflife == $tokenobj::EOL_NEVER_EXPIRES) + { + $expiredat = $langs->trans("Never"); + } elseif ($endoflife == $tokenobj::EOL_UNKNOWN) + { + $expiredat = $langs->trans("Unknown"); + } else { + $expiredat = dol_print_date($endoflife, "dayhour"); + } + } + } - $submit_enabled = 0; + $submit_enabled = 0; - print '
'; - print ''; - print ''; + print ''; + print ''; + print ''; - print ''."\n"; + print '
'."\n"; - print ''; - print ''; - print ''; - print ''; - print "\n"; + print ''; + print ''; + print ''; + print ''; + print "\n"; - print ''; - print ''; - //var_dump($key); - print $langs->trans("OAuthIDSecret").''; - print ''; - print ''; - print ''."\n"; + print ''; + print ''; + //var_dump($key); + print $langs->trans("OAuthIDSecret").''; + print ''; + print ''; + print ''."\n"; - print ''; - print ''; - //var_dump($key); - print $langs->trans("IsTokenGenerated"); - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + //var_dump($key); + print $langs->trans("IsTokenGenerated"); + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - //var_dump($key); - print $langs->trans("Token").''; - print ''; - print ''."\n"; + } + print ''; + print ''."\n"; - if (is_object($tokenobj)) - { - // Token refresh - print ''; - print ''; - //var_dump($key); - print $langs->trans("TOKEN_REFRESH").''; - print ''; - print ''; + if (is_object($tokenobj)) + { + // Token refresh + print ''; + print ''; + //var_dump($key); + print $langs->trans("TOKEN_REFRESH").''; + print ''; + print ''; - // Token expired - print ''; - print ''; - //var_dump($key); - print $langs->trans("TOKEN_EXPIRED").''; - print ''; - print ''; + // Token expired + print ''; + print ''; + //var_dump($key); + print $langs->trans("TOKEN_EXPIRED").''; + print ''; + print ''; - // Token expired at - print ''; - print ''; - //var_dump($key); - print $langs->trans("TOKEN_EXPIRE_AT").''; - print ''; - print ''; - } + // Token expired at + print ''; + print ''; + //var_dump($key); + print $langs->trans("TOKEN_EXPIRE_AT").''; + print ''; + print ''; + } - print '
'.$langs->trans($key[0]).'
'.$langs->trans($key[0]).'
'; - print $langs->trans("SeePreviousTab"); - print ''; - print '
'; + print $langs->trans("SeePreviousTab"); + print ''; + print '
'; - if (is_object($tokenobj)) print $langs->trans("HasAccessToken"); - else print $langs->trans("NoAccessToken"); - print ''; - // Links to delete/checks token - if (is_object($tokenobj)) - { - //test on $storage->hasAccessToken($OAUTH_SERVICENAME) ? - print ''.$langs->trans('DeleteAccess').'
'; - } - // Request remote token - if ($urltorenew) - { - print ''.$langs->trans('RequestAccess').'
'; - } - // Check remote access - if ($urltocheckperms) - { - print '
'.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': '.$urltocheckperms.''; - } - print '
'; + if (is_object($tokenobj)) print $langs->trans("HasAccessToken"); + else print $langs->trans("NoAccessToken"); + print ''; + // Links to delete/checks token + if (is_object($tokenobj)) + { + //test on $storage->hasAccessToken($OAUTH_SERVICENAME) ? + print ''.$langs->trans('DeleteAccess').'
'; + } + // Request remote token + if ($urltorenew) + { + print ''.$langs->trans('RequestAccess').'
'; + } + // Check remote access + if ($urltocheckperms) + { + print '
'.$langs->trans("ToCheckDeleteTokenOnProvider", $OAUTH_SERVICENAME).': '.$urltocheckperms.''; + } + print '
'; - if (is_object($tokenobj)) - { - //var_dump($tokenobj); - print $tokenobj->getAccessToken().'
'; - //print 'Refresh: '.$tokenobj->getRefreshToken().'
'; - //print 'EndOfLife: '.$tokenobj->getEndOfLife().'
'; - //var_dump($tokenobj->getExtraParams()); - /*print '
Extra:
';*/ - } - print '
'; - print yn($refreshtoken); - print '
'; + print yn($refreshtoken); + print '
'; - print yn($expire); - print '
'; + print yn($expire); + print '
'; - print $expiredat; - print '
'; + print $expiredat; + print '
'; + print ''; - if (!empty($driver)) - { - if ($submit_enabled) { - print '
'; - } - } + if (!empty($driver)) + { + if ($submit_enabled) { + print '
'; + } + } - print '
'; - } + print ''; + } } if ($mode == 'test' && $user->admin) { - print $langs->trans('PrintTestDesc'.$driver)."

\n"; + print $langs->trans('PrintTestDesc'.$driver)."

\n"; - print ''; - if (!empty($driver)) - { - require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php'; - $classname = 'printing_'.$driver; - $langs->load($driver); - $printer = new $classname($db); - //print '
'.print_r($printer, true).'
'; - if (count($printer->getlistAvailablePrinters())) { - if ($printer->listAvailablePrinters() == 0) { - print $printer->resprint; - } else { - setEventMessages($printer->error, $printer->errors, 'errors'); - } - } else { - print $langs->trans('PleaseConfigureDriverfromList'); - } - } + print '
'; + if (!empty($driver)) + { + require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php'; + $classname = 'printing_'.$driver; + $langs->load($driver); + $printer = new $classname($db); + //print '
'.print_r($printer, true).'
'; + if (count($printer->getlistAvailablePrinters())) { + if ($printer->listAvailablePrinters() == 0) { + print $printer->resprint; + } else { + setEventMessages($printer->error, $printer->errors, 'errors'); + } + } else { + print $langs->trans('PleaseConfigureDriverfromList'); + } + } - print '
'; + print ''; } if ($mode == 'userconf' && $user->admin) { - print $langs->trans('PrintUserConfDesc'.$driver)."

\n"; + print $langs->trans('PrintUserConfDesc'.$driver)."

\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - $sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid'; - $resql = $db->query($sql); - while ($row = $db->fetch_array($resql)) { - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - } - print '
'.$langs->trans("User").''.$langs->trans("PrintModule").''.$langs->trans("PrintDriver").''.$langs->trans("Printer").''.$langs->trans("PrinterLocation").''.$langs->trans("PrinterId").''.$langs->trans("NumberOfCopy").''.$langs->trans("Delete").'
'.$row['login'].''.$row['module'].''.$row['driver'].''.$row['printer_name'].''.$row['printer_location'].''.$row['printer_id'].''.$row['copy'].''.img_picto($langs->trans("Delete"), 'delete').'
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $sql = 'SELECT p.rowid, p.printer_name, p.printer_location, p.printer_id, p.copy, p.module, p.driver, p.userid, u.login FROM '.MAIN_DB_PREFIX.'printing as p, '.MAIN_DB_PREFIX.'user as u WHERE p.userid=u.rowid'; + $resql = $db->query($sql); + while ($row = $db->fetch_array($resql)) { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + } + print '
'.$langs->trans("User").''.$langs->trans("PrintModule").''.$langs->trans("PrintDriver").''.$langs->trans("Printer").''.$langs->trans("PrinterLocation").''.$langs->trans("PrinterId").''.$langs->trans("NumberOfCopy").''.$langs->trans("Delete").'
'.$row['login'].''.$row['module'].''.$row['driver'].''.$row['printer_name'].''.$row['printer_location'].''.$row['printer_id'].''.$row['copy'].''.img_picto($langs->trans("Delete"), 'delete').'
'; } dol_fiche_end(); diff --git a/htdocs/admin/receiptprinter.php b/htdocs/admin/receiptprinter.php index 92b9ffbd8b4..350d4a3dc15 100644 --- a/htdocs/admin/receiptprinter.php +++ b/htdocs/admin/receiptprinter.php @@ -53,16 +53,16 @@ if (!$mode) $mode = 'config'; // used in library escpos maybe useful if php doesn't support gzdecode if (!function_exists('gzdecode')) { - /** - * Gzdecode - * - * @param string $data data to deflate - * @return string data deflated - */ - function gzdecode($data) - { - return gzinflate(substr($data, 10, -8)); - } + /** + * Gzdecode + * + * @param string $data data to deflate + * @return string data deflated + */ + function gzdecode($data) + { + return gzinflate(substr($data, 10, -8)); + } } @@ -71,167 +71,167 @@ if (!function_exists('gzdecode')) { */ if ($action == 'addprinter' && $user->admin) { - $error = 0; - if (empty($printername)) { - $error++; - setEventMessages($langs->trans("PrinterNameEmpty"), null, 'errors'); - } + $error = 0; + if (empty($printername)) { + $error++; + setEventMessages($langs->trans("PrinterNameEmpty"), null, 'errors'); + } - if (empty($parameter)) { - setEventMessages($langs->trans("PrinterParameterEmpty"), null, 'warnings'); - } + if (empty($parameter)) { + setEventMessages($langs->trans("PrinterParameterEmpty"), null, 'warnings'); + } - if (!$error) { - $db->begin(); - $result = $printer->addPrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->addPrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter); + if ($result > 0) $error++; - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("PrinterAdded", $printername), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("PrinterAdded", $printername), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'deleteprinter' && $user->admin) { - $error = 0; - if (empty($printerid)) { - $error++; - setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); - } + $error = 0; + if (empty($printerid)) { + $error++; + setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); + } - if (!$error) { - $db->begin(); - $result = $printer->deletePrinter($printerid); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->deletePrinter($printerid); + if ($result > 0) $error++; - if (!$error) - { - $db->commit(); - setEventMessages($langs->trans("PrinterDeleted", $printername), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) + { + $db->commit(); + setEventMessages($langs->trans("PrinterDeleted", $printername), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'updateprinter' && $user->admin) { - $error = 0; - if (empty($printerid)) { - $error++; - setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); - } + $error = 0; + if (empty($printerid)) { + $error++; + setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); + } - if (!$error) { - $db->begin(); - $result = $printer->updatePrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter, $printerid); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->updatePrinter($printername, GETPOST('printertypeid', 'int'), GETPOST('printerprofileid', 'int'), $parameter, $printerid); + if ($result > 0) $error++; - if (!$error) { - $db->commit(); - setEventMessages($langs->trans("PrinterUpdated", $printername), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) { + $db->commit(); + setEventMessages($langs->trans("PrinterUpdated", $printername), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'testprinter' && $user->admin) { - $error = 0; - if (empty($printerid)) { - $error++; - setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); - } + $error = 0; + if (empty($printerid)) { + $error++; + setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); + } - if (!$error) { - // test - $ret = $printer->sendTestToPrinter($printerid); - if ($ret == 0) { - setEventMessages($langs->trans("TestSentToPrinter", $printername), null); - } else { - setEventMessages($printer->error, $printer->errors, 'errors'); - } - } - $action = ''; + if (!$error) { + // test + $ret = $printer->sendTestToPrinter($printerid); + if ($ret == 0) { + setEventMessages($langs->trans("TestSentToPrinter", $printername), null); + } else { + setEventMessages($printer->error, $printer->errors, 'errors'); + } + } + $action = ''; } if ($action == 'testtemplate' && $user->admin) { - $error = 0; - // if (empty($printerid)) { - // $error++; - // setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); - // } + $error = 0; + // if (empty($printerid)) { + // $error++; + // setEventMessages($langs->trans("PrinterIdEmpty"), null, 'errors'); + // } - // if (! $error) { + // if (! $error) { // test require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $object = new Facture($db); //$object->initAsSpecimen(); $object->fetch(18); //var_dump($object->lines); - $ret = $printer->sendToPrinter($object, $templateid, 1); - if ($ret == 0) { - setEventMessages($langs->trans("TestTemplateToPrinter", $printername), null); - } else { - setEventMessages($printer->error, $printer->errors, 'errors'); - } - //} - $action = ''; + $ret = $printer->sendToPrinter($object, $templateid, 1); + if ($ret == 0) { + setEventMessages($langs->trans("TestTemplateToPrinter", $printername), null); + } else { + setEventMessages($printer->error, $printer->errors, 'errors'); + } + //} + $action = ''; } if ($action == 'updatetemplate' && $user->admin) { - $error = 0; - if (empty($templateid)) { - $error++; - setEventMessages($langs->trans("TemplateIdEmpty"), null, 'errors'); - } + $error = 0; + if (empty($templateid)) { + $error++; + setEventMessages($langs->trans("TemplateIdEmpty"), null, 'errors'); + } - if (!$error) { - $db->begin(); - $result = $printer->updateTemplate($templatename, $template, $templateid); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->updateTemplate($templatename, $template, $templateid); + if ($result > 0) $error++; - if (!$error) { - $db->commit(); - setEventMessages($langs->trans("TemplateUpdated", $templatename), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) { + $db->commit(); + setEventMessages($langs->trans("TemplateUpdated", $templatename), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'addtemplate' && $user->admin) { - $error = 0; - if (empty($templatename)) { - $error++; - setEventMessages($langs->trans("TemplateNameEmpty"), null, 'errors'); - } + $error = 0; + if (empty($templatename)) { + $error++; + setEventMessages($langs->trans("TemplateNameEmpty"), null, 'errors'); + } - if (!$error) { - $db->begin(); - $result = $printer->addTemplate($templatename, $template); - if ($result > 0) $error++; + if (!$error) { + $db->begin(); + $result = $printer->addTemplate($templatename, $template); + if ($result > 0) $error++; - if (!$error) { - $db->commit(); - setEventMessages($langs->trans("TemplateAdded", $templatename), null); - } else { - $db->rollback(); - dol_print_error($db); - } - } - $action = ''; + if (!$error) { + $db->commit(); + setEventMessages($langs->trans("TemplateAdded", $templatename), null); + } else { + $db->rollback(); + dol_print_error($db); + } + } + $action = ''; } if ($action == 'deletetemplate' && $user->admin) { @@ -273,116 +273,116 @@ $head = receiptprinteradmin_prepare_head($mode); // mode = config if ($mode == 'config' && $user->admin) { - print '
'; - print ''; - if ($action != 'editprinter') { - print ''; - } else { - print ''; - } + print ''; + print ''; + if ($action != 'editprinter') { + print ''; + } else { + print ''; + } - dol_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); + dol_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); - print ''.$langs->trans("ReceiptPrinterDesc")."

\n"; + print ''.$langs->trans("ReceiptPrinterDesc")."

\n"; - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print "\n"; - $ret = $printer->listprinters(); - $nbofprinters = count($printer->listprinters); + print '
'.$langs->trans("Name").''.$langs->trans("Type").''.$langs->trans("Profile").''.$langs->trans("Parameters").'
'."\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $ret = $printer->listprinters(); + $nbofprinters = count($printer->listprinters); - if ($action != 'editprinter') { - print ''; - print ''; - $ret = $printer->selectTypePrinter(); - print ''; - $ret = $printer->selectProfilePrinter(); - print ''; - print ''; - print ''; - print ''; - } + if ($action != 'editprinter') { + print ''; + print ''; + $ret = $printer->selectTypePrinter(); + print ''; + $ret = $printer->selectProfilePrinter(); + print ''; + print ''; + print ''; + print ''; + } - if ($ret > 0) { - setEventMessages($printer->error, $printer->errors, 'errors'); - } else { - for ($line = 0; $line < $nbofprinters; $line++) { - print ''; - if ($action == 'editprinter' && $printer->listprinters[$line]['rowid'] == $printerid) { - print ''; - print ''; - $ret = $printer->selectTypePrinter($printer->listprinters[$line]['fk_type']); - print ''; - $ret = $printer->selectProfilePrinter($printer->listprinters[$line]['fk_profile']); - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - print ''; - print ''; - // edit icon - print ''; - print ''; - } - } - } + if ($ret > 0) { + setEventMessages($printer->error, $printer->errors, 'errors'); + } else { + for ($line = 0; $line < $nbofprinters; $line++) { + print ''; + if ($action == 'editprinter' && $printer->listprinters[$line]['rowid'] == $printerid) { + print ''; + print ''; + $ret = $printer->selectTypePrinter($printer->listprinters[$line]['fk_type']); + print ''; + $ret = $printer->selectProfilePrinter($printer->listprinters[$line]['fk_profile']); + print ''; + print ''; + print ''; + print ''; + } else { + print ''; + print ''; + print ''; + print ''; + // edit icon + print ''; + print ''; + } + } + } - print '
'.$langs->trans("Name").''.$langs->trans("Type").''.$langs->trans("Profile").''.$langs->trans("Parameters").'
'.$printer->resprint.''.$printer->profileresprint.''; - if ($action != 'editprinter') { - print '
'; - } - print '
'.$printer->resprint.''.$printer->profileresprint.''; + if ($action != 'editprinter') { + print '
'; + } + print '
'.$printer->resprint.''.$printer->profileresprint.''; - print '
'; - print '
'.$printer->listprinters[$line]['name'].''.$langs->trans($printer->listprinters[$line]['fk_type_name']).''.$langs->trans($printer->listprinters[$line]['fk_profile_name']).''.$printer->listprinters[$line]['parameter'].''; - print img_picto($langs->trans("Edit"), 'edit'); - print ''; - // delete icon - print ''; - print img_picto($langs->trans("Delete"), 'delete'); - print ''; - // test icon - print ''; - print img_picto($langs->trans("TestPrinter"), 'printer'); - print '
'.$printer->resprint.''.$printer->profileresprint.''; + print '
'; + print '
'.$printer->listprinters[$line]['name'].''.$langs->trans($printer->listprinters[$line]['fk_type_name']).''.$langs->trans($printer->listprinters[$line]['fk_profile_name']).''.$printer->listprinters[$line]['parameter'].''; + print img_picto($langs->trans("Edit"), 'edit'); + print ''; + // delete icon + print ''; + print img_picto($langs->trans("Delete"), 'delete'); + print ''; + // test icon + print ''; + print img_picto($langs->trans("TestPrinter"), 'printer'); + print '
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); - print '
'; + print ''; - print '
'; + print '
'; - print load_fiche_titre($langs->trans("ReceiptPrinterTypeDesc"), '', '')."\n"; + print load_fiche_titre($langs->trans("ReceiptPrinterTypeDesc"), '', '')."\n"; - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
'.$langs->trans("CONNECTOR_DUMMY").':'.$langs->trans("CONNECTOR_DUMMY_HELP").'
'.$langs->trans("CONNECTOR_NETWORK_PRINT").':'.$langs->trans("CONNECTOR_NETWORK_PRINT_HELP").'
'.$langs->trans("CONNECTOR_FILE_PRINT").':'.$langs->trans("CONNECTOR_FILE_PRINT_HELP").'
'.$langs->trans("CONNECTOR_WINDOWS_PRINT").':'.$langs->trans("CONNECTOR_WINDOWS_PRINT_HELP").'
'.$langs->trans("CONNECTOR_CUPS_PRINT").':'.$langs->trans("CONNECTOR_CUPS_PRINT_HELP").'
'; + print ''."\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("CONNECTOR_DUMMY").':'.$langs->trans("CONNECTOR_DUMMY_HELP").'
'.$langs->trans("CONNECTOR_NETWORK_PRINT").':'.$langs->trans("CONNECTOR_NETWORK_PRINT_HELP").'
'.$langs->trans("CONNECTOR_FILE_PRINT").':'.$langs->trans("CONNECTOR_FILE_PRINT_HELP").'
'.$langs->trans("CONNECTOR_WINDOWS_PRINT").':'.$langs->trans("CONNECTOR_WINDOWS_PRINT_HELP").'
'.$langs->trans("CONNECTOR_CUPS_PRINT").':'.$langs->trans("CONNECTOR_CUPS_PRINT_HELP").'
'; - print '
'; + print '
'; - print load_fiche_titre($langs->trans("ReceiptPrinterProfileDesc"), '', '')."\n"; + print load_fiche_titre($langs->trans("ReceiptPrinterProfileDesc"), '', '')."\n"; - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - print ''; - print '
'.$langs->trans("PROFILE_DEFAULT").':'.$langs->trans("PROFILE_DEFAULT_HELP").'
'.$langs->trans("PROFILE_SIMPLE").':'.$langs->trans("PROFILE_SIMPLE_HELP").'
'.$langs->trans("PROFILE_EPOSTEP").':'.$langs->trans("PROFILE_EPOSTEP_HELP").'
'.$langs->trans("PROFILE_P822D").':'.$langs->trans("PROFILE_P822D_HELP").'
'.$langs->trans("PROFILE_STAR").':'.$langs->trans("PROFILE_STAR_HELP").'
'; + print ''."\n"; + print ''; + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("PROFILE_DEFAULT").':'.$langs->trans("PROFILE_DEFAULT_HELP").'
'.$langs->trans("PROFILE_SIMPLE").':'.$langs->trans("PROFILE_SIMPLE_HELP").'
'.$langs->trans("PROFILE_EPOSTEP").':'.$langs->trans("PROFILE_EPOSTEP_HELP").'
'.$langs->trans("PROFILE_P822D").':'.$langs->trans("PROFILE_P822D_HELP").'
'.$langs->trans("PROFILE_STAR").':'.$langs->trans("PROFILE_STAR_HELP").'
'; } // mode = template @@ -390,56 +390,56 @@ if ($mode == 'template' && $user->admin) { dol_fiche_head($head, $mode, $langs->trans("ModuleSetup"), -1, 'technic'); print '
'; - print ''; - if ($action != 'edittemplate') { - print ''; - } else { - print ''; - } + print ''; + if ($action != 'edittemplate') { + print ''; + } else { + print ''; + } - print ''."\n"; - print ''; - print ''; - print ''; - print ''; - print "\n"; - $ret = $printer->listPrintersTemplates(); - //print '
'.print_r($printer->listprinterstemplates, true).'
'; - if ($ret > 0) { - setEventMessages($printer->error, $printer->errors, 'errors'); - } else { - $max = count($printer->listprinterstemplates); - for ($line = 0; $line < $max; $line++) { - print ''; - if ($action == 'edittemplate' && $printer->listprinterstemplates[$line]['rowid'] == $templateid) { - print ''; - print ''; - print ''; - print ''; - } else { - print ''; - print ''; - // edit icon - print ''; - } - print ''; - } - } + print '
'.$langs->trans("Name").''.$langs->trans("Template").'
'; - print ''; - print ''.$printer->listprinterstemplates[$line]['name'].''.nl2br(htmlentities($printer->listprinterstemplates[$line]['template'])).''; - print img_picto($langs->trans("Edit"), 'edit'); - print ''; - // delete icon - print ''; - print img_picto($langs->trans("Delete"), 'delete'); - print ''; - // test icon - print ''; - print img_picto($langs->trans("TestPrinterTemplate"), 'printer'); - print '
'."\n"; + print ''; + print ''; + print ''; + print ''; + print "\n"; + $ret = $printer->listPrintersTemplates(); + //print '
'.print_r($printer->listprinterstemplates, true).'
'; + if ($ret > 0) { + setEventMessages($printer->error, $printer->errors, 'errors'); + } else { + $max = count($printer->listprinterstemplates); + for ($line = 0; $line < $max; $line++) { + print ''; + if ($action == 'edittemplate' && $printer->listprinterstemplates[$line]['rowid'] == $templateid) { + print ''; + print ''; + print ''; + print ''; + } else { + print ''; + print ''; + // edit icon + print ''; + } + print ''; + } + } - if ($action != 'edittemplate') { - print ''; + if ($action != 'edittemplate') { + print ''; print ''; print '
'.$langs->trans("Name").''.$langs->trans("Template").'
'; + print ''; + print ''.$printer->listprinterstemplates[$line]['name'].''.nl2br(htmlentities($printer->listprinterstemplates[$line]['template'])).''; + print img_picto($langs->trans("Edit"), 'edit'); + print ''; + // delete icon + print ''; + print img_picto($langs->trans("Delete"), 'delete'); + print ''; + // test icon + print ''; + print img_picto($langs->trans("TestPrinterTemplate"), 'printer'); + print '
'; print '
'."\n"; - print '
'; + print '
'.$langs->trans("RunCommandSummary").':
'."\n"; + print '
'."\n"; + print '
'; - //print $paramclear; + //print $paramclear; - // Now show result - print ''.$langs->trans("BackupResult").': '; + // Now show result + print ''.$langs->trans("BackupResult").': '; print $_SESSION["commandbackupresult"]; $_SESSION["commandbackuplastdone"] = ''; @@ -568,20 +568,20 @@ $filecompression['zip'] = array('function' => 'dol_compress_dir', 'id' => 'radio $i = 0; foreach ($filecompression as $key => $val) { - if (!$val['function'] || function_exists($val['function'])) // Enabled export format - { - $checked = ''; - if ($key == 'gz') $checked = ' checked'; - print ''; - print ' '; - } else // Disabled export format - { - print ''; - print ' '; - print ' ('.$langs->trans("NotAvailable").')'; - } - print '     '; - $i++; + if (!$val['function'] || function_exists($val['function'])) // Enabled export format + { + $checked = ''; + if ($key == 'gz') $checked = ' checked'; + print ''; + print ' '; + } else // Disabled export format + { + print ''; + print ' '; + print ' ('.$langs->trans("NotAvailable").')'; + } + print '     '; + $i++; } print ''; diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index 560530c9161..c962a9fb776 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -73,16 +73,16 @@ include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers { - $transkey = ''; - $transvalue = ''; - $toselect = ''; - $search_array_options = array(); + $transkey = ''; + $transvalue = ''; + $toselect = ''; + $search_array_options = array(); } if ($action == 'setMAIN_ENABLE_OVERWRITE_TRANSLATION') { - if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 1, 'chaine', 0, '', $conf->entity); - else dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 0, 'chaine', 0, '', $conf->entity); + if (GETPOST('value')) dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 1, 'chaine', 0, '', $conf->entity); + else dolibarr_set_const($db, 'MAIN_ENABLE_OVERWRITE_TRANSLATION', 0, 'chaine', 0, '', $conf->entity); } if ($action == 'update') @@ -139,25 +139,25 @@ if ($action == 'add') } if (!$error) { - $db->begin(); + $db->begin(); - $sql = "INSERT INTO ".MAIN_DB_PREFIX."overwrite_trans(lang, transkey, transvalue, entity) VALUES ('".$db->escape($langcode)."','".$db->escape($transkey)."','".$db->escape($transvalue)."', ".$db->escape($conf->entity).")"; + $sql = "INSERT INTO ".MAIN_DB_PREFIX."overwrite_trans(lang, transkey, transvalue, entity) VALUES ('".$db->escape($langcode)."','".$db->escape($transkey)."','".$db->escape($transvalue)."', ".$db->escape($conf->entity).")"; $result = $db->query($sql); if ($result > 0) { - $db->commit(); - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + $db->commit(); + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $action = ""; $transkey = ""; $transvalue = ""; } else { - $db->rollback(); - if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { - setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings'); - } else { - setEventMessages($db->lasterror(), null, 'errors'); - } + $db->rollback(); + if ($db->lasterrno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') + { + setEventMessages($langs->trans("WarningAnEntryAlreadyExistForTransKey"), null, 'warnings'); + } else { + setEventMessages($db->lasterror(), null, 'errors'); + } $action = ''; } } @@ -196,15 +196,15 @@ $enabledisablehtml = ''; $enabledisablehtml .= $langs->trans("EnableOverwriteTranslation").' '; if (empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) { - // Button off, click to enable - $enabledisablehtml .= ''; - $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); - $enabledisablehtml .= ''; + // Button off, click to enable + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Disabled"), 'switch_off'); + $enabledisablehtml .= ''; } else { - // Button on, click to disable - $enabledisablehtml .= ''; - $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); - $enabledisablehtml .= ''; + // Button on, click to disable + $enabledisablehtml .= ''; + $enabledisablehtml .= img_picto($langs->trans("Activated"), 'switch_on'); + $enabledisablehtml .= ''; } print load_fiche_titre($langs->trans("Translation"), $enabledisablehtml, 'title_setup'); @@ -247,43 +247,43 @@ if ($mode == 'overwrite') if ($action == 'edit' || empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) $disablededit = ' disabled'; print '
'; - print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); - $urlwikitranslatordoc = 'https://wiki.dolibarr.org/index.php/Translator_documentation'; - print ' ('.$langs->trans("SeeAlso", ''.$langs->trans("Here").'').')
'; - print $langs->trans("TranslationOverwriteDesc", $langs->transnoentitiesnoconv("Language"), $langs->transnoentitiesnoconv("Key"), $langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n"; - print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."
\n"; - print '
'; + print img_info().' '.$langs->trans("SomeTranslationAreUncomplete"); + $urlwikitranslatordoc = 'https://wiki.dolibarr.org/index.php/Translator_documentation'; + print ' ('.$langs->trans("SeeAlso", ''.$langs->trans("Here").'').')
'; + print $langs->trans("TranslationOverwriteDesc", $langs->transnoentitiesnoconv("Language"), $langs->transnoentitiesnoconv("Key"), $langs->transnoentitiesnoconv("NewTranslationStringToShow"))."\n"; + print ' ('.$langs->trans("TranslationOverwriteDesc2").').'."
\n"; + print ''; - print '
'; + print '
'; print ''; - print ''; + print ''; print '
'; - print ''; - print ''; - print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("NewTranslationStringToShow", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); - //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); - print ''; - print "\n"; + print '
'; + print ''; + print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("NewTranslationStringToShow", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); + //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); + print ''; + print "\n"; - // Line to add new record - print "\n"; + // Line to add new record + print "\n"; - print ''."\n"; - print ''; - // Limit to superadmin - /*if (! empty($conf->multicompany->enabled) && !$user->entity) + print ''."\n"; + print ''; + // Limit to superadmin + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print '\n"; - print ''; + print '\n"; + print ''; - // Show constants - $sql = "SELECT rowid, entity, lang, transkey, transvalue"; - $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; - $sql .= " WHERE 1 = 1"; - $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; - $sql .= $db->order($sortfield, $sortorder); + // Show constants + $sql = "SELECT rowid, entity, lang, transkey, transvalue"; + $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; + $sql .= " WHERE 1 = 1"; + $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; + $sql .= $db->order($sortfield, $sortorder); - dol_syslog("translation::select from table", LOG_DEBUG); - $result = $db->query($sql); - if ($result) - { - $num = $db->num_rows($result); - $i = 0; + dol_syslog("translation::select from table", LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $num = $db->num_rows($result); + $i = 0; - while ($i < $num) - { - $obj = $db->fetch_object($result); + while ($i < $num) + { + $obj = $db->fetch_object($result); - print "\n"; + print "\n"; - print ''; + print ''; - print ''."\n"; - print ''."\n"; + print ''."\n"; + print ''."\n"; - // Value - print ''; + if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) + { + print ''; + } else { + print dol_escape_htmltag($obj->transvalue); + } + print ''; - print ''; + print ''; + } else { + print ''.img_edit().''; + print '   '; + print ''.img_delete().''; + } + print ''; - print "\n"; - print "\n"; - $i++; - } - } + print "\n"; + print "\n"; + $i++; + } + } - print '
'; - print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit ? 1 : 0, 'maxwidthonsmartphone', 1); - print ''; - print ''; - print ''; - print ''; - print '
'; + print $formadmin->select_language(GETPOST('langcode'), 'langcode', 0, null, 1, 0, $disablededit ? 1 : 0, 'maxwidthonsmartphone', 1); + print ''; + print ''; + print ''; + print ''; + print ''; print ''; @@ -292,118 +292,118 @@ if ($mode == 'overwrite') } else {*/ - print ''; - print ''; - //} - print ''; - print "
'; + print ''; + //} + print ''; + print "
'.$obj->lang.''.$obj->transkey.''.$obj->lang.''.$obj->transkey.''; - /*print ''; + // Value + print ''; + /*print ''; print ''; print ''; print ''; */ - if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) - { - print ''; - } else { - print dol_escape_htmltag($obj->transvalue); - } - print ''; - if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) - { - print ''; - print ''; - print '   '; - print ''; - } else { - print ''.img_edit().''; + print ''; + if ($action == 'edit' && $obj->rowid == GETPOST('rowid', 'int')) + { + print ''; + print ''; print '   '; - print ''.img_delete().''; - } - print '
'; - print '
'; + print '
'; + print ''; } if ($mode == 'searchkey') { - $langcode = GETPOST('langcode') ?GETPOST('langcode') : $langs->defaultlang; + $langcode = GETPOST('langcode') ?GETPOST('langcode') : $langs->defaultlang; - $newlang = new Translate('', $conf); - $newlang->setDefaultLang($langcode); + $newlang = new Translate('', $conf); + $newlang->setDefaultLang($langcode); - $newlangfileonly = new Translate('', $conf); - $newlangfileonly->setDefaultLang($langcode); + $newlangfileonly = new Translate('', $conf); + $newlangfileonly->setDefaultLang($langcode); - $recordtoshow = array(); + $recordtoshow = array(); - // Search modules dirs - $modulesdir = dolGetModulesDirs(); + // Search modules dirs + $modulesdir = dolGetModulesDirs(); - $nbtotaloffiles = 0; - $nbempty = 0; - /*var_dump($langcode); + $nbtotaloffiles = 0; + $nbempty = 0; + /*var_dump($langcode); var_dump($transkey); var_dump($transvalue);*/ - if (empty($langcode) || $langcode == '-1') $nbempty++; - if (empty($transkey)) $nbempty++; - if (empty($transvalue)) $nbempty++; - if ($action == 'search' && ($nbempty > 999)) // 999 to disable this - { - setEventMessages($langs->trans("WarningAtLeastKeyOrTranslationRequired"), null, 'warnings'); - } else { - // Search into dir of modules (the $modulesdir is already a list that loop on $conf->file->dol_document_root) - $i = 0; - foreach ($modulesdir as $keydir => $tmpsearchdir) - { - $searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/' + if (empty($langcode) || $langcode == '-1') $nbempty++; + if (empty($transkey)) $nbempty++; + if (empty($transvalue)) $nbempty++; + if ($action == 'search' && ($nbempty > 999)) // 999 to disable this + { + setEventMessages($langs->trans("WarningAtLeastKeyOrTranslationRequired"), null, 'warnings'); + } else { + // Search into dir of modules (the $modulesdir is already a list that loop on $conf->file->dol_document_root) + $i = 0; + foreach ($modulesdir as $keydir => $tmpsearchdir) + { + $searchdir = $tmpsearchdir; // $searchdir can be '.../htdocs/core/modules/' or '.../htdocs/custom/mymodule/core/modules/' - // Directory of translation files - $dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels - $dir_lang_osencoded = dol_osencode($dir_lang); + // Directory of translation files + $dir_lang = dirname(dirname($searchdir))."/langs/".$langcode; // The 2 dirname is to go up in dir for 2 levels + $dir_lang_osencoded = dol_osencode($dir_lang); - $filearray = dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder) == 'asc' ?SORT_ASC:SORT_DESC), 1); - foreach ($filearray as $file) - { + $filearray = dol_dir_list($dir_lang_osencoded, 'files', 0, '', '', $sortfield, (strtolower($sortorder) == 'asc' ?SORT_ASC:SORT_DESC), 1); + foreach ($filearray as $file) + { $tmpfile = preg_replace('/.lang/i', '', basename($file['name'])); $moduledirname = (basename(dirname(dirname($dir_lang)))); @@ -416,135 +416,135 @@ if ($mode == 'searchkey') if ($result < 0) print 'Failed to load language file '.$tmpfile.'
'."\n"; else $nbtotaloffiles++; //print 'After loading lang '.$langkey.', newlang has '.count($newlang->tab_translate).' records
'."\n"; - } - $i++; - } + } + $i++; + } - // Now search into translation array - foreach ($newlang->tab_translate as $key => $val) - { - if ($transkey && !preg_match('/'.preg_quote($transkey, '/').'/i', $key)) continue; - if ($transvalue && !preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) continue; - $recordtoshow[$key] = $val; - } - } + // Now search into translation array + foreach ($newlang->tab_translate as $key => $val) + { + if ($transkey && !preg_match('/'.preg_quote($transkey, '/').'/i', $key)) continue; + if ($transvalue && !preg_match('/'.preg_quote($transvalue, '/').'/i', $val)) continue; + $recordtoshow[$key] = $val; + } + } - //print '
'; - $nbtotalofrecordswithoutfilters = count($newlang->tab_translate); - $nbtotalofrecords = count($recordtoshow); - $num = $limit + 1; - if (($offset + $num) > $nbtotalofrecords) $num = $limit; + //print '
'; + $nbtotalofrecordswithoutfilters = count($newlang->tab_translate); + $nbtotalofrecords = count($recordtoshow); + $num = $limit + 1; + if (($offset + $num) > $nbtotalofrecords) $num = $limit; - //print 'param='.$param.' $_SERVER["PHP_SELF"]='.$_SERVER["PHP_SELF"].' num='.$num.' page='.$page.' nbtotalofrecords='.$nbtotalofrecords." sortfield=".$sortfield." sortorder=".$sortorder; - $title = $langs->trans("TranslationKeySearch"); - if ($nbtotalofrecords > 0) $title .= ' ('.$nbtotalofrecords.' / '.$nbtotalofrecordswithoutfilters.' - '.$nbtotaloffiles.' '.$langs->trans("Files").')'; - print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1); + //print 'param='.$param.' $_SERVER["PHP_SELF"]='.$_SERVER["PHP_SELF"].' num='.$num.' page='.$page.' nbtotalofrecords='.$nbtotalofrecords." sortfield=".$sortfield." sortorder=".$sortorder; + $title = $langs->trans("TranslationKeySearch"); + if ($nbtotalofrecords > 0) $title .= ' ('.$nbtotalofrecords.' / '.$nbtotalofrecordswithoutfilters.' - '.$nbtotaloffiles.' '.$langs->trans("Files").')'; + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, -1 * $nbtotalofrecords, '', 0, '', '', $limit, 0, 0, 1); - print ''; - print ''; + print ''; + print ''; print '
'; - print ''; - print ''; - print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); - print_liste_field_titre("CurrentTranslationString", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); - //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); - print ''; - print "\n"; + print '
'; + print ''; + print_liste_field_titre("Language_en_US_es_MX_etc", $_SERVER["PHP_SELF"], 'lang,transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("Key", $_SERVER["PHP_SELF"], 'transkey', '', $param, '', $sortfield, $sortorder); + print_liste_field_titre("CurrentTranslationString", $_SERVER["PHP_SELF"], 'transvalue', '', $param, '', $sortfield, $sortorder); + //if (! empty($conf->multicompany->enabled) && !$user->entity) print_liste_field_titre("Entity", $_SERVER["PHP_SELF"], 'entity,transkey', '', $param, '', $sortfield, $sortorder); + print ''; + print "\n"; - // Line to search new record - print "\n"; + // Line to search new record + print "\n"; - print ''."\n"; - print ''."\n"; + print ''; - // Action column - print ''; - print ''; + print ''; + //} + print ''; + // Action column + print ''; + print ''; - if ($sortfield == 'transkey' && strtolower($sortorder) == 'asc') ksort($recordtoshow); - if ($sortfield == 'transkey' && strtolower($sortorder) == 'desc') krsort($recordtoshow); - if ($sortfield == 'transvalue' && strtolower($sortorder) == 'asc') asort($recordtoshow); - if ($sortfield == 'transvalue' && strtolower($sortorder) == 'desc') arsort($recordtoshow); + if ($sortfield == 'transkey' && strtolower($sortorder) == 'asc') ksort($recordtoshow); + if ($sortfield == 'transkey' && strtolower($sortorder) == 'desc') krsort($recordtoshow); + if ($sortfield == 'transvalue' && strtolower($sortorder) == 'asc') asort($recordtoshow); + if ($sortfield == 'transvalue' && strtolower($sortorder) == 'desc') arsort($recordtoshow); - // Show result - $i = 0; - foreach ($recordtoshow as $key => $val) - { - $i++; - if ($i <= $offset) continue; - if ($i > ($offset + $limit)) break; - print ''; }*/ - print ''."\n"; - } + print ''."\n"; + } - print '
'; - //print $formadmin->select_language($langcode,'langcode',0,null,$langs->trans("All"),0,0,'',1); - print $formadmin->select_language($langcode, 'langcode', 0, null, 0, 0, 0, 'maxwidthonsmartphone', 1); - print ''; - print ''; - print ''; - print ''; - // Limit to superadmin - /*if (! empty($conf->multicompany->enabled) && !$user->entity) + print '
'; + //print $formadmin->select_language($langcode,'langcode',0,null,$langs->trans("All"),0,0,'',1); + print $formadmin->select_language($langcode, 'langcode', 0, null, 0, 0, 0, 'maxwidthonsmartphone', 1); + print ''; + print ''; + print ''; + print ''; + // Limit to superadmin + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print ''; print ''; } else {*/ - print ''; - //} - print ''; - $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); - print $searchpicto; - print '
'; + $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + print $searchpicto; + print '
'.$langcode.''.$key.''; - print dol_escape_htmltag($val); - print ''; - if (!empty($newlangfileonly->tab_translate[$key])) - { - if ($val != $newlangfileonly->tab_translate[$key]) - { - // retrieve rowid - $sql = "SELECT rowid"; - $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; - $sql .= " WHERE transkey = '".$key."'"; - $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; - dol_syslog("translation::select from table", LOG_DEBUG); - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - } - print ''.img_edit().''; - print ' '; - print ''.img_delete().''; - print '  '; - $htmltext = $langs->trans("OriginalValueWas", ''.$newlangfileonly->tab_translate[$key].''); - print $form->textwithpicto('', $htmltext, 1, 'info'); - } elseif (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) - { - //print $key.'-'.$val; - print ''.img_edit_add($langs->trans("Overwrite")).''; - } + // Show result + $i = 0; + foreach ($recordtoshow as $key => $val) + { + $i++; + if ($i <= $offset) continue; + if ($i > ($offset + $limit)) break; + print '
'.$langcode.''.$key.''; + print dol_escape_htmltag($val); + print ''; + if (!empty($newlangfileonly->tab_translate[$key])) + { + if ($val != $newlangfileonly->tab_translate[$key]) + { + // retrieve rowid + $sql = "SELECT rowid"; + $sql .= " FROM ".MAIN_DB_PREFIX."overwrite_trans"; + $sql .= " WHERE transkey = '".$key."'"; + $sql .= " AND entity IN (".getEntity('overwrite_trans').")"; + dol_syslog("translation::select from table", LOG_DEBUG); + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + } + print ''.img_edit().''; + print ' '; + print ''.img_delete().''; + print '  '; + $htmltext = $langs->trans("OriginalValueWas", ''.$newlangfileonly->tab_translate[$key].''); + print $form->textwithpicto('', $htmltext, 1, 'info'); + } elseif (!empty($conf->global->MAIN_ENABLE_OVERWRITE_TRANSLATION)) + { + //print $key.'-'.$val; + print ''.img_edit_add($langs->trans("Overwrite")).''; + } - if (!empty($conf->global->MAIN_FEATURES_LEVEL)) - { - $transifexlangfile = '$'; // $ means 'All' - //$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key; - $transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?q=key%3A'.$key; + if (!empty($conf->global->MAIN_FEATURES_LEVEL)) + { + $transifexlangfile = '$'; // $ means 'All' + //$transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?key='.$key; + $transifexurl = 'https://www.transifex.com/dolibarr-association/dolibarr/translate/#'.$langcode.'/'.$transifexlangfile.'?q=key%3A'.$key; - print '   '.img_picto($langs->trans('FixOnTransifex'), 'globe').''; - } - } else { - $htmltext = $langs->trans("TransKeyWithoutOriginalValue", $key); - print $form->textwithpicto('', $htmltext, 1, 'warning'); - } - /*if (! empty($conf->multicompany->enabled) && !$user->entity) + print '   '.img_picto($langs->trans('FixOnTransifex'), 'globe').''; + } + } else { + $htmltext = $langs->trans("TransKeyWithoutOriginalValue", $key); + print $form->textwithpicto('', $htmltext, 1, 'warning'); + } + /*if (! empty($conf->multicompany->enabled) && !$user->entity) { print ''.$val.'
'; - print '
'; + print ''; + print ''; } dol_fiche_end(); diff --git a/htdocs/admin/website.php b/htdocs/admin/website.php index b8520ecc227..19d71ebb1d9 100644 --- a/htdocs/admin/website.php +++ b/htdocs/admin/website.php @@ -124,252 +124,252 @@ $sourceList = array(); // Actions add or modify a website if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) { - $listfield = explode(',', $tabfield[$id]); - $listfieldinsert = explode(',', $tabfieldinsert[$id]); - $listfieldmodify = explode(',', $tabfieldinsert[$id]); - $listfieldvalue = explode(',', $tabfieldvalue[$id]); + $listfield = explode(',', $tabfield[$id]); + $listfieldinsert = explode(',', $tabfieldinsert[$id]); + $listfieldmodify = explode(',', $tabfieldinsert[$id]); + $listfieldvalue = explode(',', $tabfieldvalue[$id]); - // Check that all fields are filled - $ok = 1; - foreach ($listfield as $f => $value) - { - if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == '')) - { - $ok = 0; - $fieldnamekey = $listfield[$f]; - setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); - break; - } elseif ($value == 'ref' && !preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value])) - { + // Check that all fields are filled + $ok = 1; + foreach ($listfield as $f => $value) + { + if ($value == 'ref' && (!GETPOSTISSET($value) || GETPOST($value) == '')) + { $ok = 0; - $fieldnamekey = $listfield[$f]; + $fieldnamekey = $listfield[$f]; + setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); + break; + } elseif ($value == 'ref' && !preg_match('/^[a-z0-9_\-\.]+$/i', $_POST[$value])) + { + $ok = 0; + $fieldnamekey = $listfield[$f]; setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities($fieldnamekey)), null, 'errors'); break; - } - } + } + } - // Clean parameters - if (!empty($_POST['ref'])) - { - $websitekey = strtolower($_POST['ref']); - } + // Clean parameters + if (!empty($_POST['ref'])) + { + $websitekey = strtolower($_POST['ref']); + } - // Si verif ok et action add, on ajoute la ligne - if ($ok && GETPOST('actionadd', 'alpha')) - { - if ($tabrowid[$id]) - { - // Recupere id libre pour insertion - $newid = 0; - $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; - $result = $db->query($sql); - if ($result) - { - $obj = $db->fetch_object($result); - $newid = ($obj->newid + 1); - } else { - dol_print_error($db); - } - } + // Si verif ok et action add, on ajoute la ligne + if ($ok && GETPOST('actionadd', 'alpha')) + { + if ($tabrowid[$id]) + { + // Recupere id libre pour insertion + $newid = 0; + $sql = "SELECT max(".$tabrowid[$id].") newid from ".$tabname[$id]; + $result = $db->query($sql); + if ($result) + { + $obj = $db->fetch_object($result); + $newid = ($obj->newid + 1); + } else { + dol_print_error($db); + } + } - /* $website=new Website($db); + /* $website=new Website($db); $website->ref= $website->description= $website->virtualhost= $website->create($user); */ - // Add new entry - $sql = "INSERT INTO ".$tabname[$id]." ("; - // List of fields - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) - $sql .= $tabrowid[$id].","; - $sql .= $tabfieldinsert[$id]; - $sql .= ",status)"; - $sql .= " VALUES("; + // Add new entry + $sql = "INSERT INTO ".$tabname[$id]." ("; + // List of fields + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $tabrowid[$id].","; + $sql .= $tabfieldinsert[$id]; + $sql .= ",status)"; + $sql .= " VALUES("; - // List of values - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) - $sql .= $newid.","; - $i = 0; - foreach ($listfieldinsert as $f => $value) - { - if ($value == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($value == 'ref') { - $_POST[$listfieldvalue[$i]] = strtolower($_POST[$listfieldvalue[$i]]); - } - if ($i) $sql .= ","; - if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; - else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql .= ",1)"; + // List of values + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldinsert)) + $sql .= $newid.","; + $i = 0; + foreach ($listfieldinsert as $f => $value) + { + if ($value == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($value == 'ref') { + $_POST[$listfieldvalue[$i]] = strtolower($_POST[$listfieldvalue[$i]]); + } + if ($i) $sql .= ","; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql .= ",1)"; - dol_syslog("actionadd", LOG_DEBUG); - $result = $db->query($sql); - if ($result) // Add is ok - { - setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); - unset($_POST); // Clean $_POST array, we keep only - } else { - if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); - } else { - dol_print_error($db); - } - } - } + dol_syslog("actionadd", LOG_DEBUG); + $result = $db->query($sql); + if ($result) // Add is ok + { + setEventMessages($langs->transnoentities("RecordSaved"), null, 'mesgs'); + unset($_POST); // Clean $_POST array, we keep only + } else { + if ($db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + setEventMessages($langs->transnoentities("ErrorRecordAlreadyExists"), null, 'errors'); + } else { + dol_print_error($db); + } + } + } - // Si verif ok et action modify, on modifie la ligne - if ($ok && GETPOST('actionmodify', 'alpha')) - { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + // Si verif ok et action modify, on modifie la ligne + if ($ok && GETPOST('actionmodify', 'alpha')) + { + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $db->begin(); + $db->begin(); - $website = new Website($db); - $rowid = GETPOST('rowid', 'int'); - $website->fetch($rowid); + $website = new Website($db); + $rowid = GETPOST('rowid', 'int'); + $website->fetch($rowid); - // Modify entry - $sql = "UPDATE ".$tabname[$id]." SET "; - // Modifie valeur des champs - if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) - { - $sql .= $tabrowid[$id]."="; - $sql .= "'".$db->escape($rowid)."', "; - } - $i = 0; - foreach ($listfieldmodify as $field) - { - if ($field == 'entity') { - $_POST[$listfieldvalue[$i]] = $conf->entity; - } - if ($i) $sql .= ","; - $sql .= $field."="; - if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; - else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; - $i++; - } - $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); + // Modify entry + $sql = "UPDATE ".$tabname[$id]." SET "; + // Modifie valeur des champs + if ($tabrowid[$id] && !in_array($tabrowid[$id], $listfieldmodify)) + { + $sql .= $tabrowid[$id]."="; + $sql .= "'".$db->escape($rowid)."', "; + } + $i = 0; + foreach ($listfieldmodify as $field) + { + if ($field == 'entity') { + $_POST[$listfieldvalue[$i]] = $conf->entity; + } + if ($i) $sql .= ","; + $sql .= $field."="; + if ($_POST[$listfieldvalue[$i]] == '') $sql .= "null"; + else $sql .= "'".$db->escape($_POST[$listfieldvalue[$i]])."'"; + $i++; + } + $sql .= " WHERE ".$rowidcol." = ".((int) $rowid); - dol_syslog("actionmodify", LOG_DEBUG); - //print $sql; - $resql = $db->query($sql); - if ($resql) - { - $newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09')); - if ($newname != $website->ref) - { - $srcfile = DOL_DATA_ROOT.'/website/'.$website->ref; - $destfile = DOL_DATA_ROOT.'/website/'.$newname; + dol_syslog("actionmodify", LOG_DEBUG); + //print $sql; + $resql = $db->query($sql); + if ($resql) + { + $newname = dol_sanitizeFileName(GETPOST('ref', 'aZ09')); + if ($newname != $website->ref) + { + $srcfile = DOL_DATA_ROOT.'/website/'.$website->ref; + $destfile = DOL_DATA_ROOT.'/website/'.$newname; - if (dol_is_dir($destfile)) - { - $error++; - setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors'); - } else { - @rename($srcfile, $destfile); + if (dol_is_dir($destfile)) + { + $error++; + setEventMessages($langs->trans('ErrorDirAlreadyExists', $destfile), null, 'errors'); + } else { + @rename($srcfile, $destfile); - // We must now rename $website->ref into $newname inside files - $arrayreplacement = array($website->ref.'/htmlheader.html' => $newname.'/htmlheader.html'); - $listofilestochange = dol_dir_list($destfile, 'files', 0, '\.php$'); + // We must now rename $website->ref into $newname inside files + $arrayreplacement = array($website->ref.'/htmlheader.html' => $newname.'/htmlheader.html'); + $listofilestochange = dol_dir_list($destfile, 'files', 0, '\.php$'); foreach ($listofilestochange as $key => $value) - { - dolReplaceInFile($value['fullname'], $arrayreplacement); - } - } - } - } else { - $error++; - setEventMessages($db->lasterror(), null, 'errors'); - } + { + dolReplaceInFile($value['fullname'], $arrayreplacement); + } + } + } + } else { + $error++; + setEventMessages($db->lasterror(), null, 'errors'); + } - if (!$error) - { - $db->commit(); - } else { - $db->rollback(); - } - } - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + if (!$error) + { + $db->commit(); + } else { + $db->rollback(); + } + } + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if (GETPOST('actioncancel', 'alpha')) { - //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition + //$_GET["id"]=GETPOST('id', 'int'); // Force affichage dictionnaire en cours d'edition } if ($action == 'confirm_delete' && $confirm == 'yes') // delete { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - $website = new Website($db); - $website->fetch($rowid); + $website = new Website($db); + $website->fetch($rowid); - if ($website->id > 0) - { - $sql = "DELETE from ".MAIN_DB_PREFIX."website_account WHERE fk_website = ".((int) $rowid); - $result = $db->query($sql); + if ($website->id > 0) + { + $sql = "DELETE from ".MAIN_DB_PREFIX."website_account WHERE fk_website = ".((int) $rowid); + $result = $db->query($sql); - $sql = "DELETE from ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $rowid); - $result = $db->query($sql); + $sql = "DELETE from ".MAIN_DB_PREFIX."website_page WHERE fk_website = ".((int) $rowid); + $result = $db->query($sql); - $sql = "DELETE from ".MAIN_DB_PREFIX."website_extrafields WHERE fk_object = ".((int) $rowid); - $result = $db->query($sql); + $sql = "DELETE from ".MAIN_DB_PREFIX."website_extrafields WHERE fk_object = ".((int) $rowid); + $result = $db->query($sql); - $sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $rowid); - $result = $db->query($sql); - if (!$result) - { - if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') - { - setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); - } else { - dol_print_error($db); - } - } + $sql = "DELETE from ".MAIN_DB_PREFIX."website WHERE rowid = ".((int) $rowid); + $result = $db->query($sql); + if (!$result) + { + if ($db->errno() == 'DB_ERROR_CHILD_EXISTS') + { + setEventMessages($langs->transnoentities("ErrorRecordIsUsedByChild"), null, 'errors'); + } else { + dol_print_error($db); + } + } - if ($website->ref) - { - dol_delete_dir_recursive($conf->website->dir_output.'/'.$website->ref); - } - } else { - dol_print_error($db, 'Failed to load website with id '.$rowid); - } + if ($website->ref) + { + dol_delete_dir_recursive($conf->website->dir_output.'/'.$website->ref); + } + } else { + dol_print_error($db, 'Failed to load website with id '.$rowid); + } } // activate if ($action == $acts[0]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid = ".((int) $rowid); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET status = 1 WHERE rowid = ".((int) $rowid); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } // disable if ($action == $acts[1]) { - if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } + if ($tabrowid[$id]) { $rowidcol = $tabrowid[$id]; } else { $rowidcol = "rowid"; } - if ($rowid) { - $sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid = ".((int) $rowid); - } + if ($rowid) { + $sql = "UPDATE ".$tabname[$id]." SET status = 0 WHERE rowid = ".((int) $rowid); + } - $result = $db->query($sql); - if (!$result) - { - dol_print_error($db); - } + $result = $db->query($sql); + if (!$result) + { + dol_print_error($db); + } } @@ -411,7 +411,7 @@ print "
\n"; // Confirmation de la suppression de la ligne if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid, $langs->trans('DeleteWebsite'), $langs->trans('ConfirmDeleteWebsite'), 'confirm_delete', '', 0, 1, 220); + print $form->formconfirm($_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.$rowid, $langs->trans('DeleteWebsite'), $langs->trans('ConfirmDeleteWebsite'), 'confirm_delete', '', 0, 1, 220); } //var_dump($elementList); @@ -420,205 +420,205 @@ if ($action == 'delete') */ if ($id) { - // Complete requete recherche valeurs avec critere de tri - $sql = $tabsql[$id]; - $sql .= $db->order($sortfield, $sortorder); - $sql .= $db->plimit($limit + 1, $offset); - //print $sql; + // Complete requete recherche valeurs avec critere de tri + $sql = $tabsql[$id]; + $sql .= $db->order($sortfield, $sortorder); + $sql .= $db->plimit($limit + 1, $offset); + //print $sql; - $fieldlist = explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); - print ''; - print ''; - print ''; + print ''; + print ''; + print '
'; - // Form to add a new line - if ($tabname[$id]) - { - $alabelisused = 0; - $var = false; + // Form to add a new line + if ($tabname[$id]) + { + $alabelisused = 0; + $var = false; - $fieldlist = explode(',', $tabfield[$id]); + $fieldlist = explode(',', $tabfield[$id]); - // Line for title - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow = $langs->trans($valuetoshow); // try to translate - $align = ''; - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($valuetoshow != '') - { - print ''; - } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; - } + // Line for title + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + $align = ''; + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } + if ($valuetoshow != '') + { + print ''; + } + if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') $alabelisused = 1; + } - print ''; - print ''; + print ''; + print ''; - // Line to enter new values - print ""; + // Line to enter new values + print ""; - $obj = new stdClass(); - // If data was already input, we define them in obj to populate input fields. - if (GETPOST('actionadd', 'alpha')) - { - foreach ($fieldlist as $key=>$val) - { - if (GETPOST($val, 'alpha')) - $obj->$val = GETPOST($val); - } - } + $obj = new stdClass(); + // If data was already input, we define them in obj to populate input fields. + if (GETPOST('actionadd', 'alpha')) + { + foreach ($fieldlist as $key=>$val) + { + if (GETPOST($val, 'alpha')) + $obj->$val = GETPOST($val); + } + } - fieldListWebsites($fieldlist, $obj, $tabname[$id], 'add'); + fieldListWebsites($fieldlist, $obj, $tabname[$id], 'add'); - print ''; - print ""; + print ''; + print ""; - $colspan = count($fieldlist) + 2; - } + $colspan = count($fieldlist) + 2; + } - print '
'; - if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; - elseif (!empty($tabhelp[$id][$value])) - { - if ($value == 'virtualhost') print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual'); - else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); - } else print $valuetoshow; - print '
'; + if (!empty($tabhelp[$id][$value]) && preg_match('/^http(s*):/i', $tabhelp[$id][$value])) print ''.$valuetoshow.' '.img_help(1, $valuetoshow).''; + elseif (!empty($tabhelp[$id][$value])) + { + if ($value == 'virtualhost') print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value], 1, 'help', '', 0, 2, 'tooltipvirtual'); + else print $form->textwithpicto($valuetoshow, $tabhelp[$id][$value]); + } else print $valuetoshow; + print ''; - print '
'; + print '
'; - if ($action != 'edit') - { - print ''; - } - print '
'; + if ($action != 'edit') + { + print ''; + } + print '
'; - print '
'; + print ''; + print ''; - // List of websites in database - $resql = $db->query($sql); - if ($resql) - { - $num = $db->num_rows($resql); - $i = 0; - if ($num) - { - print '
'; + // List of websites in database + $resql = $db->query($sql); + if ($resql) + { + $num = $db->num_rows($resql); + $i = 0; + if ($num) + { + print '
'; - print '
'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; + print '
'; - // Title of lines - print ''; - foreach ($fieldlist as $field => $value) - { - // Determine le nom du champ par rapport aux noms possibles - // dans les dictionnaires de donnees - $showfield = 1; // Par defaut - $align = "left"; - $sortable = 1; - $valuetoshow = ''; - /* + // Title of lines + print ''; + foreach ($fieldlist as $field => $value) + { + // Determine le nom du champ par rapport aux noms possibles + // dans les dictionnaires de donnees + $showfield = 1; // Par defaut + $align = "left"; + $sortable = 1; + $valuetoshow = ''; + /* $tmparray=getLabelOfField($fieldlist[$field]); $showfield=$tmp['showfield']; $valuetoshow=$tmp['valuetoshow']; $align=$tmp['align']; $sortable=$tmp['sortable']; */ - $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut - $valuetoshow = $langs->trans($valuetoshow); // try to translate - if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } - if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } - if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } + $valuetoshow = ucfirst($fieldlist[$field]); // Par defaut + $valuetoshow = $langs->trans($valuetoshow); // try to translate + if ($fieldlist[$field] == 'lang') { $valuetoshow = $langs->trans("Language"); } + if ($fieldlist[$field] == 'type') { $valuetoshow = $langs->trans("Type"); } + if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } - // Affiche nom du champ - if ($showfield) - { - print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder); - } - } + // Affiche nom du champ + if ($showfield) + { + print getTitleFieldOfList($valuetoshow, 0, $_SERVER["PHP_SELF"], ($sortable ? $fieldlist[$field] : ''), ($page ? 'page='.$page.'&' : ''), "", "align=".$align, $sortfield, $sortorder); + } + } print getTitleFieldOfList($langs->trans("Status"), 0, $_SERVER["PHP_SELF"], "status", ($page ? 'page='.$page.'&' : ''), "", 'align="center"', $sortfield, $sortorder); - print getTitleFieldOfList(''); - print getTitleFieldOfList(''); - print ''; + print getTitleFieldOfList(''); + print getTitleFieldOfList(''); + print ''; - // Lines with values - while ($i < $num) - { - $obj = $db->fetch_object($resql); - //print_r($obj); - print ''; - if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) - { - $tmpaction = 'edit'; - $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('editWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + // Lines with values + while ($i < $num) + { + $obj = $db->fetch_object($resql); + //print_r($obj); + print ''; + if ($action == 'edit' && ($rowid == (!empty($obj->rowid) ? $obj->rowid : $obj->code))) + { + $tmpaction = 'edit'; + $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('editWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) fieldListWebsites($fieldlist, $obj, $tabname[$id], 'edit'); + if (empty($reshook)) fieldListWebsites($fieldlist, $obj, $tabname[$id], 'edit'); - print ''; - } else { - $tmpaction = 'view'; - $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); - $reshook = $hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks + print ''; + } else { + $tmpaction = 'view'; + $parameters = array('var'=>$var, 'fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); + $reshook = $hookmanager->executeHooks('viewWebsiteFieldlist', $parameters, $obj, $tmpaction); // Note that $action and $object may have been modified by some hooks - $error = $hookmanager->error; $errors = $hookmanager->errors; + $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) - { - foreach ($fieldlist as $field => $value) - { - $showfield = 1; - $align = "left"; - $fieldname = $fieldlist[$field]; - $valuetoshow = $obj->$fieldname; + if (empty($reshook)) + { + foreach ($fieldlist as $field => $value) + { + $showfield = 1; + $align = "left"; + $fieldname = $fieldlist[$field]; + $valuetoshow = $obj->$fieldname; // Show value for field if ($showfield) print ''; - } - } + } + } - // Can an entry be erased or disabled ? - $iserasable = 1; $isdisable = 1; // true by default - if ($obj->status) $iserasable = 0; // We can't delete a website on. Disable it first. + // Can an entry be erased or disabled ? + $iserasable = 1; $isdisable = 1; // true by default + if ($obj->status) $iserasable = 0; // We can't delete a website on. Disable it first. - $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '').'&'; + $url = $_SERVER["PHP_SELF"].'?'.($page ? 'page='.$page.'&' : '').'sortfield='.$sortfield.'&sortorder='.$sortorder.'&rowid='.(!empty($obj->rowid) ? $obj->rowid : (!empty($obj->code) ? $obj->code : '')).'&code='.(!empty($obj->code) ?urlencode($obj->code) : '').'&'; - // Active - print '"; + // Active + print '"; - // Modify link - print ''; + // Modify link + print ''; - // Delete link - if ($iserasable) print ''; - else print ''; + // Delete link + if ($iserasable) print ''; + else print ''; - print "\n"; - } - $i++; - } + print "\n"; + } + $i++; + } - print '
 '; - print '  '; + print ' '.$valuetoshow.''; - print ''.$actl[($obj->status ? 1 : 0)].''; - print "'; + print ''.$actl[($obj->status ? 1 : 0)].''; + print "'.img_edit().''.img_edit().''.img_delete().''.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').''.img_delete().''.img_delete($langs->trans("DisableSiteFirst"), 'class="opacitymedium"').'
'; + print ''; - print '
'; - } - } else { - dol_print_error($db); - } + print ''; + } + } else { + dol_print_error($db); + } } dol_fiche_end(); @@ -649,7 +649,7 @@ function fieldListWebsites($fieldlist, $obj = '', $tabname = '', $context = '') foreach ($fieldlist as $field => $value) { - $fieldname = $fieldlist[$field]; + $fieldname = $fieldlist[$field]; if ($fieldlist[$field] == 'lang') { print ''; diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index fbe5e7b1872..8177fbf7e1e 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -35,1865 +35,1865 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php'; */ class Setup extends DolibarrApi { - private $translations = null; - - /** - * Constructor - */ - public function __construct() - { - global $db; - $this->db = $db; - } - - /** - * Get the list of ordering methods. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Payment type is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'OrderByWWW')" - * - * @url GET dictionary/ordering_methods - * - * @return array [List of ordering methods] - * - * @throws RestException 400 - */ - public function getOrderingMethods($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->rights->commande->lire) { - throw new RestException(401); - } - - $sql = "SELECT rowid, code, libelle as label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, '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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of payments types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Payment type is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')" - * - * @url GET dictionary/payment_types - * - * @return array [List of payment types] - * - * @throws RestException 400 - */ - public function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } - - $sql = "SELECT id, code, type, libelle as label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_paiement').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, '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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of states/provinces. - * - * The names of the states will be translated to the given language if - * the $lang parameter is provided. The value of $lang must be a language - * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. - * The returned list is sorted by state ID. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $filter To filter the countries by name - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of countries - * - * @url GET dictionary/states - * - * @throws RestException - */ - public function getListOfStates($sortfield = "code_departement", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $sqlfilters = '') - { - $list = array(); - - // Note: The filter is not applied in the SQL request because it must - // be applied to the translated names, not to the names in database. - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_departements as t"; - $sql .= " WHERE 1 = 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, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $obj = $this->db->fetch_object($result); - $state = new Cstate($this->db); - if ($state->fetch($obj->rowid) > 0) { - if (empty($filter) || stripos($state->label, $filter) !== false) { - $list[] = $this->_cleanObjectDatas($state); - } - } - } - } else { - throw new RestException(503, 'Error when retrieving list of states'); - } - - return $list; - } - - /** - * Get state by ID. - * - * @param int $id ID of state - * @return array Array of cleaned object properties - * - * @url GET dictionary/states/{id} - * - * @throws RestException - */ - public function getStateByID($id) - { - return $this->_fetchCstate($id, ''); - } - - /** - * Get state by Code. - * - * @param string $code Code of state - * @return array Array of cleaned object properties - * - * @url GET dictionary/states/byCode/{code} - * - * @throws RestException - */ - public function getStateByCode($code) - { - return $this->_fetchCstate('', $code); - } - - /** - * Get the list of countries. - * - * The names of the countries will be translated to the given language if - * the $lang parameter is provided. The value of $lang must be a language - * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. - * The returned list is sorted by country ID. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $filter To filter the countries by name - * @param string $lang Code of the language the label of the countries must be translated to - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of countries - * - * @url GET dictionary/countries - * - * @throws RestException - */ - public function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') - { - $list = array(); - - // Note: The filter is not applied in the SQL request because it must - // be applied to the translated names, not to the names in database. - $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; - $sql .= " WHERE 1 = 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, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $obj = $this->db->fetch_object($result); - $country = new Ccountry($this->db); - if ($country->fetch($obj->rowid) > 0) { - // Translate the name of the country if needed - // and then apply the filter if there is one. - $this->translateLabel($country, $lang, 'Country'); - - if (empty($filter) || stripos($country->label, $filter) !== false) { - $list[] = $this->_cleanObjectDatas($country); - } - } - } - } else { - throw new RestException(503, 'Error when retrieving list of countries'); - } - - return $list; - } - - /** - * Get country by ID. - * - * @param int $id ID of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @url GET dictionary/countries/{id} - * - * @throws RestException - */ - public function getCountryByID($id, $lang = '') - { - return $this->_fetchCcountry($id, '', '', $lang); - } - - /** - * Get country by Code. - * - * @param string $code Code of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @url GET dictionary/countries/byCode/{code} - * - * @throws RestException - */ - public function getCountryByCode($code, $lang = '') - { - return $this->_fetchCcountry('', $code, '', $lang); - } - - /** - * Get country by Iso. - * - * @param string $iso ISO of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @url GET dictionary/countries/byISO/{iso} - * - * @throws RestException - */ - public function getCountryByISO($iso, $lang = '') - { - return $this->_fetchCcountry('', '', $iso, $lang); - } - - /** - * Get state. - * - * @param int $id ID of state - * @param string $code Code of state - * @return array Array of cleaned object properties - * - * @throws RestException - */ - private function _fetchCstate($id, $code = '') - { - $state = new Cstate($this->db); - - $result = $state->fetch($id, $code); - if ($result < 0) { - throw new RestException(503, 'Error when retrieving state : '.$state->error); - } elseif ($result == 0) { - throw new RestException(404, 'State not found'); - } - - return $this->_cleanObjectDatas($state); - } - - /** - * Get country. - * - * @param int $id ID of country - * @param string $code Code of country - * @param string $iso ISO of country - * @param string $lang Code of the language the name of the - * country must be translated to - * @return array Array of cleaned object properties - * - * @throws RestException - */ - private function _fetchCcountry($id, $code = '', $iso = '', $lang = '') - { - $country = new Ccountry($this->db); - - $result = $country->fetch($id, $code, $iso); - if ($result < 0) { - throw new RestException(503, 'Error when retrieving country : '.$country->error); - } elseif ($result == 0) { - throw new RestException(404, 'country not found'); - } - - $this->translateLabel($country, $lang, 'Country'); - - return $this->_cleanObjectDatas($country); - } - - /** - * Get the list of delivery times. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Delivery times is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter with. - * - * @url GET dictionary/availability - * - * @return array [List of availability] - * - * @throws RestException 400 - */ - public function getAvailability($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->rights->commande->lire) { - throw new RestException(401); - } - - $sql = "SELECT rowid, code, label"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_availability as t"; - $sql .= " WHERE t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, '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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param object $object Object to clean - * @return array Array of cleaned object properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); - - unset($object->error); - unset($object->errors); - - return $object; - } - - /** - * Translate the name of the object to the given language. - * - * @param object $object Object with label to translate - * @param string $lang Code of the language the name of the object must be translated to - * @param string $prefix Prefix for translation key - * - * @return void - */ - private function translateLabel($object, $lang, $prefix = 'Country') - { - if (!empty($lang)) { - // Load the translations if this is a new language. - if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { - global $conf; - $this->translations = new Translate('', $conf); - $this->translations->setDefaultLang($lang); - $this->translations->load('dict'); - } - if ($object->code) { - $key = $prefix.$object->code; - - $translation = $this->translations->trans($key); - if ($translation != $key) { - $object->label = html_entity_decode($translation); - } - } - } - } - - /** - * Get the list of shipment methods. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * - * @return array List of shipment methods - * - * @url GET dictionary/shipment_methods - * - * @throws RestException - */ - public function getListOfShipmentMethods($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - $sql = "SELECT t.rowid, t.code, t.libelle, t.description, t.tracking"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; - $sql .= " WHERE t.active = ".$active; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of shipment methods : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of events types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $type To filter on type of event - * @param string $module To filter on module events - * @param int $active Event's type is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of events types - * - * @url GET dictionary/event_types - * - * @throws RestException - */ - public function getListOfEventTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT id, code, type, libelle as label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; - $sql .= " WHERE t.active = ".$active; - if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); - } - - return $list; - } - - - /** - * Get the list of Expense Report types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $module To filter on module - * @param int $active Event's type is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of expense report types - * - * @url GET dictionary/expensereport_types - * - * @throws RestException - */ - public function getListOfExpenseReportsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT id, code, label, accountancy_code, active, module, position"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as t"; - $sql .= " WHERE t.active = ".$active; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of expense report types : '.$this->db->lasterror()); - } - - return $list; - } - - - /** - * Get the list of contacts types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $type To filter on type of contact - * @param string $module To filter on module contacts - * @param int $active Contact's type is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of Contacts types - * - * @url GET dictionary/contact_types - * - * @throws RestException - */ - public function getListOfContactTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, element as type, libelle as label, source, module, position"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as t"; - $sql .= " WHERE t.active = ".$active; - if ($type) $sql .= " AND type LIKE '%".$this->db->escape($type)."%'"; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of contacts types : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of civilities. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $module To filter on module events - * @param int $active Civility is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of civility types - * - * @url GET dictionary/civilities - * - * @throws RestException - */ - public function getListOfCivilities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, label, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_civility as t"; - $sql .= " WHERE t.active = ".$active; - if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of civility : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of currencies. - * - * @param int $multicurrency Multicurrency rates (0: no multicurrency, 1: last rate, 2: all rates) {@min 0} {@max 2} - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of currencies - * - * @url GET dictionary/currencies - * - * @throws RestException - */ - public function getListOfCurrencies($multicurrency = 0, $sortfield = "code_iso", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - $sql = "SELECT t.code_iso, t.label, t.unicode"; - if (!empty($multicurrency)) $sql .= " , cr.date_sync, cr.rate "; - $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies as t"; - if (!empty($multicurrency)) { - $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso"; - $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)"; - } - $sql .= " WHERE t.active = ".$active; - if (!empty($multicurrency)) { - $sql .= " AND m.entity IN (".getEntity('multicurrency').")"; - if (!empty($multicurrency) && $multicurrency != 2) { - $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.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->plimit($limit, $offset); - } - - $result = $this->db->query($sql); - - if ($result) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of currency : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of extra fields. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" - * @return array List of extra fields - * - * @url GET extrafields - * - * @throws RestException - */ - public function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->admin) { - throw new RestException(401, 'Only an admin user can get list of extrafields'); - } - - if ($type == 'thirdparty') $type = 'societe'; - if ($type == 'contact') $type = 'socpeople'; - - $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed"; - $sql .= " FROM ".MAIN_DB_PREFIX."extrafields as t"; - $sql .= " WHERE t.entity IN (".getEntity('extrafields').")"; - if (!empty($type)) $sql .= " AND t.elementtype = '".$this->db->escape($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).")"; - } - - $sql .= $this->db->order($sortfield, $sortorder); - - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - while ($tab = $this->db->fetch_object($resql)) - { - // New usage - $list[$tab->elementtype][$tab->name]['type'] = $tab->type; - $list[$tab->elementtype][$tab->name]['label'] = $tab->label; - $list[$tab->elementtype][$tab->name]['size'] = $tab->size; - $list[$tab->elementtype][$tab->name]['elementtype'] = $tab->elementtype; - $list[$tab->elementtype][$tab->name]['default'] = $tab->fielddefault; - $list[$tab->elementtype][$tab->name]['computed'] = $tab->fieldcomputed; - $list[$tab->elementtype][$tab->name]['unique'] = $tab->fieldunique; - $list[$tab->elementtype][$tab->name]['required'] = $tab->fieldrequired; - $list[$tab->elementtype][$tab->name]['param'] = ($tab->param ? unserialize($tab->param) : ''); - $list[$tab->elementtype][$tab->name]['pos'] = $tab->pos; - $list[$tab->elementtype][$tab->name]['alwayseditable'] = $tab->alwayseditable; - $list[$tab->elementtype][$tab->name]['perms'] = $tab->perms; - $list[$tab->elementtype][$tab->name]['list'] = $tab->list; - } - } - } else { - throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); - } - - if (!count($list)) - { - throw new RestException(404, 'No extrafield found'); - } - - return $list; - } - - - /** - * Get the list of towns. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param string $zipcode To filter on zipcode - * @param string $town To filter on city name - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of towns - * - * @url GET dictionary/towns - * - * @throws RestException - */ - public function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; - $sql .= " AND t.active = ".$active; - if ($zipcode) $sql .= " AND t.zip LIKE '%".$this->db->escape($zipcode)."%'"; - if ($town) $sql .= " AND t.town LIKE '%".$this->db->escape($town)."%'"; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of payments terms. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" - * - * @url GET dictionary/payment_terms - * - * @return array List of payment terms - * - * @throws RestException 400 - */ - public function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { - throw new RestException(401); - } - - $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_payment_term').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, '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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of shipping methods. - * - * @param int $limit Number of items per page - * @param int $page Page number {@min 0} - * @param int $active Shipping methodsm is active or not {@min 0} {@max 1} - * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" - * - * @url GET dictionary/shipping_methods - * - * @return array List of shipping methods - * - * @throws RestException 400 - */ - public function getShippingModes($limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid as id, code, libelle as label, description, tracking, module"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_shipment_mode').")"; - $sql .= " AND t.active = ".$active; - // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { - throw new RestException(400, '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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(400, $this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of measuring units. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Measuring unit is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of measuring unit - * - * @url GET dictionary/units - * - * @throws RestException - */ - public function getListOfMeasuringUnits($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - //TODO link with multicurrency module - $sql = "SELECT t.rowid, t.code, t.label,t.short_label, t.active, t.scale, t.unit_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; - $sql .= " WHERE t.active = ".$active; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of measuring units: '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of social networks. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Social network is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of social networks - * - * @url GET dictionary/socialnetworks - * - * @throws RestException - */ - public function getListOfsocialNetworks($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - global $conf; - - if (empty($conf->socialnetworks->enabled)) { - throw new RestException(400, 'API not available: this dictionary is not enabled by setup'); - } + private $translations = null; + + /** + * Constructor + */ + public function __construct() + { + global $db; + $this->db = $db; + } + + /** + * Get the list of ordering methods. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment type is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'OrderByWWW')" + * + * @url GET dictionary/ordering_methods + * + * @return array [List of ordering methods] + * + * @throws RestException 400 + */ + public function getOrderingMethods($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid, code, libelle as label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_input_method as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, '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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of payments types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment type is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')" + * + * @url GET dictionary/payment_types + * + * @return array [List of payment types] + * + * @throws RestException 400 + */ + public function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_paiement as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_paiement').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, '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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of states/provinces. + * + * The names of the states will be translated to the given language if + * the $lang parameter is provided. The value of $lang must be a language + * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. + * The returned list is sorted by state ID. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $filter To filter the countries by name + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of countries + * + * @url GET dictionary/states + * + * @throws RestException + */ + public function getListOfStates($sortfield = "code_departement", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $sqlfilters = '') + { + $list = array(); + + // Note: The filter is not applied in the SQL request because it must + // be applied to the translated names, not to the names in database. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_departements as t"; + $sql .= " WHERE 1 = 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, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $obj = $this->db->fetch_object($result); + $state = new Cstate($this->db); + if ($state->fetch($obj->rowid) > 0) { + if (empty($filter) || stripos($state->label, $filter) !== false) { + $list[] = $this->_cleanObjectDatas($state); + } + } + } + } else { + throw new RestException(503, 'Error when retrieving list of states'); + } + + return $list; + } + + /** + * Get state by ID. + * + * @param int $id ID of state + * @return array Array of cleaned object properties + * + * @url GET dictionary/states/{id} + * + * @throws RestException + */ + public function getStateByID($id) + { + return $this->_fetchCstate($id, ''); + } + + /** + * Get state by Code. + * + * @param string $code Code of state + * @return array Array of cleaned object properties + * + * @url GET dictionary/states/byCode/{code} + * + * @throws RestException + */ + public function getStateByCode($code) + { + return $this->_fetchCstate('', $code); + } + + /** + * Get the list of countries. + * + * The names of the countries will be translated to the given language if + * the $lang parameter is provided. The value of $lang must be a language + * code supported by Dolibarr, for example 'en_US' or 'fr_FR'. + * The returned list is sorted by country ID. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $filter To filter the countries by name + * @param string $lang Code of the language the label of the countries must be translated to + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of countries + * + * @url GET dictionary/countries + * + * @throws RestException + */ + public function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '') + { + $list = array(); + + // Note: The filter is not applied in the SQL request because it must + // be applied to the translated names, not to the names in database. + $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t"; + $sql .= " WHERE 1 = 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, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $obj = $this->db->fetch_object($result); + $country = new Ccountry($this->db); + if ($country->fetch($obj->rowid) > 0) { + // Translate the name of the country if needed + // and then apply the filter if there is one. + $this->translateLabel($country, $lang, 'Country'); + + if (empty($filter) || stripos($country->label, $filter) !== false) { + $list[] = $this->_cleanObjectDatas($country); + } + } + } + } else { + throw new RestException(503, 'Error when retrieving list of countries'); + } + + return $list; + } + + /** + * Get country by ID. + * + * @param int $id ID of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @url GET dictionary/countries/{id} + * + * @throws RestException + */ + public function getCountryByID($id, $lang = '') + { + return $this->_fetchCcountry($id, '', '', $lang); + } + + /** + * Get country by Code. + * + * @param string $code Code of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @url GET dictionary/countries/byCode/{code} + * + * @throws RestException + */ + public function getCountryByCode($code, $lang = '') + { + return $this->_fetchCcountry('', $code, '', $lang); + } + + /** + * Get country by Iso. + * + * @param string $iso ISO of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @url GET dictionary/countries/byISO/{iso} + * + * @throws RestException + */ + public function getCountryByISO($iso, $lang = '') + { + return $this->_fetchCcountry('', '', $iso, $lang); + } + + /** + * Get state. + * + * @param int $id ID of state + * @param string $code Code of state + * @return array Array of cleaned object properties + * + * @throws RestException + */ + private function _fetchCstate($id, $code = '') + { + $state = new Cstate($this->db); + + $result = $state->fetch($id, $code); + if ($result < 0) { + throw new RestException(503, 'Error when retrieving state : '.$state->error); + } elseif ($result == 0) { + throw new RestException(404, 'State not found'); + } + + return $this->_cleanObjectDatas($state); + } + + /** + * Get country. + * + * @param int $id ID of country + * @param string $code Code of country + * @param string $iso ISO of country + * @param string $lang Code of the language the name of the + * country must be translated to + * @return array Array of cleaned object properties + * + * @throws RestException + */ + private function _fetchCcountry($id, $code = '', $iso = '', $lang = '') + { + $country = new Ccountry($this->db); + + $result = $country->fetch($id, $code, $iso); + if ($result < 0) { + throw new RestException(503, 'Error when retrieving country : '.$country->error); + } elseif ($result == 0) { + throw new RestException(404, 'country not found'); + } + + $this->translateLabel($country, $lang, 'Country'); + + return $this->_cleanObjectDatas($country); + } + + /** + * Get the list of delivery times. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Delivery times is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter with. + * + * @url GET dictionary/availability + * + * @return array [List of availability] + * + * @throws RestException 400 + */ + public function getAvailability($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->commande->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid, code, label"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_availability as t"; + $sql .= " WHERE t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, '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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); + + unset($object->error); + unset($object->errors); + + return $object; + } + + /** + * Translate the name of the object to the given language. + * + * @param object $object Object with label to translate + * @param string $lang Code of the language the name of the object must be translated to + * @param string $prefix Prefix for translation key + * + * @return void + */ + private function translateLabel($object, $lang, $prefix = 'Country') + { + if (!empty($lang)) { + // Load the translations if this is a new language. + if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) { + global $conf; + $this->translations = new Translate('', $conf); + $this->translations->setDefaultLang($lang); + $this->translations->load('dict'); + } + if ($object->code) { + $key = $prefix.$object->code; + + $translation = $this->translations->trans($key); + if ($translation != $key) { + $object->label = html_entity_decode($translation); + } + } + } + } + + /** + * Get the list of shipment methods. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * + * @return array List of shipment methods + * + * @url GET dictionary/shipment_methods + * + * @throws RestException + */ + public function getListOfShipmentMethods($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + $sql = "SELECT t.rowid, t.code, t.libelle, t.description, t.tracking"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; + $sql .= " WHERE t.active = ".$active; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of shipment methods : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of events types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $type To filter on type of event + * @param string $module To filter on module events + * @param int $active Event's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of events types + * + * @url GET dictionary/event_types + * + * @throws RestException + */ + public function getListOfEventTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, type, libelle as label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t"; + $sql .= " WHERE t.active = ".$active; + if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror()); + } + + return $list; + } + + + /** + * Get the list of Expense Report types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $module To filter on module + * @param int $active Event's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of expense report types + * + * @url GET dictionary/expensereport_types + * + * @throws RestException + */ + public function getListOfExpenseReportsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT id, code, label, accountancy_code, active, module, position"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as t"; + $sql .= " WHERE t.active = ".$active; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of expense report types : '.$this->db->lasterror()); + } + + return $list; + } + + + /** + * Get the list of contacts types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $type To filter on type of contact + * @param string $module To filter on module contacts + * @param int $active Contact's type is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of Contacts types + * + * @url GET dictionary/contact_types + * + * @throws RestException + */ + public function getListOfContactTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, element as type, libelle as label, source, module, position"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_type_contact as t"; + $sql .= " WHERE t.active = ".$active; + if ($type) $sql .= " AND type LIKE '%".$this->db->escape($type)."%'"; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of contacts types : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of civilities. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $module To filter on module events + * @param int $active Civility is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of civility types + * + * @url GET dictionary/civilities + * + * @throws RestException + */ + public function getListOfCivilities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $module = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, label, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_civility as t"; + $sql .= " WHERE t.active = ".$active; + if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of civility : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of currencies. + * + * @param int $multicurrency Multicurrency rates (0: no multicurrency, 1: last rate, 2: all rates) {@min 0} {@max 2} + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of currencies + * + * @url GET dictionary/currencies + * + * @throws RestException + */ + public function getListOfCurrencies($multicurrency = 0, $sortfield = "code_iso", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + $sql = "SELECT t.code_iso, t.label, t.unicode"; + if (!empty($multicurrency)) $sql .= " , cr.date_sync, cr.rate "; + $sql .= " FROM ".MAIN_DB_PREFIX."c_currencies as t"; + if (!empty($multicurrency)) { + $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency as m ON m.code=t.code_iso"; + $sql .= " JOIN ".MAIN_DB_PREFIX."multicurrency_rate as cr ON (m.rowid = cr.fk_multicurrency)"; + } + $sql .= " WHERE t.active = ".$active; + if (!empty($multicurrency)) { + $sql .= " AND m.entity IN (".getEntity('multicurrency').")"; + if (!empty($multicurrency) && $multicurrency != 2) { + $sql .= " AND cr.date_sync = (SELECT MAX(cr2.date_sync) FROM ".MAIN_DB_PREFIX."multicurrency_rate AS cr2 WHERE cr2.fk_multicurrency = m.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->plimit($limit, $offset); + } + + $result = $this->db->query($sql); + + if ($result) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of currency : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of extra fields. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param string $type Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...) + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')" + * @return array List of extra fields + * + * @url GET extrafields + * + * @throws RestException + */ + public function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->admin) { + throw new RestException(401, 'Only an admin user can get list of extrafields'); + } + + if ($type == 'thirdparty') $type = 'societe'; + if ($type == 'contact') $type = 'socpeople'; + + $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed"; + $sql .= " FROM ".MAIN_DB_PREFIX."extrafields as t"; + $sql .= " WHERE t.entity IN (".getEntity('extrafields').")"; + if (!empty($type)) $sql .= " AND t.elementtype = '".$this->db->escape($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).")"; + } + + $sql .= $this->db->order($sortfield, $sortorder); + + $resql = $this->db->query($sql); + if ($resql) + { + if ($this->db->num_rows($resql)) + { + while ($tab = $this->db->fetch_object($resql)) + { + // New usage + $list[$tab->elementtype][$tab->name]['type'] = $tab->type; + $list[$tab->elementtype][$tab->name]['label'] = $tab->label; + $list[$tab->elementtype][$tab->name]['size'] = $tab->size; + $list[$tab->elementtype][$tab->name]['elementtype'] = $tab->elementtype; + $list[$tab->elementtype][$tab->name]['default'] = $tab->fielddefault; + $list[$tab->elementtype][$tab->name]['computed'] = $tab->fieldcomputed; + $list[$tab->elementtype][$tab->name]['unique'] = $tab->fieldunique; + $list[$tab->elementtype][$tab->name]['required'] = $tab->fieldrequired; + $list[$tab->elementtype][$tab->name]['param'] = ($tab->param ? unserialize($tab->param) : ''); + $list[$tab->elementtype][$tab->name]['pos'] = $tab->pos; + $list[$tab->elementtype][$tab->name]['alwayseditable'] = $tab->alwayseditable; + $list[$tab->elementtype][$tab->name]['perms'] = $tab->perms; + $list[$tab->elementtype][$tab->name]['list'] = $tab->list; + } + } + } else { + throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); + } + + if (!count($list)) + { + throw new RestException(404, 'No extrafield found'); + } + + return $list; + } + + + /** + * Get the list of towns. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param string $zipcode To filter on zipcode + * @param string $town To filter on city name + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of towns + * + * @url GET dictionary/towns + * + * @throws RestException + */ + public function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ziptown as t"; + $sql .= " AND t.active = ".$active; + if ($zipcode) $sql .= " AND t.zip LIKE '%".$this->db->escape($zipcode)."%'"; + if ($town) $sql .= " AND t.town LIKE '%".$this->db->escape($town)."%'"; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of payments terms. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" + * + * @url GET dictionary/payment_terms + * + * @return array List of payment terms + * + * @throws RestException 400 + */ + public function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + if (!DolibarrApiAccess::$user->rights->propal->lire && !DolibarrApiAccess::$user->rights->commande->lire && !DolibarrApiAccess::$user->rights->facture->lire) { + throw new RestException(401); + } + + $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_payment_term as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_payment_term').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, '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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of shipping methods. + * + * @param int $limit Number of items per page + * @param int $page Page number {@min 0} + * @param int $active Shipping methodsm is active or not {@min 0} {@max 1} + * @param string $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')" + * + * @url GET dictionary/shipping_methods + * + * @return array List of shipping methods + * + * @throws RestException 400 + */ + public function getShippingModes($limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid as id, code, libelle as label, description, tracking, module"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_shipment_mode as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_shipment_mode').")"; + $sql .= " AND t.active = ".$active; + // Add sql filters + if ($sqlfilters) + { + if (!DolibarrApi::_checkFilters($sqlfilters)) + { + throw new RestException(400, '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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(400, $this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of measuring units. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Measuring unit is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of measuring unit + * + * @url GET dictionary/units + * + * @throws RestException + */ + public function getListOfMeasuringUnits($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + //TODO link with multicurrency module + $sql = "SELECT t.rowid, t.code, t.label,t.short_label, t.active, t.scale, t.unit_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_units as t"; + $sql .= " WHERE t.active = ".$active; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of measuring units: '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of social networks. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Social network is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of social networks + * + * @url GET dictionary/socialnetworks + * + * @throws RestException + */ + public function getListOfsocialNetworks($sortfield = "rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + global $conf; + + if (empty($conf->socialnetworks->enabled)) { + throw new RestException(400, 'API not available: this dictionary is not enabled by setup'); + } $list = array(); - //TODO link with multicurrency module - $sql = "SELECT t.rowid, t.entity, t.code, t.label, t.url, t.icon, t.active"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_socialnetworks as t"; - $sql .= " WHERE t.entity IN (".getEntity('c_socialnetworks').")"; - $sql .= " AND t.active = ".$active; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of social networks: '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of tickets categories. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of ticket categories - * - * @url GET dictionary/ticket_categories - * - * @throws RestException - */ - public function getTicketsCategories($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, pos, label, use_default, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t"; - $sql .= " WHERE t.active = ".$active; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of ticket categories : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of tickets severity. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of ticket severities - * - * @url GET dictionary/ticket_severities - * - * @throws RestException - */ - public function getTicketsSeverities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, pos, label, use_default, color, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t"; - $sql .= " WHERE t.active = ".$active; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of ticket severities : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get the list of tickets types. - * - * @param string $sortfield Sort field - * @param string $sortorder Sort order - * @param int $limit Number of items per page - * @param int $page Page number (starting from zero) - * @param int $active Payment term is active or not {@min 0} {@max 1} - * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" - * @return array List of ticket types - * - * @url GET dictionary/ticket_types - * - * @throws RestException - */ - public function getTicketsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') - { - $list = array(); - - $sql = "SELECT rowid, code, pos, label, use_default, description"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t"; - $sql .= " WHERE t.active = ".(int) $active; - // if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; - // if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; - // 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) { - $num = $this->db->num_rows($result); - $min = min($num, ($limit <= 0 ? $num : $limit)); - for ($i = 0; $i < $min; $i++) { - $list[] = $this->db->fetch_object($result); - } - } else { - throw new RestException(503, 'Error when retrieving list of ticket types : '.$this->db->lasterror()); - } - - return $list; - } - - /** - * Get properties of company - * - * @url GET /company - * - * @return array|mixed Data without useless information - * - */ - public function getCompany() - { - global $mysoc; - - return $this->_cleanObjectDatas($mysoc); - } - - - /** - * Get value of a setup variables - * - * Note that conf variables that stores security key or password hashes can't be loaded with API. - * - * @param string $constantname Name of conf variable to get - * @return array|mixed Data without useless information - * - * @url GET conf/{constantname} - * - * @throws RestException 403 Forbidden - * @throws RestException 404 Error Bad or unknown value for constantname - */ - public function getConf($constantname) - { - global $conf; - - if (!DolibarrApiAccess::$user->admin - && (empty($conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ) || DolibarrApiAccess::$user->login != $conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ)) { - throw new RestException(403, 'Error API open to admin users only or to the users with logins defined into constant API_LOGINS_ALLOWED_FOR_CONST_READ'); - } - - if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) { - throw new RestException(404, 'Error Bad or unknown value for constantname'); - } - if (isASecretKey($constantname)) { - throw new RestException(403, 'Forbidden. This parameter cant be read with APIs'); - } - - return $conf->global->$constantname; - } - - /** - * Do a test of integrity for files and setup. - * - * @param string $target Can be 'local' or 'default' or Url of the signatures file to use for the test. Must be reachable by the tested Dolibarr. - * @return array Result of file and setup integrity check - * - * @url GET checkintegrity - * - * @throws RestException 404 Signature file not found - * @throws RestException 500 Technical error - * @throws RestException 503 Forbidden - */ - public function getCheckIntegrity($target) - { - global $langs, $conf; - - if (!DolibarrApiAccess::$user->admin - && (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK)) - { - throw new RestException(503, 'Error API open to admin users only or to the users with logins defined into constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK'); - } - - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; - - $langs->load("admin"); - - $outexpectedchecksum = ''; - $outcurrentchecksum = ''; - - // Modified or missing files - $file_list = array('missing' => array(), 'updated' => array()); - - // Local file to compare to - $xmlshortfile = GETPOST('xmlshortfile') ?GETPOST('xmlshortfile') : '/install/filelist-'.DOL_VERSION.'.xml'; - $xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; - // Remote file to compare to - $xmlremote = ($target == 'default' ? '' : $target); - if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; - $param = 'MAIN_FILECHECK_URL_'.DOL_VERSION; - if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param; - if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; - - if ($target == 'local') - { - if (dol_is_file($xmlfile)) - { - $xml = simplexml_load_file($xmlfile); - } else { - throw new RestException(500, $langs->trans('XmlNotFound').': '.$xmlfile); - } - } else { - $xmlarray = getURLContent($xmlremote); - - // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) - if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') - { - $xmlfile = $xmlarray['content']; - //print "xmlfilestart".$xmlfile."endxmlfile"; - $xml = simplexml_load_string($xmlfile); - } else { - $errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; - throw new RestException(500, $errormsg); - } - } - - - - if ($xml) - { - $checksumconcat = array(); - $file_list = array(); - $out = ''; - - // Forced constants - if (is_object($xml->dolibarr_constants[0])) - { - $out .= load_fiche_titre($langs->trans("ForcedConstants")); - - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - - $i = 0; - foreach ($xml->dolibarr_constants[0]->constant as $constant) // $constant is a simpleXMLElement - { - $constname = $constant['name']; - $constvalue = (string) $constant; - $constvalue = (empty($constvalue) ? '0' : $constvalue); - // Value found - $value = ''; - if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname; - $valueforchecksum = (empty($value) ? '0' : $value); - - $checksumconcat[] = $valueforchecksum; - - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - - if ($i == 0) - { - $out .= ''; - } - $out .= '
#'.$langs->trans("Constant").''.$langs->trans("ExpectedValue").''.$langs->trans("Value").'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$langs->trans("None").'
'; - $out .= '
'; - - $out .= '
'; - } - - // Scan htdocs - if (is_object($xml->dolibarr_htdocs_dir[0])) - { - //var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit; - $includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']); - - // Defined qualified files (must be same than into generate_filelist_xml.php) - $regextoinclude = '\.(php|php3|php4|php5|phtml|phps|phar|inc|css|scss|html|xml|js|json|tpl|jpg|jpeg|png|gif|ico|sql|lang|txt|yml|bak|md|mp3|mp4|wav|mkv|z|gz|zip|rar|tar|less|svg|eot|woff|woff2|ttf|manifest)$'; - $regextoexclude = '('.($includecustom ? '' : 'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs - $scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude); - - // Fill file_list with files in signature, new files, modified files - $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list - // Complete with list of new files - foreach ($scanfiles as $keyfile => $valfile) - { - $tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); - if (!in_array($tmprelativefilename, $file_list['insignature'])) - { - $md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file - $file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); - } - } - - // Files missings - $out .= load_fiche_titre($langs->trans("FilesMissing")); - - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); - if (is_array($tmpfilelist) && count($tmpfilelist)) - { - $i = 0; - foreach ($tmpfilelist as $file) - { - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - } else { - $out .= ''; - } - $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].'
'.$langs->trans("None").'
'; - $out .= '
'; - - $out .= '
'; - - // Files modified - $out .= load_fiche_titre($langs->trans("FilesModified")); - - $totalsize = 0; - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - $tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename'); - if (is_array($tmpfilelist2) && count($tmpfilelist2)) - { - $i = 0; - foreach ($tmpfilelist2 as $file) - { - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); - $totalsize += $size; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } else { - $out .= ''; - } - $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; - $out .= '
'; - - $out .= '
'; - - // Files added - $out .= load_fiche_titre($langs->trans("FilesAdded")); - - $totalsize = 0; - $out .= '
'; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''; - $out .= ''."\n"; - $tmpfilelist3 = dol_sort_array($file_list['added'], 'filename'); - if (is_array($tmpfilelist3) && count($tmpfilelist3)) - { - $i = 0; - foreach ($tmpfilelist3 as $file) - { - $i++; - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); - $totalsize += $size; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } - $out .= ''; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= ''."\n"; - $out .= "\n"; - } else { - $out .= ''; - } - $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; - $out .= '
'; - - - // Show warning - if (empty($tmpfilelist) && empty($tmpfilelist2) && empty($tmpfilelist3)) - { - //setEventMessages($langs->trans("FileIntegrityIsStrictlyConformedWithReference"), null, 'mesgs'); - } else { - //setEventMessages($langs->trans("FileIntegritySomeFilesWereRemovedOrModified"), null, 'warnings'); - } - } else { - throw new RestException(500, 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile); - } - - - // Scan scripts - - - asort($checksumconcat); // Sort list of checksum - //var_dump($checksumconcat); - $checksumget = md5(join(',', $checksumconcat)); - $checksumtoget = trim((string) $xml->dolibarr_htdocs_dir_checksum); - - $outexpectedchecksum = ($checksumtoget ? $checksumtoget : $langs->trans("Unknown")); - if ($checksumget == $checksumtoget) - { - if (count($file_list['added'])) - { - $resultcode = 'warning'; - $resultcomment = 'FileIntegrityIsOkButFilesWereAdded'; - //$outcurrentchecksum = $checksumget.' - '.$langs->trans("FileIntegrityIsOkButFilesWereAdded").''; - $outcurrentchecksum = $checksumget; - } else { - $resultcode = 'ok'; - $resultcomment = 'Success'; - //$outcurrentchecksum = ''.$checksumget.''; - $outcurrentchecksum = $checksumget; - } - } else { - $resultcode = 'error'; - $resultcomment = 'Error'; - //$outcurrentchecksum = ''.$checksumget.''; - $outcurrentchecksum = $checksumget; - } - } else { - throw new RestException(404, 'No signature file known'); - } - - return array('resultcode'=>$resultcode, 'resultcomment'=>$resultcomment, 'expectedchecksum'=> $outexpectedchecksum, 'currentchecksum'=> $outcurrentchecksum, 'out'=>$out); - } + //TODO link with multicurrency module + $sql = "SELECT t.rowid, t.entity, t.code, t.label, t.url, t.icon, t.active"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_socialnetworks as t"; + $sql .= " WHERE t.entity IN (".getEntity('c_socialnetworks').")"; + $sql .= " AND t.active = ".$active; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of social networks: '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of tickets categories. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of ticket categories + * + * @url GET dictionary/ticket_categories + * + * @throws RestException + */ + public function getTicketsCategories($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_category as t"; + $sql .= " WHERE t.active = ".$active; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticket categories : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of tickets severity. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of ticket severities + * + * @url GET dictionary/ticket_severities + * + * @throws RestException + */ + public function getTicketsSeverities($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, color, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_severity as t"; + $sql .= " WHERE t.active = ".$active; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticket severities : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get the list of tickets types. + * + * @param string $sortfield Sort field + * @param string $sortorder Sort order + * @param int $limit Number of items per page + * @param int $page Page number (starting from zero) + * @param int $active Payment term is active or not {@min 0} {@max 1} + * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)" + * @return array List of ticket types + * + * @url GET dictionary/ticket_types + * + * @throws RestException + */ + public function getTicketsTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '') + { + $list = array(); + + $sql = "SELECT rowid, code, pos, label, use_default, description"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ticket_type as t"; + $sql .= " WHERE t.active = ".(int) $active; + // if ($type) $sql .= " AND t.type LIKE '%".$this->db->escape($type)."%'"; + // if ($module) $sql .= " AND t.module LIKE '%".$this->db->escape($module)."%'"; + // 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) { + $num = $this->db->num_rows($result); + $min = min($num, ($limit <= 0 ? $num : $limit)); + for ($i = 0; $i < $min; $i++) { + $list[] = $this->db->fetch_object($result); + } + } else { + throw new RestException(503, 'Error when retrieving list of ticket types : '.$this->db->lasterror()); + } + + return $list; + } + + /** + * Get properties of company + * + * @url GET /company + * + * @return array|mixed Data without useless information + * + */ + public function getCompany() + { + global $mysoc; + + return $this->_cleanObjectDatas($mysoc); + } + + + /** + * Get value of a setup variables + * + * Note that conf variables that stores security key or password hashes can't be loaded with API. + * + * @param string $constantname Name of conf variable to get + * @return array|mixed Data without useless information + * + * @url GET conf/{constantname} + * + * @throws RestException 403 Forbidden + * @throws RestException 404 Error Bad or unknown value for constantname + */ + public function getConf($constantname) + { + global $conf; + + if (!DolibarrApiAccess::$user->admin + && (empty($conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ) || DolibarrApiAccess::$user->login != $conf->global->API_LOGINS_ALLOWED_FOR_CONST_READ)) { + throw new RestException(403, 'Error API open to admin users only or to the users with logins defined into constant API_LOGINS_ALLOWED_FOR_CONST_READ'); + } + + if (!preg_match('/^[a-zA-Z0-9_]+$/', $constantname) || !isset($conf->global->$constantname)) { + throw new RestException(404, 'Error Bad or unknown value for constantname'); + } + if (isASecretKey($constantname)) { + throw new RestException(403, 'Forbidden. This parameter cant be read with APIs'); + } + + return $conf->global->$constantname; + } + + /** + * Do a test of integrity for files and setup. + * + * @param string $target Can be 'local' or 'default' or Url of the signatures file to use for the test. Must be reachable by the tested Dolibarr. + * @return array Result of file and setup integrity check + * + * @url GET checkintegrity + * + * @throws RestException 404 Signature file not found + * @throws RestException 500 Technical error + * @throws RestException 503 Forbidden + */ + public function getCheckIntegrity($target) + { + global $langs, $conf; + + if (!DolibarrApiAccess::$user->admin + && (empty($conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK) || DolibarrApiAccess::$user->login != $conf->global->API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK)) + { + throw new RestException(503, 'Error API open to admin users only or to the users with logins defined into constant API_LOGIN_ALLOWED_FOR_INTEGRITY_CHECK'); + } + + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; + + $langs->load("admin"); + + $outexpectedchecksum = ''; + $outcurrentchecksum = ''; + + // Modified or missing files + $file_list = array('missing' => array(), 'updated' => array()); + + // Local file to compare to + $xmlshortfile = GETPOST('xmlshortfile') ?GETPOST('xmlshortfile') : '/install/filelist-'.DOL_VERSION.'.xml'; + $xmlfile = DOL_DOCUMENT_ROOT.$xmlshortfile; + // Remote file to compare to + $xmlremote = ($target == 'default' ? '' : $target); + if (empty($xmlremote) && !empty($conf->global->MAIN_FILECHECK_URL)) $xmlremote = $conf->global->MAIN_FILECHECK_URL; + $param = 'MAIN_FILECHECK_URL_'.DOL_VERSION; + if (empty($xmlremote) && !empty($conf->global->$param)) $xmlremote = $conf->global->$param; + if (empty($xmlremote)) $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; + + if ($target == 'local') + { + if (dol_is_file($xmlfile)) + { + $xml = simplexml_load_file($xmlfile); + } else { + throw new RestException(500, $langs->trans('XmlNotFound').': '.$xmlfile); + } + } else { + $xmlarray = getURLContent($xmlremote); + + // Return array('content'=>response,'curl_error_no'=>errno,'curl_error_msg'=>errmsg...) + if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '404') + { + $xmlfile = $xmlarray['content']; + //print "xmlfilestart".$xmlfile."endxmlfile"; + $xml = simplexml_load_string($xmlfile); + } else { + $errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; + throw new RestException(500, $errormsg); + } + } + + + + if ($xml) + { + $checksumconcat = array(); + $file_list = array(); + $out = ''; + + // Forced constants + if (is_object($xml->dolibarr_constants[0])) + { + $out .= load_fiche_titre($langs->trans("ForcedConstants")); + + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + + $i = 0; + foreach ($xml->dolibarr_constants[0]->constant as $constant) // $constant is a simpleXMLElement + { + $constname = $constant['name']; + $constvalue = (string) $constant; + $constvalue = (empty($constvalue) ? '0' : $constvalue); + // Value found + $value = ''; + if ($constname && $conf->global->$constname != '') $value = $conf->global->$constname; + $valueforchecksum = (empty($value) ? '0' : $value); + + $checksumconcat[] = $valueforchecksum; + + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + + if ($i == 0) + { + $out .= ''; + } + $out .= '
#'.$langs->trans("Constant").''.$langs->trans("ExpectedValue").''.$langs->trans("Value").'
'.$i.''.$constname.''.$constvalue.''.$valueforchecksum.'
'.$langs->trans("None").'
'; + $out .= '
'; + + $out .= '
'; + } + + // Scan htdocs + if (is_object($xml->dolibarr_htdocs_dir[0])) + { + //var_dump($xml->dolibarr_htdocs_dir[0]['includecustom']);exit; + $includecustom = (empty($xml->dolibarr_htdocs_dir[0]['includecustom']) ? 0 : $xml->dolibarr_htdocs_dir[0]['includecustom']); + + // Defined qualified files (must be same than into generate_filelist_xml.php) + $regextoinclude = '\.(php|php3|php4|php5|phtml|phps|phar|inc|css|scss|html|xml|js|json|tpl|jpg|jpeg|png|gif|ico|sql|lang|txt|yml|bak|md|mp3|mp4|wav|mkv|z|gz|zip|rar|tar|less|svg|eot|woff|woff2|ttf|manifest)$'; + $regextoexclude = '('.($includecustom ? '' : 'custom|').'documents|conf|install|public\/test|Shared\/PCLZip|nusoap\/lib\/Mail|php\/example|php\/test|geoip\/sample.*\.php|ckeditor\/samples|ckeditor\/adapters)$'; // Exclude dirs + $scanfiles = dol_dir_list(DOL_DOCUMENT_ROOT, 'files', 1, $regextoinclude, $regextoexclude); + + // Fill file_list with files in signature, new files, modified files + $ret = getFilesUpdated($file_list, $xml->dolibarr_htdocs_dir[0], '', DOL_DOCUMENT_ROOT, $checksumconcat); // Fill array $file_list + // Complete with list of new files + foreach ($scanfiles as $keyfile => $valfile) + { + $tmprelativefilename = preg_replace('/^'.preg_quote(DOL_DOCUMENT_ROOT, '/').'/', '', $valfile['fullname']); + if (!in_array($tmprelativefilename, $file_list['insignature'])) + { + $md5newfile = @md5_file($valfile['fullname']); // Can fails if we don't have permission to open/read file + $file_list['added'][] = array('filename'=>$tmprelativefilename, 'md5'=>$md5newfile); + } + } + + // Files missings + $out .= load_fiche_titre($langs->trans("FilesMissing")); + + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + $tmpfilelist = dol_sort_array($file_list['missing'], 'filename'); + if (is_array($tmpfilelist) && count($tmpfilelist)) + { + $i = 0; + foreach ($tmpfilelist as $file) + { + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + } else { + $out .= ''; + } + $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].'
'.$langs->trans("None").'
'; + $out .= '
'; + + $out .= '
'; + + // Files modified + $out .= load_fiche_titre($langs->trans("FilesModified")); + + $totalsize = 0; + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + $tmpfilelist2 = dol_sort_array($file_list['updated'], 'filename'); + if (is_array($tmpfilelist2) && count($tmpfilelist2)) + { + $i = 0; + foreach ($tmpfilelist2 as $file) + { + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); + $totalsize += $size; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } else { + $out .= ''; + } + $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; + $out .= '
'; + + $out .= '
'; + + // Files added + $out .= load_fiche_titre($langs->trans("FilesAdded")); + + $totalsize = 0; + $out .= '
'; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''; + $out .= ''."\n"; + $tmpfilelist3 = dol_sort_array($file_list['added'], 'filename'); + if (is_array($tmpfilelist3) && count($tmpfilelist3)) + { + $i = 0; + foreach ($tmpfilelist3 as $file) + { + $i++; + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $size = dol_filesize(DOL_DOCUMENT_ROOT.'/'.$file['filename']); + $totalsize += $size; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } + $out .= ''; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= ''."\n"; + $out .= "\n"; + } else { + $out .= ''; + } + $out .= '
#'.$langs->trans("Filename").''.$langs->trans("ExpectedChecksum").''.$langs->trans("CurrentChecksum").''.$langs->trans("Size").''.$langs->trans("DateModification").'
'.$i.''.$file['filename'].''.$file['expectedmd5'].''.$file['md5'].''.dol_print_size($size).''.dol_print_date(dol_filemtime(DOL_DOCUMENT_ROOT.'/'.$file['filename']), 'dayhour').'
'.$langs->trans("Total").''.dol_print_size($totalsize).'
'.$langs->trans("None").'
'; + $out .= '
'; + + + // Show warning + if (empty($tmpfilelist) && empty($tmpfilelist2) && empty($tmpfilelist3)) + { + //setEventMessages($langs->trans("FileIntegrityIsStrictlyConformedWithReference"), null, 'mesgs'); + } else { + //setEventMessages($langs->trans("FileIntegritySomeFilesWereRemovedOrModified"), null, 'warnings'); + } + } else { + throw new RestException(500, 'Error: Failed to found dolibarr_htdocs_dir into XML file '.$xmlfile); + } + + + // Scan scripts + + + asort($checksumconcat); // Sort list of checksum + //var_dump($checksumconcat); + $checksumget = md5(join(',', $checksumconcat)); + $checksumtoget = trim((string) $xml->dolibarr_htdocs_dir_checksum); + + $outexpectedchecksum = ($checksumtoget ? $checksumtoget : $langs->trans("Unknown")); + if ($checksumget == $checksumtoget) + { + if (count($file_list['added'])) + { + $resultcode = 'warning'; + $resultcomment = 'FileIntegrityIsOkButFilesWereAdded'; + //$outcurrentchecksum = $checksumget.' - '.$langs->trans("FileIntegrityIsOkButFilesWereAdded").''; + $outcurrentchecksum = $checksumget; + } else { + $resultcode = 'ok'; + $resultcomment = 'Success'; + //$outcurrentchecksum = ''.$checksumget.''; + $outcurrentchecksum = $checksumget; + } + } else { + $resultcode = 'error'; + $resultcomment = 'Error'; + //$outcurrentchecksum = ''.$checksumget.''; + $outcurrentchecksum = $checksumget; + } + } else { + throw new RestException(404, 'No signature file known'); + } + + return array('resultcode'=>$resultcode, 'resultcomment'=>$resultcomment, 'expectedchecksum'=> $outexpectedchecksum, 'currentchecksum'=> $outcurrentchecksum, 'out'=>$out); + } } diff --git a/htdocs/bom/tpl/objectline_view.tpl.php b/htdocs/bom/tpl/objectline_view.tpl.php index c5ee3870272..05682dc3da6 100644 --- a/htdocs/bom/tpl/objectline_view.tpl.php +++ b/htdocs/bom/tpl/objectline_view.tpl.php @@ -111,21 +111,21 @@ print ''; if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines') { print ''; $coldisplay++; - if (($line->info_bits & 2) == 2 || !empty($disableedit)) { - } else { - print 'id.'">'.img_edit().''; - } - print ''; + if (($line->info_bits & 2) == 2 || !empty($disableedit)) { + } else { + print 'id.'">'.img_edit().''; + } + print ''; - print ''; - $coldisplay++; - if (($line->fk_prev_id == null) && empty($disableremove)) { - //La suppression n'est autorisée que si il n'y a pas de ligne dans une précédente situation - print 'id.'">'; - print img_delete(); - print ''; - } - print ''; + print ''; + $coldisplay++; + if (($line->fk_prev_id == null) && empty($disableremove)) { + //La suppression n'est autorisée que si il n'y a pas de ligne dans une précédente situation + print 'id.'">'; + print img_delete(); + print ''; + } + print ''; if ($num > 1 && $conf->browser->layout != 'phone' && empty($disablemove)) { print ''; @@ -146,14 +146,14 @@ if ($this->status == 0 && ($object_rights->write) && $action != 'selectlines') { $coldisplay++; } } else { - print ''; - $coldisplay = $coldisplay + 3; + print ''; + $coldisplay = $coldisplay + 3; } if ($action == 'selectlines') { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } print ''; diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index dc0a980a6f8..866a98fd816 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -44,8 +44,8 @@ $confirm = GETPOST('confirm'); if ($id == '' && $label == '') { - dol_print_error('', 'Missing parameter id'); - exit(); + dol_print_error('', 'Missing parameter id'); + exit(); } // Security check @@ -70,34 +70,34 @@ if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backwar if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sendit"] && !empty($conf->global->MAIN_UPLOAD_DOC)) { - if ($object->id) { - $file = $_FILES['userfile']; - if (is_array($file['name']) && count($file['name']) > 0) - { - foreach ($file['name'] as $i => $name) - { - if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i])) - { - setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles')); - unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]); - } - } - } + if ($object->id) { + $file = $_FILES['userfile']; + if (is_array($file['name']) && count($file['name']) > 0) + { + foreach ($file['name'] as $i => $name) + { + if (empty($file['tmp_name'][$i]) || intval($conf->global->MAIN_UPLOAD_DOC) * 1000 <= filesize($file['tmp_name'][$i])) + { + setEventMessage($file['name'][$i].' : '.$langs->trans(empty($file['tmp_name'][$i]) ? 'ErrorFailedToSaveFile' : 'MaxSizeForUploadedFiles')); + unset($file['name'][$i], $file['type'][$i], $file['tmp_name'][$i], $file['error'][$i], $file['size'][$i]); + } + } + } - if (!empty($file['tmp_name'])) { - $object->add_photo($upload_dir, $file); - } - } + if (!empty($file['tmp_name'])) { + $object->add_photo($upload_dir, $file); + } + } } if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer) { - $object->delete_photo($upload_dir."/".$_GET["file"]); + $object->delete_photo($upload_dir."/".$_GET["file"]); } if ($action == 'addthumb' && $_GET["file"]) { - $object->addThumbs($upload_dir."/".$_GET["file"]); + $object->addThumbs($upload_dir."/".$_GET["file"]); } @@ -126,7 +126,7 @@ if ($object->id) $ways = $object->print_all_ways(" >> ", '', 1); foreach ($ways as $way) { - $morehtmlref .= $way."
\n"; + $morehtmlref .= $way."
\n"; } $morehtmlref .= ''; @@ -137,7 +137,7 @@ if ($object->id) */ if ($action == 'delete') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1); } print '
'; @@ -159,7 +159,7 @@ if ($object->id) print ''; print "\n"; - print ''; + print ''; dol_fiche_end(); @@ -213,62 +213,62 @@ if ($object->id) if (is_array($listofphoto) && count($listofphoto)) { - print '
'; - print ''; + print '
'; + print '
'; - foreach ($listofphoto as $key => $obj) - { - $nbphoto++; + foreach ($listofphoto as $key => $obj) + { + $nbphoto++; - if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print ''; - if ($nbbyrow) print ''; + if ($nbbyrow) print ''; - if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print ''; - } + // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites + if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight)) + { + print ''.img_picto($langs->trans('GenerateThumb'), 'refresh').'  '; + } + if ($user->rights->categorie->creer) + { + print ''; + print img_delete().''; + } + if ($nbbyrow) print ''; + if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print ''; + } - // Ferme tableau - while ($nbphoto % $nbbyrow) - { - print ''; - $nbphoto++; - } + // Ferme tableau + while ($nbphoto % $nbbyrow) + { + print ''; + $nbphoto++; + } - print '
'; + if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print '
'; - print ''; + print ''; - // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine - if ($obj['photo_vignette']) - { - $filename = $obj['photo_vignette']; - } else { - $filename = $obj['photo']; - } + // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine + if ($obj['photo_vignette']) + { + $filename = $obj['photo_vignette']; + } else { + $filename = $obj['photo']; + } - // Nom affiche - $viewfilename = $obj['photo']; + // Nom affiche + $viewfilename = $obj['photo']; - // Taille de l'image - $object->get_image_size($dir.$filename); - $imgWidth = ($object->imgWidth < $maxWidth) ? $object->imgWidth : $maxWidth; - $imgHeight = ($object->imgHeight < $maxHeight) ? $object->imgHeight : $maxHeight; + // Taille de l'image + $object->get_image_size($dir.$filename); + $imgWidth = ($object->imgWidth < $maxWidth) ? $object->imgWidth : $maxWidth; + $imgHeight = ($object->imgHeight < $maxHeight) ? $object->imgHeight : $maxHeight; - print ''; + print ''; - print ''; - print '
'.$viewfilename; - print '
'; + print ''; + print '
'.$viewfilename; + print '
'; - // On propose la generation de la vignette si elle n'existe pas et si la taille est superieure aux limites - if (!$obj['photo_vignette'] && preg_match('/(\.bmp|\.gif|\.jpg|\.jpeg|\.png)$/i', $obj['photo']) && ($object->imgWidth > $maxWidth || $object->imgHeight > $maxHeight)) - { - print ''.img_picto($langs->trans('GenerateThumb'), 'refresh').'  '; - } - if ($user->rights->categorie->creer) - { - print ''; - print img_delete().''; - } - if ($nbbyrow) print '
  
'; + print ''; } if ($nbphoto < 1) @@ -277,7 +277,7 @@ if ($object->id) } } } else { - print $langs->trans("ErrorUnknown"); + print $langs->trans("ErrorUnknown"); } // End of page diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index f5755a697ca..f4e073c4e1c 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -83,43 +83,43 @@ $cancel != $langs->trans("Cancel") && $current_lang = $langs->getDefaultLang(); // check parameters - $forcelangprod = GETPOST('forcelangprod', 'alpha'); - $libelle = GETPOST('libelle', 'alpha'); - $desc = GETPOST('desc', 'restricthtml'); + $forcelangprod = GETPOST('forcelangprod', 'alpha'); + $libelle = GETPOST('libelle', 'alpha'); + $desc = GETPOST('desc', 'restricthtml'); - if (empty($forcelangprod)) { - $error++; - $object->errors[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Translation')); - } + if (empty($forcelangprod)) { + $error++; + $object->errors[] = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Translation')); + } - if (!$error) { - if (empty($libelle)) { - $error++; - $object->errors[] = $langs->trans('Language_'.$forcelangprod).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); - } + if (!$error) { + if (empty($libelle)) { + $error++; + $object->errors[] = $langs->trans('Language_'.$forcelangprod).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); + } - if (!$error) { - // update de l'objet - if ($forcelangprod == $current_lang) { - $object->label = $libelle; - $object->description = dol_htmlcleanlastbr($desc); - } else { - $object->multilangs[$forcelangprod]["label"] = $libelle; - $object->multilangs[$forcelangprod]["description"] = dol_htmlcleanlastbr($desc); - } + if (!$error) { + // update de l'objet + if ($forcelangprod == $current_lang) { + $object->label = $libelle; + $object->description = dol_htmlcleanlastbr($desc); + } else { + $object->multilangs[$forcelangprod]["label"] = $libelle; + $object->multilangs[$forcelangprod]["description"] = dol_htmlcleanlastbr($desc); + } - // sauvegarde en base - $res = $object->setMultiLangs($user); - if ($res < 0) $error++; - } - } + // sauvegarde en base + $res = $object->setMultiLangs($user); + if ($res < 0) $error++; + } + } - if ($error) { - $action = 'add'; - setEventMessages($object->error, $object->errors, 'errors'); - } else { - $action = ''; - } + if ($error) { + $action = 'add'; + setEventMessages($object->error, $object->errors, 'errors'); + } else { + $action = ''; + } } // Validation de l'edition @@ -132,13 +132,13 @@ $cancel != $langs->trans("Cancel") && foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet { - $libelle = GETPOST('libelle-'.$key, 'alpha'); - $desc = GETPOST('desc-'.$key); + $libelle = GETPOST('libelle-'.$key, 'alpha'); + $desc = GETPOST('desc-'.$key); - if (empty($libelle)) { - $error++; - $object->errors[] = $langs->trans('Language_'.$key).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); - } + if (empty($libelle)) { + $error++; + $object->errors[] = $langs->trans('Language_'.$key).' : '.$langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Label')); + } if ($key == $current_lang) { $object->label = $libelle; @@ -149,17 +149,17 @@ $cancel != $langs->trans("Cancel") && } } - if (!$error) { - $res = $object->setMultiLangs($user); - if ($res < 0) $error++; - } + if (!$error) { + $res = $object->setMultiLangs($user); + if ($res < 0) $error++; + } - if ($error) { - $action = 'edit'; - setEventMessages($object->error, $object->errors, 'errors'); - } else { - $action = ''; - } + if ($error) { + $action = 'edit'; + setEventMessages($object->error, $object->errors, 'errors'); + } else { + $action = ''; + } } @@ -181,10 +181,10 @@ $head = categories_prepare_head($object, $type); $cnt_trans = 0; if (!empty($object->multilangs)) { - foreach ($object->multilangs as $key => $value) - { - $cnt_trans++; - } + foreach ($object->multilangs as $key => $value) + { + $cnt_trans++; + } } dol_fiche_head($head, 'translation', $langs->trans($title), -1, 'category'); @@ -195,7 +195,7 @@ $object->ref = $object->label; $morehtmlref = '
'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); foreach ($ways as $way) { - $morehtmlref .= $way."
\n"; + $morehtmlref .= $way."
\n"; } $morehtmlref .= '
'; @@ -238,11 +238,11 @@ print "\n
\n"; if ($action == '') { - if ($user->rights->produit->creer || $user->rights->service->creer) - { - print ''.$langs->trans('Add').''; - if ($cnt_trans > 0) print ''.$langs->trans('Update').''; - } + if ($user->rights->produit->creer || $user->rights->service->creer) + { + print ''.$langs->trans('Add').''; + if ($cnt_trans > 0) print ''.$langs->trans('Update').''; + } } print "\n
\n"; @@ -258,20 +258,20 @@ if ($action == 'edit') print ''; print ''; print ''; - print ''; + print ''; if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { - print "
".$langs->trans('Language_'.$key)." :
"; + print "
".$langs->trans('Language_'.$key)." :
"; print ''; // Label - $libelle = (GETPOST('libelle-'.$key, 'alpha') ? GETPOST('libelle-'.$key, 'alpha') : $object->multilangs[$key]['label']); + $libelle = (GETPOST('libelle-'.$key, 'alpha') ? GETPOST('libelle-'.$key, 'alpha') : $object->multilangs[$key]['label']); print ''; // Desc - $desc = (GETPOST('desc-'.$key) ? GETPOST('desc-'.$key) : $object->multilangs[$key]['description']); + $desc = (GETPOST('desc-'.$key) ? GETPOST('desc-'.$key) : $object->multilangs[$key]['description']); print ''; + print "
'.$langs->trans('Label').'
'.$langs->trans('Description').''; $doleditor = new DolEditor("desc-$key", $desc, '', 160, 'dolibarr_notes', '', false, true, $conf->global->FCKEDITOR_ENABLE_PRODUCTDESC, ROWS_3, '90%'); $doleditor->Create(); @@ -293,20 +293,20 @@ if ($action == 'edit') print ''; } elseif ($action != 'add') { - if ($cnt_trans) print '
'; + if ($cnt_trans) print '
'; - if (!empty($object->multilangs)) + if (!empty($object->multilangs)) { foreach ($object->multilangs as $key => $value) { - $s = picto_from_langcode($key); + $s = picto_from_langcode($key); print ''; print ''; print ''; print ''; if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION)) { - print ''; + print ''; } print '
'.($s ? $s.' ' : '')." ".$langs->trans('Language_'.$key).": ".''.img_delete('', '').'
'.$langs->trans('Label').''.$object->multilangs[$key]["label"].'
'.$langs->trans('Description').''.$object->multilangs[$key]["description"].'
'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')'.$object->multilangs[$key]["other"].'
'.$langs->trans('Other').' ('.$langs->trans("NotUsed").')'.$object->multilangs[$key]["other"].'
'; } @@ -329,11 +329,11 @@ if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; print ''; print ''; diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index d056f4fb3af..d3a60d76e14 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -138,12 +138,12 @@ if (empty($reshook)) } // customer preferred shipping method - if ($action == 'setshippingmethod' && $user->rights->societe->creer) - { - $object->fetch($id); - $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); - } + if ($action == 'setshippingmethod' && $user->rights->societe->creer) + { + $object->fetch($id); + $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); + if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + } // assujetissement a la TVA if ($action == 'setassujtva' && $user->rights->societe->creer) @@ -191,31 +191,31 @@ if (empty($reshook)) } // Set sales representatives - if ($action == 'set_salesrepresentatives' && $user->rights->societe->creer) + if ($action == 'set_salesrepresentatives' && $user->rights->societe->creer) { $object->fetch($id); $result = $object->setSalesRep(GETPOST('commercial', 'array')); } if ($action == 'update_extras') { - $object->fetch($id); + $object->fetch($id); - $object->oldcopy = dol_clone($object); + $object->oldcopy = dol_clone($object); - // Fill array 'array_options' with data from update form - $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; - if (!$error) - { - $result = $object->insertExtraFields('COMPANY_MODIFY'); + // Fill array 'array_options' with data from update form + $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); + if ($ret < 0) $error++; + if (!$error) + { + $result = $object->insertExtraFields('COMPANY_MODIFY'); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } - } - if ($error) $action = 'edit_extras'; - } + } + if ($error) $action = 'edit_extras'; + } } @@ -249,11 +249,11 @@ if ($object->id > 0) $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 '
'.$langs->trans('Translation').''; - print $formadmin->select_language(GETPOST('forcelangprod', 'alpha'), 'forcelangprod', 0, $object->multilangs); + print $formadmin->select_language(GETPOST('forcelangprod', 'alpha'), 'forcelangprod', 0, $object->multilangs); print '
'.$langs->trans('Label').'
'; // Prospect/Customer @@ -262,16 +262,16 @@ if ($object->id > 0) print ''; // Prefix - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { - print ''; - } + if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field + { + print ''; + } if ($object->client) { - $langs->load("compta"); + $langs->load("compta"); print ''; - print ''; + print ''; + print ''; - // Absolute discounts (Discounts-Drawbacks-Rebates) - print ''; - print ''; - print ''; + // Absolute discounts (Discounts-Drawbacks-Rebates) + print ''; + print ''; + print ''; } // Max outstanding bill if ($object->client) { - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } if ($object->client) { if (!empty($conf->commande->enabled) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)) { - print ''."\n"; - print ''; - print ''; - print ''; + print ''."\n"; + print ''; + print ''; + print ''; } } @@ -468,24 +468,24 @@ if ($object->id > 0) print ''; } - // Preferred shipping Method - if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) { - print '"; - print ''; - } + // Preferred shipping Method + if (!empty($conf->global->SOCIETE_ASK_FOR_SHIPPING_METHOD)) { + print '"; + print ''; + } // Categories if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { @@ -500,70 +500,70 @@ if ($object->id > 0) $parameters = array('socid'=>$object->id); include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - // Sales representative + // Sales representative include DOL_DOCUMENT_ROOT.'/societe/tpl/linesalesrepresentative.tpl.php'; - // Module Adherent - if (!empty($conf->adherent->enabled)) - { - $langs->load("members"); - $langs->load("users"); + // Module Adherent + if (!empty($conf->adherent->enabled)) + { + $langs->load("members"); + $langs->load("users"); - print ''; - print ''; - print "\n"; - } + print ''; + print ''; + print "\n"; + } print "
'.$langs->trans("Prefix").''; - print ($object->prefix_comm ? $object->prefix_comm : ' '); - print '
'.$langs->trans("Prefix").''; + print ($object->prefix_comm ? $object->prefix_comm : ' '); + print '
'; print $langs->trans('CustomerCode').''; @@ -386,64 +386,64 @@ if ($object->id > 0) // Relative discounts (Discounts-Drawbacks-Rebates) if ($isCustomer) { - print '
'; - print '
'; - print $langs->trans("CustomerRelativeDiscountShort"); - print ''; - if ($user->rights->societe->creer && !$user->socid > 0) - { - print ''.img_edit($langs->trans("Modify")).''; - } - print '
'; - print '
'.($object->remise_percent ? ''.$object->remise_percent.'%' : '').'
'; + print '
'; + print $langs->trans("CustomerRelativeDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->socid > 0) + { + print ''.img_edit($langs->trans("Modify")).''; + } + print '
'; + print '
'.($object->remise_percent ? ''.$object->remise_percent.'%' : '').'
'; - print ''; - print '
'; - print $langs->trans("CustomerAbsoluteDiscountShort"); - print ''; - if ($user->rights->societe->creer && !$user->socid > 0) - { - print ''.img_edit($langs->trans("Modify")).''; - } - print '
'; - print '
'; - $amount_discount = $object->getAvailableDiscounts(); - if ($amount_discount < 0) dol_print_error($db, $object->error); - if ($amount_discount > 0) print ''.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).''; - //else print $langs->trans("DiscountNone"); - print '
'; + print ''; + print '
'; + print $langs->trans("CustomerAbsoluteDiscountShort"); + print ''; + if ($user->rights->societe->creer && !$user->socid > 0) + { + print ''.img_edit($langs->trans("Modify")).''; + } + print '
'; + print '
'; + $amount_discount = $object->getAvailableDiscounts(); + if ($amount_discount < 0) dol_print_error($db, $object->error); + if ($amount_discount > 0) print ''.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).''; + //else print $langs->trans("DiscountNone"); + print '
'; - print $form->editfieldkey("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer); - print ''; - $limit_field_type = (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount'; - print $form->editfieldval("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer, $limit_field_type, ($object->outstanding_limit != '' ? price($object->outstanding_limit) : '')); - print '
'; + print $form->editfieldkey("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer); + print ''; + $limit_field_type = (!empty($conf->global->MAIN_USE_JQUERY_JEDITABLE)) ? 'numeric' : 'amount'; + print $form->editfieldval("OutstandingBill", 'outstanding_limit', $object->outstanding_limit, $object, $user->rights->societe->creer, $limit_field_type, ($object->outstanding_limit != '' ? price($object->outstanding_limit) : '')); + print '
'; - print $form->editfieldkey("OrderMinAmount", 'order_min_amount', $object->order_min_amount, $object, $user->rights->societe->creer); - print ''; - print $form->editfieldval("OrderMinAmount", 'order_min_amount', $object->order_min_amount, $object, $user->rights->societe->creer, $limit_field_type, ($object->order_min_amount != '' ? price($object->order_min_amount) : '')); - print '
'; + print $form->editfieldkey("OrderMinAmount", 'order_min_amount', $object->order_min_amount, $object, $user->rights->societe->creer); + print ''; + print $form->editfieldval("OrderMinAmount", 'order_min_amount', $object->order_min_amount, $object, $user->rights->societe->creer, $limit_field_type, ($object->order_min_amount != '' ? price($object->order_min_amount) : '')); + print '
'; - print ''; - print '
'; - print $langs->trans('SendingMethod'); - print ''; - if (($action != 'editshipping') && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('SetMode'), 1).'
'; - print '
'; - if ($action == 'editshipping') - { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); - } else { - $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'none'); - } - print "
'; + print ''; + print '
'; + print $langs->trans('SendingMethod'); + print ''; + if (($action != 'editshipping') && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('SetMode'), 1).'
'; + print '
'; + if ($action == 'editshipping') + { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'shipping_method_id', 1); + } else { + $form->formSelectShippingMethod($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->shipping_method_id, 'none'); + } + print "
'.$langs->trans("LinkedToDolibarrMember").''; - $adh = new Adherent($db); - $result = $adh->fetch('', '', $object->id); - if ($result > 0) - { - $adh->ref = $adh->getFullName($langs); - print $adh->getNomUrl(1); - } else { - print ''.$langs->trans("ThirdpartyNotLinkedToMember").''; - } - print '
'.$langs->trans("LinkedToDolibarrMember").''; + $adh = new Adherent($db); + $result = $adh->fetch('', '', $object->id); + if ($result > 0) + { + $adh->ref = $adh->getFullName($langs); + print $adh->getNomUrl(1); + } else { + print ''.$langs->trans("ThirdpartyNotLinkedToMember").''; + } + print '
"; // Prospection level and status if ($object->client == 2 || $object->client == 3) { - print '
'; + print '
'; - print '
'; - print ''; + print '
'; + print '
'; - // Level of prospection - print '"; - print ''; + // Level of prospection + print '"; + print ''; - // Status of prospection - $object->loadCacheOfProspStatus(); - print ''; - print "
'; - print ''; - print '
'; - print $langs->trans('ProspectLevel'); - print ''; - if ($action != 'editlevel' && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('Modify'), 1).'
'; - print '
'; - if ($action == 'editlevel') - { - $formcompany->form_prospect_level($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->fk_prospectlevel, 'prospect_level_id', 1); - } else { - print $object->getLibProspLevel(); - } - print "
'; + print ''; + print '
'; + print $langs->trans('ProspectLevel'); + print ''; + if ($action != 'editlevel' && $user->rights->societe->creer) print 'id.'">'.img_edit($langs->trans('Modify'), 1).'
'; + print '
'; + if ($action == 'editlevel') + { + $formcompany->form_prospect_level($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->fk_prospectlevel, 'prospect_level_id', 1); + } else { + print $object->getLibProspLevel(); + } + print "
'.$langs->trans("StatusProsp").''.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']); - print '     '; - print '
'; - foreach ($object->cacheprospectstatus as $key => $val) - { + // Status of prospection + $object->loadCacheOfProspStatus(); + print '
'.$langs->trans("StatusProsp").''.$object->getLibProspCommStatut(4, $object->cacheprospectstatus[$object->stcomm_id]['label']); + print '     '; + print '
'; + foreach ($object->cacheprospectstatus as $key => $val) + { $titlealt = 'default'; if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label']; if ($object->stcomm_id != $val['id']) print ''.img_action($titlealt, $val['code'], $val['picto']).''; } - print '
"; + print '
"; } print '
'; @@ -670,9 +670,9 @@ if ($object->id > 0) $langs->load("propal"); $sql = "SELECT s.nom, s.rowid, p.rowid as propalid, p.fk_statut, p.total_ht"; - $sql .= ", p.tva as total_tva"; - $sql .= ", p.total as total_ttc"; - $sql .= ", p.ref, p.ref_client, p.remise"; + $sql .= ", p.tva as total_tva"; + $sql .= ", p.total as total_ttc"; + $sql .= ", p.ref, p.ref_client, p.remise"; $sql .= ", p.datep as dp, p.fin_validite as date_limit"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p, ".MAIN_DB_PREFIX."c_propalst as c"; $sql .= " WHERE p.fk_soc = s.rowid AND p.fk_statut = c.id"; @@ -686,17 +686,17 @@ if ($object->id > 0) $propal_static = new Propal($db); $num = $db->num_rows($resql); - if ($num > 0) - { - print '
'; - print ''; + if ($num > 0) + { + print '
'; + print '
'; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + } $i = 0; while ($i < $num && $i < $MAXLIST) @@ -704,17 +704,17 @@ if ($object->id > 0) $objp = $db->fetch_object($resql); print ''; - print '\n"; print ''; print ''; @@ -737,12 +737,12 @@ if ($object->id > 0) */ if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { - $sql = "SELECT s.nom, s.rowid"; - $sql .= ", c.rowid as cid, c.total_ht"; - $sql .= ", c.tva as total_tva"; - $sql .= ", c.total_ttc"; - $sql .= ", c.ref, c.ref_client, c.fk_statut, c.facture"; - $sql .= ", c.date_commande as dc"; + $sql = "SELECT s.nom, s.rowid"; + $sql .= ", c.rowid as cid, c.total_ht"; + $sql .= ", c.tva as total_tva"; + $sql .= ", c.total_ttc"; + $sql .= ", c.ref, c.ref_client, c.fk_statut, c.facture"; + $sql .= ", c.date_commande as dc"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c"; $sql .= " WHERE c.fk_soc = s.rowid "; $sql .= " AND s.rowid = ".$object->id; @@ -795,8 +795,8 @@ if ($object->id > 0) $commande_static->billed = $objp->billed; print ''; - print '\n"; print ''; print ''; @@ -814,78 +814,78 @@ if ($object->id > 0) } } - /* + /* * Latest shipments */ - if (!empty($conf->expedition->enabled) && $user->rights->expedition->lire) - { - $sql = 'SELECT e.rowid as id'; - $sql .= ', e.ref'; - $sql .= ', e.date_creation'; - $sql .= ', e.fk_statut as statut'; - $sql .= ', s.nom'; - $sql .= ', s.rowid as socid'; - $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."expedition as e"; - $sql .= " WHERE e.fk_soc = s.rowid AND s.rowid = ".$object->id; - $sql .= " AND e.entity IN (".getEntity('expedition').")"; - $sql .= ' GROUP BY e.rowid'; - $sql .= ', e.ref'; - $sql .= ', e.date_creation'; - $sql .= ', e.fk_statut'; - $sql .= ', s.nom'; - $sql .= ', s.rowid'; - $sql .= " ORDER BY e.date_creation DESC"; + if (!empty($conf->expedition->enabled) && $user->rights->expedition->lire) + { + $sql = 'SELECT e.rowid as id'; + $sql .= ', e.ref'; + $sql .= ', e.date_creation'; + $sql .= ', e.fk_statut as statut'; + $sql .= ', s.nom'; + $sql .= ', s.rowid as socid'; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."expedition as e"; + $sql .= " WHERE e.fk_soc = s.rowid AND s.rowid = ".$object->id; + $sql .= " AND e.entity IN (".getEntity('expedition').")"; + $sql .= ' GROUP BY e.rowid'; + $sql .= ', e.ref'; + $sql .= ', e.date_creation'; + $sql .= ', e.fk_statut'; + $sql .= ', s.nom'; + $sql .= ', s.rowid'; + $sql .= " ORDER BY e.date_creation DESC"; - $resql = $db->query($sql); - if ($resql) - { - $sendingstatic = new Expedition($db); + $resql = $db->query($sql); + if ($resql) + { + $sendingstatic = new Expedition($db); - $num = $db->num_rows($resql); - if ($num > 0) { - print '
'; - print '
'; - print ''; - print '
'.$langs->trans("LastPropals", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllPropals").''.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
'; + print ''; + print '
'.$langs->trans("LastPropals", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllPropals").''.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
'; - $propal_static->id = $objp->propalid; - $propal_static->ref = $objp->ref; - $propal_static->ref_client = $objp->ref_client; - $propal_static->total_ht = $objp->total_ht; - $propal_static->total_tva = $objp->total_tva; - $propal_static->total_ttc = $objp->total_ttc; - print $propal_static->getNomUrl(1); - if (($db->jdate($objp->date_limit) < ($now - $conf->propal->cloture->warning_delay)) && $objp->fk_statut == $propal_static::STATUS_VALIDATED) { - print " ".img_warning(); - } + print ''; + $propal_static->id = $objp->propalid; + $propal_static->ref = $objp->ref; + $propal_static->ref_client = $objp->ref_client; + $propal_static->total_ht = $objp->total_ht; + $propal_static->total_tva = $objp->total_tva; + $propal_static->total_ttc = $objp->total_ttc; + print $propal_static->getNomUrl(1); + if (($db->jdate($objp->date_limit) < ($now - $conf->propal->cloture->warning_delay)) && $objp->fk_statut == $propal_static::STATUS_VALIDATED) { + print " ".img_warning(); + } print ''.dol_print_date($db->jdate($objp->dp), 'day')."'.price($objp->total_ht).''.$propal_static->LibStatut($objp->fk_statut, 5).'
'; - print $commande_static->getNomUrl(1); + print ''; + print $commande_static->getNomUrl(1); print ''.dol_print_date($db->jdate($objp->dc), 'day')."'.price($objp->total_ht).''.$commande_static->LibStatut($objp->fk_statut, $objp->facture, 5).'
'; + $num = $db->num_rows($resql); + if ($num > 0) { + print '
'; + print '
'; - print ''; - print ''; - print ''; - } + print ''; + print ''; + print ''; + } - $i = 0; - while ($i < $num && $i < $MAXLIST) - { - $objp = $db->fetch_object($resql); + $i = 0; + while ($i < $num && $i < $MAXLIST) + { + $objp = $db->fetch_object($resql); - $sendingstatic->id = $objp->id; - $sendingstatic->ref = $objp->ref; + $sendingstatic->id = $objp->id; + $sendingstatic->ref = $objp->ref; - print ''; - print ''; - if ($objp->date_creation > 0) { - print ''; - } else { - print ''; - } + print ''; + print ''; + if ($objp->date_creation > 0) { + print ''; + } else { + print ''; + } - print ''; - print "\n"; - $i++; - } - $db->free($resql); + print ''; + print "\n"; + $i++; + } + $db->free($resql); - if ($num > 0) - { - print "
'; - print ''; - print '
'.$langs->trans("LastSendings", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllSendings").''.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
'; + print ''; + print '
'.$langs->trans("LastSendings", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllSendings").''.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
'; - print $sendingstatic->getNomUrl(1); - print ''.dol_print_date($db->jdate($objp->date_creation), 'day').'!!!
'; + print $sendingstatic->getNomUrl(1); + print ''.dol_print_date($db->jdate($objp->date_creation), 'day').'!!!'.$sendingstatic->LibStatut($objp->statut, 5).'
'.$sendingstatic->LibStatut($objp->statut, 5).'
"; - print '
'; - } - } else { - dol_print_error($db); - } - } + if ($num > 0) + { + print ""; + print '
'; + } + } else { + dol_print_error($db); + } + } /* * Latest contracts @@ -910,7 +910,7 @@ if ($object->id > 0) print '
'; print ''; - print ''; + print ''; print '
'; print ''; //print ''; @@ -987,7 +987,7 @@ if ($object->id > 0) print '
'; print '
'.$langs->trans("LastContracts", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllContracts").''.$num.''.img_picto($langs->trans("Statistics"),'stats').'
'; - print ''; + print ''; print ''; @@ -1000,11 +1000,11 @@ if ($object->id > 0) $objp = $db->fetch_object($resql); $fichinter_static->id = $objp->id; - $fichinter_static->statut = $objp->fk_statut; + $fichinter_static->statut = $objp->fk_statut; print ''; print ''."\n"; - //print ''."\n"; + //print ''."\n"; print ''."\n"; print ''."\n"; print ''; @@ -1130,10 +1130,10 @@ if ($object->id > 0) */ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { - $sql = 'SELECT f.rowid as facid, f.ref, f.type'; - $sql .= ', f.total as total_ht'; - $sql .= ', f.tva as total_tva'; - $sql .= ', f.total_ttc'; + $sql = 'SELECT f.rowid as facid, f.ref, f.type'; + $sql .= ', f.total as total_ht'; + $sql .= ', f.tva as total_tva'; + $sql .= ', f.total_ttc'; $sql .= ', f.datef as df, f.datec as dc, f.paye as paye, f.fk_statut as statut'; $sql .= ', s.nom, s.rowid as socid'; $sql .= ', SUM(pf.amount) as am'; @@ -1159,7 +1159,7 @@ if ($object->id > 0) print ''; print ''; print ''; } @@ -1192,9 +1192,9 @@ if ($object->id > 0) if (!empty($conf->global->MAIN_SHOW_PRICE_WITH_TAX_IN_SUMMARIES)) { - print ''; + print ''; } print ''; @@ -1228,79 +1228,79 @@ if ($object->id > 0) $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - if (empty($reshook)) - { - if ($object->status != 1) - { - print ''; - } + if (empty($reshook)) + { + if ($object->status != 1) + { + print ''; + } - if (!empty($conf->propal->enabled) && $user->rights->propal->creer && $object->status == 1) - { - $langs->load("propal"); - print ''; - } + if (!empty($conf->propal->enabled) && $user->rights->propal->creer && $object->status == 1) + { + $langs->load("propal"); + print ''; + } - if (!empty($conf->commande->enabled) && $user->rights->commande->creer && $object->status == 1) - { - $langs->load("orders"); - print ''; - } + if (!empty($conf->commande->enabled) && $user->rights->commande->creer && $object->status == 1) + { + $langs->load("orders"); + print ''; + } - if ($user->rights->contrat->creer && $object->status == 1) - { - $langs->load("contracts"); - print ''; - } + if ($user->rights->contrat->creer && $object->status == 1) + { + $langs->load("contracts"); + print ''; + } - if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer && $object->status == 1) - { - $langs->load("fichinter"); - print ''; - } + if (!empty($conf->ficheinter->enabled) && $user->rights->ficheinter->creer && $object->status == 1) + { + $langs->load("fichinter"); + print ''; + } - // Add invoice - if ($user->socid == 0) - { - if (!empty($conf->deplacement->enabled) && $object->status == 1) - { - $langs->load("trips"); - print ''; - } + // Add invoice + if ($user->socid == 0) + { + if (!empty($conf->deplacement->enabled) && $object->status == 1) + { + $langs->load("trips"); + print ''; + } - if (!empty($conf->facture->enabled) && $object->status == 1) - { - if (empty($user->rights->facture->creer)) - { - print ''; - } else { - $langs->loadLangs(array("orders", "bills")); + if (!empty($conf->facture->enabled) && $object->status == 1) + { + if (empty($user->rights->facture->creer)) + { + print ''; + } else { + $langs->loadLangs(array("orders", "bills")); - if (!empty($conf->commande->enabled)) - { - if ($object->client != 0 && $object->client != 2) { - if (!empty($orders2invoice) && $orders2invoice > 0) print ''; - else print ''; - } else print ''; - } + if (!empty($conf->commande->enabled)) + { + if ($object->client != 0 && $object->client != 2) { + if (!empty($orders2invoice) && $orders2invoice > 0) print ''; + else print ''; + } else print ''; + } - if ($object->client != 0 && $object->client != 2) print ''; - else print ''; - } - } - } + if ($object->client != 0 && $object->client != 2) print ''; + else print ''; + } + } + } - // Add action - if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1) - { - if ($user->rights->agenda->myactions->create) - { - print ''; - } else { - print ''; - } - } - } + // Add action + if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1) + { + if ($user->rights->agenda->myactions->create) + { + print ''; + } else { + print ''; + } + } + } print ''; @@ -1310,14 +1310,14 @@ if ($object->id > 0) show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); } - if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB)) - { - print load_fiche_titre($langs->trans("ActionsOnCompany"), '', ''); + if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB)) + { + print load_fiche_titre($langs->trans("ActionsOnCompany"), '', ''); - // List of todo actions + // List of todo actions show_actions_todo($conf, $langs, $db, $object); - // List of done actions + // List of done actions show_actions_done($conf, $langs, $db, $object); } } else { diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 90e60bf6adb..f2275d59021 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; */ class Proposals extends DolibarrApi { - /** + /** * @var array $FIELDS Mandatory fields, checked when create and update object */ static $FIELDS = array( @@ -65,60 +65,60 @@ class Proposals extends DolibarrApi */ public function get($id, $contact_list = 1) { - return $this->_fetch($id, '', '', $contact_list); + return $this->_fetch($id, '', '', $contact_list); } - /** - * Get properties of an proposal object by ref - * - * Return an array with proposal informations - * - * @param string $ref Ref of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @url GET ref/{ref} - * - * @throws RestException - */ - public function getByRef($ref, $contact_list = 1) - { - return $this->_fetch('', $ref, '', $contact_list); - } + /** + * Get properties of an proposal object by ref + * + * Return an array with proposal informations + * + * @param string $ref Ref of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref/{ref} + * + * @throws RestException + */ + public function getByRef($ref, $contact_list = 1) + { + return $this->_fetch('', $ref, '', $contact_list); + } - /** - * Get properties of an proposal object by ref_ext - * - * Return an array with proposal informations - * - * @param string $ref_ext External reference of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @url GET ref_ext/{ref_ext} - * - * @throws RestException - */ - public function getByRefExt($ref_ext, $contact_list = 1) - { - return $this->_fetch('', '', $ref_ext, $contact_list); - } + /** + * Get properties of an proposal object by ref_ext + * + * Return an array with proposal informations + * + * @param string $ref_ext External reference of object + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @url GET ref_ext/{ref_ext} + * + * @throws RestException + */ + public function getByRefExt($ref_ext, $contact_list = 1) + { + return $this->_fetch('', '', $ref_ext, $contact_list); + } - /** - * Get properties of an proposal object - * - * Return an array with proposal informations - * - * @param int $id ID of order + /** + * Get properties of an proposal object + * + * Return an array with proposal informations + * + * @param int $id ID of order * @param string $ref Ref of object * @param string $ref_ext External reference of object - * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id - * @return array|mixed data without useless information - * - * @throws RestException - */ - private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) - { + * @param int $contact_list 0: Returned array of contacts/addresses contains all properties, 1: Return array contains just id + * @return array|mixed data without useless information + * + * @throws RestException + */ + private function _fetch($id, $ref = '', $ref_ext = '', $contact_list = 1) + { if (!DolibarrApiAccess::$user->rights->propal->lire) { throw new RestException(401); } @@ -151,8 +151,8 @@ class Proposals extends DolibarrApi * @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 = '') - { + public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '') + { global $db, $conf; $obj_ret = array(); @@ -201,8 +201,8 @@ class Proposals extends DolibarrApi $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) { @@ -235,13 +235,13 @@ class Proposals extends DolibarrApi * @param array $request_data Request data * @return int ID of proposal */ - public function post($request_data = null) - { - if (!DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401, "Insuffisant rights"); - } - // Check mandatory fields - $result = $this->_validate($request_data); + public function post($request_data = null) + { + if (!DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401, "Insuffisant rights"); + } + // Check mandatory fields + $result = $this->_validate($request_data); foreach ($request_data as $field => $value) { $this->propal->$field = $value; @@ -258,7 +258,7 @@ class Proposals extends DolibarrApi } return $this->propal->id; - } + } /** * Get lines of a commercial proposal @@ -269,26 +269,26 @@ class Proposals extends DolibarrApi * * @return int */ - public function getLines($id) - { - if (!DolibarrApiAccess::$user->rights->propal->lire) { - throw new RestException(401); - } + public function getLines($id) + { + if (!DolibarrApiAccess::$user->rights->propal->lire) { + throw new RestException(401); + } - $result = $this->propal->fetch($id); - if (!$result) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $result = $this->propal->fetch($id); + if (!$result) { + throw new RestException(404, 'Commercial Proposal not found'); + } if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->propal->getLinesArray(); - $result = array(); - foreach ($this->propal->lines as $line) { - array_push($result, $this->_cleanObjectDatas($line)); - } - return $result; + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->propal->getLinesArray(); + $result = array(); + foreach ($this->propal->lines as $line) { + array_push($result, $this->_cleanObjectDatas($line)); + } + return $result; } /** @@ -309,50 +309,50 @@ class Proposals extends DolibarrApi $result = $this->propal->fetch($id); if (!$result) { - throw new RestException(404, 'Commercial Proposal not found'); + throw new RestException(404, 'Commercial Proposal not found'); } if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $request_data = (object) $request_data; + $request_data = (object) $request_data; - $updateRes = $this->propal->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - 'HT', - 0, - $request_data->info_bits, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $request_data->fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->date_start, - $request_data->date_end, - $request_data->array_options, - $request_data->fk_unit, - $request_data->origin, - $request_data->origin_id, - $request_data->multicurrency_subprice, - $request_data->fk_remise_except - ); + $updateRes = $this->propal->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + 'HT', + 0, + $request_data->info_bits, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $request_data->fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->date_start, + $request_data->date_end, + $request_data->array_options, + $request_data->fk_unit, + $request_data->origin, + $request_data->origin_id, + $request_data->multicurrency_subprice, + $request_data->fk_remise_except + ); - if ($updateRes > 0) { - return $updateRes; - } else { - throw new RestException(400, $this->propal->error); - } - } + if ($updateRes > 0) { + return $updateRes; + } else { + throw new RestException(400, $this->propal->error); + } + } /** * Update a line of given commercial proposal @@ -388,37 +388,37 @@ class Proposals extends DolibarrApi throw new RestException(404, 'Proposal line not found'); } - $updateRes = $this->propal->updateline( - $lineid, - isset($request_data->subprice) ? $request_data->subprice : $propalline->subprice, - isset($request_data->qty) ? $request_data->qty : $propalline->qty, - isset($request_data->remise_percent) ? $request_data->remise_percent : $propalline->remise_percent, - isset($request_data->tva_tx) ? $request_data->tva_tx : $propalline->tva_tx, - isset($request_data->localtax1_tx) ? $request_data->localtax1_tx : $propalline->localtax1_tx, - isset($request_data->localtax2_tx) ? $request_data->localtax2_tx : $propalline->localtax2_tx, - isset($request_data->desc) ? $request_data->desc : $propalline->desc, - 'HT', - isset($request_data->info_bits) ? $request_data->info_bits : $propalline->info_bits, - isset($request_data->special_code) ? $request_data->special_code : $propalline->special_code, - isset($request_data->fk_parent_line) ? $request_data->fk_parent_line : $propalline->fk_parent_line, - 0, - isset($request_data->fk_fournprice) ? $request_data->fk_fournprice : $propalline->fk_fournprice, - isset($request_data->pa_ht) ? $request_data->pa_ht : $propalline->pa_ht, - isset($request_data->label) ? $request_data->label : $propalline->label, - isset($request_data->product_type) ? $request_data->product_type : $propalline->product_type, - isset($request_data->date_start) ? $request_data->date_start : $propalline->date_start, - isset($request_data->date_end) ? $request_data->date_end : $propalline->date_end, - isset($request_data->array_options) ? $request_data->array_options : $propalline->array_options, - isset($request_data->fk_unit) ? $request_data->fk_unit : $propalline->fk_unit, - isset($request_data->multicurrency_subprice) ? $request_data->multicurrency_subprice : $propalline->subprice - ); + $updateRes = $this->propal->updateline( + $lineid, + isset($request_data->subprice) ? $request_data->subprice : $propalline->subprice, + isset($request_data->qty) ? $request_data->qty : $propalline->qty, + isset($request_data->remise_percent) ? $request_data->remise_percent : $propalline->remise_percent, + isset($request_data->tva_tx) ? $request_data->tva_tx : $propalline->tva_tx, + isset($request_data->localtax1_tx) ? $request_data->localtax1_tx : $propalline->localtax1_tx, + isset($request_data->localtax2_tx) ? $request_data->localtax2_tx : $propalline->localtax2_tx, + isset($request_data->desc) ? $request_data->desc : $propalline->desc, + 'HT', + isset($request_data->info_bits) ? $request_data->info_bits : $propalline->info_bits, + isset($request_data->special_code) ? $request_data->special_code : $propalline->special_code, + isset($request_data->fk_parent_line) ? $request_data->fk_parent_line : $propalline->fk_parent_line, + 0, + isset($request_data->fk_fournprice) ? $request_data->fk_fournprice : $propalline->fk_fournprice, + isset($request_data->pa_ht) ? $request_data->pa_ht : $propalline->pa_ht, + isset($request_data->label) ? $request_data->label : $propalline->label, + isset($request_data->product_type) ? $request_data->product_type : $propalline->product_type, + isset($request_data->date_start) ? $request_data->date_start : $propalline->date_start, + isset($request_data->date_end) ? $request_data->date_end : $propalline->date_end, + isset($request_data->array_options) ? $request_data->array_options : $propalline->array_options, + isset($request_data->fk_unit) ? $request_data->fk_unit : $propalline->fk_unit, + isset($request_data->multicurrency_subprice) ? $request_data->multicurrency_subprice : $propalline->subprice + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; } /** @@ -432,13 +432,13 @@ class Proposals extends DolibarrApi * * @return int * - * @throws RestException 401 - * @throws RestException 404 + * @throws RestException 401 + * @throws RestException 404 */ - public function deleteLine($id, $lineid) - { + public function deleteLine($id, $lineid) + { if (!DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401); + throw new RestException(401); } $result = $this->propal->fetch($id); @@ -460,7 +460,7 @@ class Proposals extends DolibarrApi } } - /** + /** * Add a contact type of given commercial proposal * * @param int $id Id of commercial proposal to update @@ -471,66 +471,66 @@ class Proposals extends DolibarrApi * * @return int * - * @throws RestException 401 - * @throws RestException 404 + * @throws RestException 401 + * @throws RestException 404 */ - public function postContact($id, $contactid, $type) - { - if (!DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401); - } + public function postContact($id, $contactid, $type) + { + if (!DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } - $result = $this->propal->fetch($id); + $result = $this->propal->fetch($id); if (!$result) { throw new RestException(404, 'Proposal not found'); } - if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) { - throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER'); - } + if (!in_array($type, array('BILLING', 'SHIPPING', 'CUSTOMER'), true)) { + throw new RestException(500, 'Availables types: BILLING, SHIPPING OR CUSTOMER'); + } - if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - $result = $this->propal->add_contact($contactid, $type, 'external'); + $result = $this->propal->add_contact($contactid, $type, 'external'); - if (!$result) { - throw new RestException(500, 'Error when added the contact'); - } + if (!$result) { + throw new RestException(500, 'Error when added the contact'); + } - return $this->propal; - } + return $this->propal; + } - /** - * Delete a contact type of given commercial proposal - * - * @param int $id Id of commercial proposal to update - * @param int $contactid Row key of the contact in the array contact_ids. - * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER). - * - * @url DELETE {id}/contact/{contactid}/{type} - * - * @return int - * - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 - */ - public function deleteContact($id, $contactid, $type) - { - if (!DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401); - } + /** + * Delete a contact type of given commercial proposal + * + * @param int $id Id of commercial proposal to update + * @param int $contactid Row key of the contact in the array contact_ids. + * @param string $type Type of the contact (BILLING, SHIPPING, CUSTOMER). + * + * @url DELETE {id}/contact/{contactid}/{type} + * + * @return int + * + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 + */ + public function deleteContact($id, $contactid, $type) + { + if (!DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } - $result = $this->propal->fetch($id); + $result = $this->propal->fetch($id); if (!$result) { throw new RestException(404, 'Proposal not found'); } - if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } @@ -547,7 +547,7 @@ class Proposals extends DolibarrApi } return $this->_cleanObjectDatas($this->propal); - } + } /** * Update commercial proposal general fields (won't touch lines of commercial proposal) @@ -556,12 +556,12 @@ class Proposals extends DolibarrApi * @param array $request_data Datas * * @return int - */ - public function put($id, $request_data = null) - { - if (!DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401); - } + */ + public function put($id, $request_data = null) + { + if (!DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } $result = $this->propal->fetch($id); if (!$result) { @@ -631,14 +631,14 @@ class Proposals extends DolibarrApi } /** - * Set a proposal to draft - * - * @param int $id Order ID - * - * @url POST {id}/settodraft - * - * @return array - */ + * Set a proposal to draft + * + * @param int $id Order ID + * + * @url POST {id}/settodraft + * + * @return array + */ public function settodraft($id) { if (!DolibarrApiAccess::$user->rights->propal->creer) { @@ -690,14 +690,14 @@ class Proposals extends DolibarrApi * @url POST {id}/validate * * @throws RestException 304 - * @throws RestException 401 - * @throws RestException 404 - * @throws RestException 500 - * - * @return array - */ - public function validate($id, $notrigger = 0) - { + * @throws RestException 401 + * @throws RestException 404 + * @throws RestException 500 + * + * @return array + */ + public function validate($id, $notrigger = 0) + { if (!DolibarrApiAccess::$user->rights->propal->creer) { throw new RestException(401); } @@ -718,19 +718,19 @@ class Proposals extends DolibarrApi throw new RestException(500, 'Error when validating Commercial Proposal: '.$this->propal->error); } - $result = $this->propal->fetch($id); - if (!$result) { - throw new RestException(404, 'Commercial Proposal not found'); - } + $result = $this->propal->fetch($id); + if (!$result) { + throw new RestException(404, 'Commercial Proposal not found'); + } - if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $this->propal->fetchObjectLinked(); + $this->propal->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->propal); - } + return $this->_cleanObjectDatas($this->propal); + } /** * Close (Accept or refuse) a quote / commercial proposal @@ -780,47 +780,47 @@ class Proposals extends DolibarrApi return $this->_cleanObjectDatas($this->propal); } - /** - * Set a commercial proposal billed. Could be also called setbilled - * - * @param int $id Commercial proposal ID - * - * @url POST {id}/setinvoiced - * - * @return array - */ - public function setinvoiced($id) - { - if (!DolibarrApiAccess::$user->rights->propal->creer) { - throw new RestException(401); - } - $result = $this->propal->fetch($id); - if (!$result) { - throw new RestException(404, 'Commercial Proposal not found'); - } + /** + * Set a commercial proposal billed. Could be also called setbilled + * + * @param int $id Commercial proposal ID + * + * @url POST {id}/setinvoiced + * + * @return array + */ + public function setinvoiced($id) + { + if (!DolibarrApiAccess::$user->rights->propal->creer) { + throw new RestException(401); + } + $result = $this->propal->fetch($id); + if (!$result) { + throw new RestException(404, 'Commercial Proposal not found'); + } - if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $result = $this->propal->classifyBilled(DolibarrApiAccess::$user); - if ($result < 0) { - throw new RestException(500, 'Error : '.$this->propal->error); - } + $result = $this->propal->classifyBilled(DolibarrApiAccess::$user); + if ($result < 0) { + throw new RestException(500, 'Error : '.$this->propal->error); + } - $result = $this->propal->fetch($id); - if (!$result) { - throw new RestException(404, 'Proposal not found'); - } + $result = $this->propal->fetch($id); + if (!$result) { + throw new RestException(404, 'Proposal not found'); + } - if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if (!DolibarrApi::_checkAccessToResource('propal', $this->propal->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - $this->propal->fetchObjectLinked(); + $this->propal->fetchObjectLinked(); - return $this->_cleanObjectDatas($this->propal); - } + return $this->_cleanObjectDatas($this->propal); + } /** @@ -842,25 +842,25 @@ class Proposals extends DolibarrApi } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore - /** - * Clean sensible object datas - * - * @param object $object Object to clean - * @return array Array of cleaned object properties - */ - protected function _cleanObjectDatas($object) - { - // phpcs:enable - $object = parent::_cleanObjectDatas($object); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore + /** + * Clean sensible object datas + * + * @param object $object Object to clean + * @return array Array of cleaned object properties + */ + protected function _cleanObjectDatas($object) + { + // phpcs:enable + $object = parent::_cleanObjectDatas($object); - unset($object->note); - unset($object->name); - unset($object->lastname); - unset($object->firstname); - unset($object->civility_id); - unset($object->address); + unset($object->note); + unset($object->name); + unset($object->lastname); + unset($object->firstname); + unset($object->civility_id); + unset($object->address); - return $object; - } + return $object; + } } diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index 7ccbd8950b5..b9fbe8a6c1d 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -573,13 +573,13 @@ class Orders extends DolibarrApi $contacts = $this->commande->liste_contact(); foreach ($contacts as $contact) { - if ($contact['id'] == $contactid && $contact['code'] == $type) { - $result = $this->commande->delete_contact($contact['rowid']); + if ($contact['id'] == $contactid && $contact['code'] == $type) { + $result = $this->commande->delete_contact($contact['rowid']); - if (!$result) { - throw new RestException(500, 'Error when deleted the contact'); - } - } + if (!$result) { + throw new RestException(500, 'Error when deleted the contact'); + } + } } return array( diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index 974ba750dd1..5035e6a1366 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -109,15 +109,15 @@ if (!$sortfield) $sortfield = 'b.datev,b.dateo,b.rowid'; $object = new Account($db); if ($id > 0 || !empty($ref)) { - $result = $object->fetch($id, $ref); - $search_account = $object->id; // Force the search field on id of account + $result = $object->fetch($id, $ref); + $search_account = $object->id; // Force the search field on id of account - if (!($object->id > 0)) - { - $langs->load("errors"); - print($langs->trans('ErrorRecordNotFound')); - exit; - } + if (!($object->id > 0)) + { + $langs->load("errors"); + print($langs->trans('ErrorRecordNotFound')); + exit; + } } $mode_balance_ok = false; @@ -137,20 +137,20 @@ $extrafields->fetch_name_optionals_label('banktransaction'); $search_array_options = $extrafields->getOptionalsFromPost('banktransaction', '', 'search_'); $arrayfields = array( - 'b.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), - 'b.label'=>array('label'=>$langs->trans("Description"), 'checked'=>1), - 'b.dateo'=>array('label'=>$langs->trans("DateOperationShort"), 'checked'=>1), - 'b.datev'=>array('label'=>$langs->trans("DateValueShort"), 'checked'=>1), - 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), - 'b.num_chq'=>array('label'=>$langs->trans("Numero"), 'checked'=>1), - 'bu.label'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>500), - 'ba.ref'=>array('label'=>$langs->trans("BankAccount"), 'checked'=>(($id > 0 || !empty($ref)) ? 0 : 1), 'position'=>1000), - 'b.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1, 'position'=>600), - 'b.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1, 'position'=>605), + 'b.rowid'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), + 'b.label'=>array('label'=>$langs->trans("Description"), 'checked'=>1), + 'b.dateo'=>array('label'=>$langs->trans("DateOperationShort"), 'checked'=>1), + 'b.datev'=>array('label'=>$langs->trans("DateValueShort"), 'checked'=>1), + 'type'=>array('label'=>$langs->trans("Type"), 'checked'=>1), + 'b.num_chq'=>array('label'=>$langs->trans("Numero"), 'checked'=>1), + 'bu.label'=>array('label'=>$langs->trans("ThirdParty"), 'checked'=>1, 'position'=>500), + 'ba.ref'=>array('label'=>$langs->trans("BankAccount"), 'checked'=>(($id > 0 || !empty($ref)) ? 0 : 1), 'position'=>1000), + 'b.debit'=>array('label'=>$langs->trans("Debit"), 'checked'=>1, 'position'=>600), + 'b.credit'=>array('label'=>$langs->trans("Credit"), 'checked'=>1, 'position'=>605), 'balancebefore'=>array('label'=>$langs->trans("BalanceBefore"), 'checked'=>0, 'position'=>1000), 'balance'=>array('label'=>$langs->trans("Balance"), 'checked'=>1, 'position'=>1001), 'b.num_releve'=>array('label'=>$langs->trans("AccountStatement"), 'checked'=>1, 'position'=>1010), - 'b.conciliated'=>array('label'=>$langs->trans("Conciliated"), 'enabled'=> $object->rappro, 'checked'=>($action == 'reconcile' ? 1 : 0), 'position'=>1020), + 'b.conciliated'=>array('label'=>$langs->trans("Conciliated"), 'enabled'=> $object->rappro, 'checked'=>($action == 'reconcile' ? 1 : 0), 'position'=>1020), ); // Extra fields if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) @@ -181,10 +181,10 @@ 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 { - $search_dt_start = ''; - $search_dt_end = ''; - $search_dv_start = ''; - $search_dv_end = ''; + $search_dt_start = ''; + $search_dt_end = ''; + $search_dv_start = ''; + $search_dv_end = ''; $search_type = ""; $search_debit = ""; $search_credit = ""; @@ -203,56 +203,56 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' if (empty($reshook)) { - $objectclass = 'Account'; - $objectlabel = 'BankTransaction'; - $permissiontoread = $user->rights->banque->lire; - $permissiontodelete = $user->rights->banque->supprimer; - $uploaddir = $conf->bank->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + $objectclass = 'Account'; + $objectlabel = 'BankTransaction'; + $permissiontoread = $user->rights->banque->lire; + $permissiontodelete = $user->rights->banque->supprimer; + $uploaddir = $conf->bank->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; } // Conciliation if ((GETPOST('confirm_savestatement', 'alpha') || GETPOST('confirm_reconcile', 'alpha')) && $user->rights->banque->consolidate) { - $error = 0; + $error = 0; - // Definition, nettoyage parametres - $num_releve = GETPOST("num_releve", "alpha"); + // Definition, nettoyage parametres + $num_releve = GETPOST("num_releve", "alpha"); - if ($num_releve) - { - $bankline = new AccountLine($db); - if (isset($_POST['rowid']) && is_array($_POST['rowid'])) - { - foreach ($_POST['rowid'] as $row) - { - if ($row > 0) - { - $result = $bankline->fetch($row); - $bankline->num_releve = $num_releve; //$_POST["num_releve"]; - $result = $bankline->update_conciliation($user, GETPOST("cat"), GETPOST('confirm_reconcile', 'alpha') ? 1 : 0); // If we confirm_reconcile, we set flag 'rappro' to 1. - if ($result < 0) - { - setEventMessages($bankline->error, $bankline->errors, 'errors'); - $error++; - break; - } - } - } - } else { - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("NoRecordSelected"), null, 'errors'); - } - } else { - $error++; - $langs->load("errors"); - setEventMessages($langs->trans("ErrorPleaseTypeBankTransactionReportName"), null, 'errors'); - } + if ($num_releve) + { + $bankline = new AccountLine($db); + if (isset($_POST['rowid']) && is_array($_POST['rowid'])) + { + foreach ($_POST['rowid'] as $row) + { + if ($row > 0) + { + $result = $bankline->fetch($row); + $bankline->num_releve = $num_releve; //$_POST["num_releve"]; + $result = $bankline->update_conciliation($user, GETPOST("cat"), GETPOST('confirm_reconcile', 'alpha') ? 1 : 0); // If we confirm_reconcile, we set flag 'rappro' to 1. + if ($result < 0) + { + setEventMessages($bankline->error, $bankline->errors, 'errors'); + $error++; + break; + } + } + } + } else { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("NoRecordSelected"), null, 'errors'); + } + } else { + $error++; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorPleaseTypeBankTransactionReportName"), null, 'errors'); + } - if (!$error) - { - $param = 'action=reconcile&contextpage=banktransactionlist&id='.$id.'&search_account='.$id; + if (!$error) + { + $param = 'action=reconcile&contextpage=banktransactionlist&id='.$id.'&search_account='.$id; $param .= '&search_conciliated='.urlencode($search_conciliated); if ($page) $param .= '&page='.urlencode($page); if ($offset) $param .= '&offset='.urlencode($offset); @@ -268,85 +268,85 @@ if ((GETPOST('confirm_savestatement', 'alpha') || GETPOST('confirm_reconcile', ' if ($search_credit) $param .= '&search_credit='.urlencode($search_credit); $param .= '&sortfield='.urlencode($sortfield).'&sortorder='.urlencode($sortorder); header('Location: '.$_SERVER["PHP_SELF"].'?'.$param); // To avoid to submit twice and allow the back button - exit; - } + exit; + } } if (GETPOST('save') && !$cancel && $user->rights->banque->modifier) { - $error = 0; + $error = 0; - if (price2num($_POST["addcredit"]) > 0) - { - $amount = price2num($_POST["addcredit"]); - } else { - $amount = - price2num($_POST["adddebit"]); - } + if (price2num($_POST["addcredit"]) > 0) + { + $amount = price2num($_POST["addcredit"]); + } else { + $amount = - price2num($_POST["adddebit"]); + } - $operation = GETPOST("operation", 'alpha'); - $num_chq = GETPOST("num_chq", 'alpha'); - $label = GETPOST("label", 'alpha'); - $cat1 = GETPOST("cat1", 'alpha'); + $operation = GETPOST("operation", 'alpha'); + $num_chq = GETPOST("num_chq", 'alpha'); + $label = GETPOST("label", 'alpha'); + $cat1 = GETPOST("cat1", 'alpha'); - $bankaccountid = $id; - if (GETPOST('add_account', 'int') > 0) $bankaccountid = GETPOST('add_account', 'int'); + $bankaccountid = $id; + if (GETPOST('add_account', 'int') > 0) $bankaccountid = GETPOST('add_account', 'int'); - if (!$dateop) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - } - if (!$operation) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - } - if (!$label) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); - } - if (!$amount) { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); - } - if (!$bankaccountid > 0) - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount")), null, 'errors'); - } - /*if (! empty($conf->accounting->enabled) && (empty($search_accountancy_code) || $search_accountancy_code == '-1')) + if (!$dateop) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); + } + if (!$operation) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + } + if (!$label) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors'); + } + if (!$amount) { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Amount")), null, 'errors'); + } + if (!$bankaccountid > 0) + { + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("BankAccount")), null, 'errors'); + } + /*if (! empty($conf->accounting->enabled) && (empty($search_accountancy_code) || $search_accountancy_code == '-1')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AccountAccounting")), null, 'errors'); $error++; }*/ - if (!$error && !empty($conf->global->BANK_USE_OLD_VARIOUS_PAYMENT)) - { - $objecttmp = new Account($db); - $objecttmp->fetch($bankaccountid); - $insertid = $objecttmp->addline($dateop, $operation, $label, $amount, $num_chq, ($cat1 > 0 ? $cat1 : 0), $user, '', '', $search_accountancy_code); - if ($insertid > 0) - { - setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); - header("Location: ".$_SERVER['PHP_SELF'].($id ? "?id=".$id : '')); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } else { - $action = 'addline'; - } + if (!$error && !empty($conf->global->BANK_USE_OLD_VARIOUS_PAYMENT)) + { + $objecttmp = new Account($db); + $objecttmp->fetch($bankaccountid); + $insertid = $objecttmp->addline($dateop, $operation, $label, $amount, $num_chq, ($cat1 > 0 ? $cat1 : 0), $user, '', '', $search_accountancy_code); + if ($insertid > 0) + { + setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); + header("Location: ".$_SERVER['PHP_SELF'].($id ? "?id=".$id : '')); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + $action = 'addline'; + } } if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->banque->modifier) { - $accline = new AccountLine($db); - $result = $accline->fetch(GETPOST("rowid", "int")); - $result = $accline->delete($user); - if ($result <= 0) { - setEventMessages($accline->error, $accline->errors, 'errors'); - } else { - setEventMessages('RecordDeleted', null, 'mesgs'); - } + $accline = new AccountLine($db); + $result = $accline->fetch(GETPOST("rowid", "int")); + $result = $accline->delete($user); + if ($result <= 0) { + setEventMessages($accline->error, $accline->errors, 'errors'); + } else { + setEventMessages('RecordDeleted', null, 'mesgs'); + } } @@ -419,43 +419,43 @@ if ($id > 0 || !empty($ref)) $helpurl = ""; llxHeader('', $title, $helpurl); - // Load bank groups - require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; - $bankcateg = new BankCateg($db); + // Load bank groups + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/bankcateg.class.php'; + $bankcateg = new BankCateg($db); - foreach ($bankcateg->fetchAll() as $bankcategory) { - $options[$bankcategory->id] = $bankcategory->label; - } + foreach ($bankcateg->fetchAll() as $bankcategory) { + $options[$bankcategory->id] = $bankcategory->label; + } - // Bank card - $head = bank_prepare_head($object); - dol_fiche_head($head, 'journal', $langs->trans("FinancialAccount"), 0, 'account'); + // Bank card + $head = bank_prepare_head($object); + dol_fiche_head($head, 'journal', $langs->trans("FinancialAccount"), 0, 'account'); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1); - dol_fiche_end(); + dol_fiche_end(); - /* + /* * Buttons actions */ - if ($action != 'reconcile') - { - if ($object->canBeConciliated() > 0) - { - // If not cash account and can be reconciliate - if ($user->rights->banque->consolidate) { - $newparam = $param; - $newparam = preg_replace('/search_conciliated=\d+/i', '', $newparam); - $buttonreconcile = ''.$langs->trans("Conciliate").''; - } else { - $buttonreconcile = ''.$langs->trans("Conciliate").''; - } - } - } + if ($action != 'reconcile') + { + if ($object->canBeConciliated() > 0) + { + // If not cash account and can be reconciliate + if ($user->rights->banque->consolidate) { + $newparam = $param; + $newparam = preg_replace('/search_conciliated=\d+/i', '', $newparam); + $buttonreconcile = ''.$langs->trans("Conciliate").''; + } else { + $buttonreconcile = ''.$langs->trans("Conciliate").''; + } + } + } } else { llxHeader('', $langs->trans("BankTransactions"), '', '', 0, 0, array(), array(), $param); } @@ -538,25 +538,25 @@ $nbtotalofrecords = ''; $nbtotalofpages = 0; if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { - $result = $db->query($sql); - $nbtotalofrecords = $db->num_rows($result); - $nbtotalofpages = ceil($nbtotalofrecords / $limit); + $result = $db->query($sql); + $nbtotalofrecords = $db->num_rows($result); + $nbtotalofpages = ceil($nbtotalofrecords / $limit); } if (($id > 0 || !empty($ref)) && ((string) $page == '')) { - // We open a list of transaction of a dedicated account and no page was set by defaut - // We force on last page. - $page = ($nbtotalofpages - 1); - $offset = $limit * $page; - if ($page < 0) $page = 0; + // We open a list of transaction of a dedicated account and no page was set by defaut + // We force on last page. + $page = ($nbtotalofpages - 1); + $offset = $limit * $page; + if ($page < 0) $page = 0; } if ($page >= $nbtotalofpages) { - // If we made a search and result has low page than the page number we were on - $page = ($nbtotalofpages - 1); - $offset = $limit * $page; - if ($page < 0) $page = 0; + // If we made a search and result has low page than the page number we were on + $page = ($nbtotalofpages - 1); + $offset = $limit * $page; + if ($page < 0) $page = 0; } @@ -582,23 +582,23 @@ if ($resql) $arrayofselected = is_array($toselect) ? $toselect : array(); - // List of mass actions available - $arrayofmassactions = array( - //'presend'=>$langs->trans("SendByMail"), - //'builddoc'=>$langs->trans("PDFMerge"), - ); - //if ($user->rights->bank->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); - $massactionbutton = $form->selectMassAction('', $arrayofmassactions); + // List of mass actions available + $arrayofmassactions = array( + //'presend'=>$langs->trans("SendByMail"), + //'builddoc'=>$langs->trans("PDFMerge"), + ); + //if ($user->rights->bank->supprimer) $arrayofmassactions['predelete']=''.$langs->trans("Delete"); + if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + $massactionbutton = $form->selectMassAction('', $arrayofmassactions); - // Confirmation delete - if ($action == 'delete') - { - $text = $langs->trans('ConfirmDeleteTransaction'); - print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&rowid='.GETPOST("rowid"), $langs->trans('DeleteTransaction'), $text, 'confirm_delete', null, '', 1); - } + // Confirmation delete + if ($action == 'delete') + { + $text = $langs->trans('ConfirmDeleteTransaction'); + print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&rowid='.GETPOST("rowid"), $langs->trans('DeleteTransaction'), $text, 'confirm_delete', null, '', 1); + } - // Lines of title fields + // Lines of title fields print ''."\n"; if ($optioncss != '') print ''; print ''; @@ -607,7 +607,7 @@ if ($resql) print ''; print ''; print ''; - print ''; + print ''; print ''; print ''; if (GETPOST('bid')) print ''; @@ -615,54 +615,54 @@ if ($resql) // Form to reconcile if ($user->rights->banque->consolidate && $action == 'reconcile') { - print '
'; - print ''.$langs->trans("InputReceiptNumber").': '; - print ''; // The only default value is value we just entered - print '
'; - if (is_array($options) && count($options)) - { - print $langs->trans("EventualyAddCategory").': '; - print Form::selectarray('cat', $options, GETPOST('cat'), 1); - } - print '
'.$langs->trans("ThenCheckLinesAndConciliate").' '; - print ''; - print ' '.$langs->trans("or").' '; - print ''; - print ' '.$langs->trans("or").' '; - print ''; + print '
'; + print ''.$langs->trans("InputReceiptNumber").': '; + print ''; // The only default value is value we just entered + print '
'; + if (is_array($options) && count($options)) + { + print $langs->trans("EventualyAddCategory").': '; + print Form::selectarray('cat', $options, GETPOST('cat'), 1); + } + print '
'.$langs->trans("ThenCheckLinesAndConciliate").' '; + print ''; + print ' '.$langs->trans("or").' '; + print ''; + print ' '.$langs->trans("or").' '; + print ''; print '
'; - // Show last bank statements - $nbmax = 15; // We accept to show last 15 receipts (so we can have more than one year) - $liste = ""; - $sql = "SELECT DISTINCT num_releve FROM ".MAIN_DB_PREFIX."bank"; - $sql .= " WHERE fk_account=".$object->id." AND num_releve IS NOT NULL"; - $sql .= $db->order("num_releve", "DESC"); - $sql .= $db->plimit($nbmax + 1); - print '
'; - print $langs->trans("LastAccountStatements").' : '; - $resqlr = $db->query($sql); - if ($resqlr) - { - $numr = $db->num_rows($resqlr); - $i = 0; - $last_ok = 0; - while (($i < $numr) && ($i < $nbmax)) - { - $objr = $db->fetch_object($resqlr); - if (!$last_ok) { - $last_releve = $objr->num_releve; - $last_ok = 1; - } - $i++; - $liste = ''.$objr->num_releve.'   '.$liste; - } - if ($numr >= $nbmax) $liste = "...   ".$liste; - print $liste; - if ($numr <= 0) print ''.$langs->trans("None").''; - } else { - dol_print_error($db); - } + // Show last bank statements + $nbmax = 15; // We accept to show last 15 receipts (so we can have more than one year) + $liste = ""; + $sql = "SELECT DISTINCT num_releve FROM ".MAIN_DB_PREFIX."bank"; + $sql .= " WHERE fk_account=".$object->id." AND num_releve IS NOT NULL"; + $sql .= $db->order("num_releve", "DESC"); + $sql .= $db->plimit($nbmax + 1); + print '
'; + print $langs->trans("LastAccountStatements").' : '; + $resqlr = $db->query($sql); + if ($resqlr) + { + $numr = $db->num_rows($resqlr); + $i = 0; + $last_ok = 0; + while (($i < $numr) && ($i < $nbmax)) + { + $objr = $db->fetch_object($resqlr); + if (!$last_ok) { + $last_releve = $objr->num_releve; + $last_ok = 1; + } + $i++; + $liste = ''.$objr->num_releve.'   '.$liste; + } + if ($numr >= $nbmax) $liste = "...   ".$liste; + print $liste; + if ($numr <= 0) print ''.$langs->trans("None").''; + } else { + dol_print_error($db); + } // Using BANK_REPORT_LAST_NUM_RELEVE to automatically report last num (or not) if (!empty($conf->global->BANK_REPORT_LAST_NUM_RELEVE)) @@ -775,13 +775,13 @@ if ($resql) { if (empty($conf->global->BANK_USE_OLD_VARIOUS_PAYMENT)) // If direct entries is done using miscellaneous payments { - $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/compta/bank/various_payment/card.php?action=create&accountid='.$search_account.'&backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.urlencode($search_account)), '', $user->rights->banque->modifier); + $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/compta/bank/various_payment/card.php?action=create&accountid='.$search_account.'&backtopage='.urlencode($_SERVER['PHP_SELF'].'?id='.urlencode($search_account)), '', $user->rights->banque->modifier); } else // If direct entries is not done using miscellaneous payments { - $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?action=addline&page='.$page.$param, '', $user->rights->banque->modifier); + $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?action=addline&page='.$page.$param, '', $user->rights->banque->modifier); } } else { - $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?action=addline&page='.$page.$param, '', -1); + $newcardbutton = dolGetButtonTitle($langs->trans('AddBankRecord'), '', 'fa fa-plus-circle', $_SERVER["PHP_SELF"].'?action=addline&page='.$page.$param, '', -1); } } @@ -854,66 +854,66 @@ if ($resql) print '
'."\n"; } - $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields + $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; + $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields - print '
'; - print '
'; print ''; print '
'.$langs->trans("LastInterventions", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllInterventions").''.$num.''.img_picto($langs->trans("Statistics"), 'stats').'
'.img_object($langs->trans("ShowPropal"), "propal").' '.$objp->ref.''.dol_print_date($db->jdate($objp->startdate)).''.dol_print_date($db->jdate($objp->startdate)).''.convertSecondToTime($objp->duration).''.$fichinter_static->getLibStatut(5).'
'; - print ''; + print ''; print '
'.$langs->trans("LastCustomersBills", ($num <= $MAXLIST ? "" : $MAXLIST)).''.$langs->trans("AllBills").''.$num.''.img_picto($langs->trans("Statistics"), 'stats').''.img_picto($langs->trans("Statistics"), 'stats').'
'; - print price($objp->total_ttc); - print ''; + print price($objp->total_ttc); + print ''.($facturestatic->LibStatut($objp->paye, $objp->statut, 5, $objp->am)).'
'."\n"; + print '
'; + print '
'."\n"; print ''; if (!empty($arrayfields['b.rowid']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.label']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.dateo']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.datev']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['type']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.num_chq']['checked'])) { - // Numero - print ''; + // Numero + print ''; } if (!empty($arrayfields['bu.label']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['ba.ref']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.debit']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['b.credit']['checked'])) { - print ''; + print ''; } if (!empty($arrayfields['balancebefore']['checked'])) { @@ -932,21 +932,21 @@ if ($resql) // Numero statement if (!empty($arrayfields['b.num_releve']['checked'])) { - print ''; + print ''; } // Conciliated if (!empty($arrayfields['b.conciliated']['checked'])) { - print ''; + print ''; } print ''; print ''; + print ''; print "\n"; // Fields title @@ -984,107 +984,107 @@ if ($resql) // Loop on each record $sign = 1; - $totalarray = array(); - while ($i < min($num, $limit)) - { - $objp = $db->fetch_object($resql); + $totalarray = array(); + while ($i < min($num, $limit)) + { + $objp = $db->fetch_object($resql); - // If we are in a situation where we need/can show balance, we calculate the start of balance - if (!$balancecalculated && (!empty($arrayfields['balancebefore']['checked']) || !empty($arrayfields['balance']['checked'])) && $mode_balance_ok) - { - if (!$search_account) - { - dol_print_error('', 'account is not defined but $mode_balance_ok is true'); - exit; - } + // If we are in a situation where we need/can show balance, we calculate the start of balance + if (!$balancecalculated && (!empty($arrayfields['balancebefore']['checked']) || !empty($arrayfields['balance']['checked'])) && $mode_balance_ok) + { + if (!$search_account) + { + dol_print_error('', 'account is not defined but $mode_balance_ok is true'); + exit; + } - // Loop on each record before - $sign = 1; - $i = 0; - $sqlforbalance = 'SELECT SUM(b.amount) as previoustotal'; - $sqlforbalance .= " FROM "; - $sqlforbalance .= " ".MAIN_DB_PREFIX."bank_account as ba,"; - $sqlforbalance .= " ".MAIN_DB_PREFIX."bank as b"; - $sqlforbalance .= " WHERE b.fk_account = ba.rowid"; - $sqlforbalance .= " AND ba.entity IN (".getEntity('bank_account').")"; - $sqlforbalance .= " AND b.fk_account = ".$search_account; - $sqlforbalance .= " AND (b.datev < '".$db->idate($db->jdate($objp->dv))."' OR (b.datev = '".$db->idate($db->jdate($objp->dv))."' AND (b.dateo < '".$db->idate($db->jdate($objp->do))."' OR (b.dateo = '".$db->idate($db->jdate($objp->do))."' AND b.rowid < ".$objp->rowid."))))"; - $resqlforbalance = $db->query($sqlforbalance); - //print $sqlforbalance; - if ($resqlforbalance) - { - $objforbalance = $db->fetch_object($resqlforbalance); - if ($objforbalance) - { - // If sort is desc,desc,desc then total of previous date + amount is the balancebefore of the previous line before the line to show - if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') - { - $balancebefore = $objforbalance->previoustotal + ($sign * $objp->amount); - } // If sort is asc,asc,asc then total of previous date is balance of line before the next line to show - else { - $balance = $objforbalance->previoustotal; - } - } - } else dol_print_error($db); + // Loop on each record before + $sign = 1; + $i = 0; + $sqlforbalance = 'SELECT SUM(b.amount) as previoustotal'; + $sqlforbalance .= " FROM "; + $sqlforbalance .= " ".MAIN_DB_PREFIX."bank_account as ba,"; + $sqlforbalance .= " ".MAIN_DB_PREFIX."bank as b"; + $sqlforbalance .= " WHERE b.fk_account = ba.rowid"; + $sqlforbalance .= " AND ba.entity IN (".getEntity('bank_account').")"; + $sqlforbalance .= " AND b.fk_account = ".$search_account; + $sqlforbalance .= " AND (b.datev < '".$db->idate($db->jdate($objp->dv))."' OR (b.datev = '".$db->idate($db->jdate($objp->dv))."' AND (b.dateo < '".$db->idate($db->jdate($objp->do))."' OR (b.dateo = '".$db->idate($db->jdate($objp->do))."' AND b.rowid < ".$objp->rowid."))))"; + $resqlforbalance = $db->query($sqlforbalance); + //print $sqlforbalance; + if ($resqlforbalance) + { + $objforbalance = $db->fetch_object($resqlforbalance); + if ($objforbalance) + { + // If sort is desc,desc,desc then total of previous date + amount is the balancebefore of the previous line before the line to show + if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') + { + $balancebefore = $objforbalance->previoustotal + ($sign * $objp->amount); + } // If sort is asc,asc,asc then total of previous date is balance of line before the next line to show + else { + $balance = $objforbalance->previoustotal; + } + } + } else dol_print_error($db); - $balancecalculated = true; + $balancecalculated = true; - // Output a line with start balance - if ($user->rights->banque->consolidate && $action == 'reconcile') - { - $tmpnbfieldbeforebalance = 0; - $tmpnbfieldafterbalance = 0; - $balancefieldfound = 0; - foreach ($arrayfields as $key => $val) - { - if ($key == 'balancebefore' || $key == 'balance') - { - $balancefieldfound++; - continue; - } - if (!empty($arrayfields[$key]['checked'])) - { - if (!$balancefieldfound) $tmpnbfieldbeforebalance++; - else $tmpnbfieldafterbalance++; - } - } - // Extra fields - $element = 'banktransaction'; - if (is_array($extrafields->attributes[$element]['label']) && count($extrafields->attributes[$element]['label'])) - { - foreach ($extrafields->attributes[$element]['label'] as $key => $val) - { - if (!empty($arrayfields["ef.".$key]['checked'])) - { - if (!empty($arrayfields[$key]['checked'])) - { - if (!$balancefieldfound) $tmpnbfieldbeforebalance++; - else $tmpnbfieldafterbalance++; - } - } - } - } + // Output a line with start balance + if ($user->rights->banque->consolidate && $action == 'reconcile') + { + $tmpnbfieldbeforebalance = 0; + $tmpnbfieldafterbalance = 0; + $balancefieldfound = 0; + foreach ($arrayfields as $key => $val) + { + if ($key == 'balancebefore' || $key == 'balance') + { + $balancefieldfound++; + continue; + } + if (!empty($arrayfields[$key]['checked'])) + { + if (!$balancefieldfound) $tmpnbfieldbeforebalance++; + else $tmpnbfieldafterbalance++; + } + } + // Extra fields + $element = 'banktransaction'; + if (is_array($extrafields->attributes[$element]['label']) && count($extrafields->attributes[$element]['label'])) + { + foreach ($extrafields->attributes[$element]['label'] as $key => $val) + { + if (!empty($arrayfields["ef.".$key]['checked'])) + { + if (!empty($arrayfields[$key]['checked'])) + { + if (!$balancefieldfound) $tmpnbfieldbeforebalance++; + else $tmpnbfieldafterbalance++; + } + } + } + } - print ''; - if ($tmpnbfieldbeforebalance) - { - print ''; - } + print ''; + if ($tmpnbfieldbeforebalance) + { + print ''; + } - if (!empty($arrayfields['balancebefore']['checked'])) - { - print ''; - } - if (!empty($arrayfields['balance']['checked'])) - { - print ''; - } + } + if (!empty($arrayfields['balance']['checked'])) + { + print ''; + } print ''; - print ''; - } - } + print ''; + } + } - if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') - { - $balance = price2num($balancebefore, 'MT'); // balance = balancebefore of previous line (sort is desc) - $balancebefore = price2num($balancebefore - ($sign * $objp->amount), 'MT'); - } else { + if ($sortfield == 'b.datev,b.dateo,b.rowid' && $sortorder == 'desc,desc,desc') + { + $balance = price2num($balancebefore, 'MT'); // balance = balancebefore of previous line (sort is desc) + $balancebefore = price2num($balancebefore - ($sign * $objp->amount), 'MT'); + } else { $balancebefore = price2num($balance, 'MT'); // balancebefore = balance of previous line (sort is asc) $balance = price2num($balance + ($sign * $objp->amount), 'MT'); } - if (empty($cachebankaccount[$objp->bankid])) - { - $bankaccounttmp = new Account($db); - $bankaccounttmp->fetch($objp->bankid); - $cachebankaccount[$objp->bankid] = $bankaccounttmp; - $bankaccount = $bankaccounttmp; - } else { - $bankaccount = $cachebankaccount[$objp->bankid]; - } + if (empty($cachebankaccount[$objp->bankid])) + { + $bankaccounttmp = new Account($db); + $bankaccounttmp->fetch($objp->bankid); + $cachebankaccount[$objp->bankid] = $bankaccounttmp; + $bankaccount = $bankaccounttmp; + } else { + $bankaccount = $cachebankaccount[$objp->bankid]; + } - if (empty($conf->global->BANK_COLORIZE_MOVEMENT)) { - $backgroundcolor = "class='oddeven'"; - } else { - if ($objp->amount < 0) - { - if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR1)) { - $color = '#fca955'; - } else { - $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR1; - } - $backgroundcolor = 'style="background: '.$color.';"'; - } else { - if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR2)) { - $color = '#7fdb86'; - } else { - $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR2; - } - $backgroundcolor = 'style="background: '.$color.';"'; - } - } + if (empty($conf->global->BANK_COLORIZE_MOVEMENT)) { + $backgroundcolor = "class='oddeven'"; + } else { + if ($objp->amount < 0) + { + if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR1)) { + $color = '#fca955'; + } else { + $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR1; + } + $backgroundcolor = 'style="background: '.$color.';"'; + } else { + if (empty($conf->global->BANK_COLORIZE_MOVEMENT_COLOR2)) { + $color = '#7fdb86'; + } else { + $color = '#'.$conf->global->BANK_COLORIZE_MOVEMENT_COLOR2; + } + $backgroundcolor = 'style="background: '.$color.';"'; + } + } - $banklinestatic->id = $objp->rowid; - $banklinestatic->ref = $objp->rowid; + $banklinestatic->id = $objp->rowid; + $banklinestatic->ref = $objp->rowid; - print ''; + print ''; - // Ref - if (!empty($arrayfields['b.rowid']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } + // Ref + if (!empty($arrayfields['b.rowid']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } - // Description - if (!empty($arrayfields['b.label']['checked'])) - { - print "'; - if (!$i) $totalarray['nbfield']++; - } + // Add links after description + $links = $bankaccountstatic->get_url($objp->rowid); + $cachebankaccount = array(); + foreach ($links as $key=>$val) + { + print ''; + if ($links[$key]['type'] == 'withdraw') + { + $banktransferstatic->id = $links[$key]['url_id']; + $banktransferstatic->ref = $links[$key]['label']; + print ' '.$banktransferstatic->getNomUrl(0); + } elseif ($links[$key]['type'] == 'payment') + { + $paymentstatic->id = $links[$key]['url_id']; + $paymentstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment + print ' '.$paymentstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_supplier') + { + $paymentsupplierstatic->id = $links[$key]['url_id']; + $paymentsupplierstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment + print ' '.$paymentsupplierstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_sc') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; + //print $langs->trans("SocialContributionPayment"); + print ''; + } elseif ($links[$key]['type'] == 'payment_vat') + { + $paymentvatstatic->id = $links[$key]['url_id']; + $paymentvatstatic->ref = $links[$key]['url_id']; + print ' '.$paymentvatstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_salary') + { + $paymentsalstatic->id = $links[$key]['url_id']; + $paymentsalstatic->ref = $links[$key]['url_id']; + print ' '.$paymentsalstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_loan') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; + print ''; + } elseif ($links[$key]['type'] == 'payment_donation') + { + print ''; + print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; + print ''; + } elseif ($links[$key]['type'] == 'payment_expensereport') + { + $paymentexpensereportstatic->id = $links[$key]['url_id']; + $paymentexpensereportstatic->ref = $links[$key]['url_id']; + print ' '.$paymentexpensereportstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'payment_various') + { + $paymentvariousstatic->id = $links[$key]['url_id']; + $paymentvariousstatic->ref = $links[$key]['url_id']; + print ' '.$paymentvariousstatic->getNomUrl(2); + } elseif ($links[$key]['type'] == 'banktransfert') + { + // Do not show link to transfer since there is no transfer card (avoid confusion). Can already be accessed from transaction detail. + if ($objp->amount > 0) + { + $banklinestatic->fetch($links[$key]['url_id']); + $bankstatic->id = $banklinestatic->fk_account; + $bankstatic->label = $banklinestatic->bank_account_ref; + print ' ('.$langs->trans("TransferFrom").' '; + print $bankstatic->getNomUrl(1, 'transactions'); + print ' '.$langs->trans("toward").' '; + $bankstatic->id = $objp->bankid; + $bankstatic->label = $objp->bankref; + print $bankstatic->getNomUrl(1, ''); + print ')'; + } else { + $bankstatic->id = $objp->bankid; + $bankstatic->label = $objp->bankref; + print ' ('.$langs->trans("TransferFrom").' '; + print $bankstatic->getNomUrl(1, ''); + print ' '.$langs->trans("toward").' '; + $banklinestatic->fetch($links[$key]['url_id']); + $bankstatic->id = $banklinestatic->fk_account; + $bankstatic->label = $banklinestatic->bank_account_ref; + print $bankstatic->getNomUrl(1, 'transactions'); + print ')'; + } + //var_dump($links); + } elseif ($links[$key]['type'] == 'company') + { + } elseif ($links[$key]['type'] == 'user') + { + } elseif ($links[$key]['type'] == 'member') + { + } elseif ($links[$key]['type'] == 'sc') + { + } else { + // Show link with label $links[$key]['label'] + if (!empty($objp->label) && !empty($links[$key]['label'])) print ' - '; + print ''; + if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) + { + // Label generique car entre parentheses. On l'affiche en le traduisant + if ($reg[1] == 'paiement') $reg[1] = 'Payment'; + print ' '.$langs->trans($reg[1]); + } else { + print ' '.$links[$key]['label']; + } + print ''; + } + } + print ''; + if (!$i) $totalarray['nbfield']++; + } - // Date ope - if (!empty($arrayfields['b.dateo']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } + // Date ope + if (!empty($arrayfields['b.dateo']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } - // Date value - if (!empty($arrayfields['b.datev']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } + // Date value + if (!empty($arrayfields['b.datev']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } - // Payment type - if (!empty($arrayfields['type']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } + // Payment type + if (!empty($arrayfields['type']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } - // Num cheque - if (!empty($arrayfields['b.num_chq']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } + // Num cheque + if (!empty($arrayfields['b.num_chq']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + } // Third party - if (!empty($arrayfields['bu.label']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } + if (!$i) $totalarray['nbfield']++; + } - // Bank account - if (!empty($arrayfields['ba.ref']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - } + if (!$i) $totalarray['nbfield']++; + } - // Debit - if (!empty($arrayfields['b.debit']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['totaldebfield'] = $totalarray['nbfield']; - } + // Debit + if (!empty($arrayfields['b.debit']['checked'])) + { + print '\n"; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['totaldebfield'] = $totalarray['nbfield']; + } - // Credit - if (!empty($arrayfields['b.credit']['checked'])) - { - print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['totalcredfield'] = $totalarray['nbfield']; - } + $totalarray['totalcred'] += $objp->amount; + } + print "\n"; + if (!$i) $totalarray['nbfield']++; + if (!$i) $totalarray['totalcredfield'] = $totalarray['nbfield']; + } - // Balance before - if (!empty($arrayfields['balancebefore']['checked'])) - { - if ($mode_balance_ok) - { - if ($balancebefore >= 0) - { - print ''; - } else { - print ''; - } - } else { - print ''; - } - if (!$i) $totalarray['nbfield']++; - } - // Balance - if (!empty($arrayfields['balance']['checked'])) - { - if ($mode_balance_ok) - { - if ($balance >= 0) - { - print ''; - } else { - print ''; - } - } else { - print ''; - } - if (!$i) $totalarray['nbfield']++; - } + // Balance before + if (!empty($arrayfields['balancebefore']['checked'])) + { + if ($mode_balance_ok) + { + if ($balancebefore >= 0) + { + print ''; + } else { + print ''; + } + } else { + print ''; + } + if (!$i) $totalarray['nbfield']++; + } + // Balance + if (!empty($arrayfields['balance']['checked'])) + { + if ($mode_balance_ok) + { + if ($balance >= 0) + { + print ''; + } else { + print ''; + } + } else { + print ''; + } + if (!$i) $totalarray['nbfield']++; + } - if (!empty($arrayfields['b.num_releve']['checked'])) - { - print ''; - if (!$i) - { - $totalarray['nbfield']++; - $posconciliatecol = $totalarray['nbfield']; - } - } + if (!empty($arrayfields['b.num_releve']['checked'])) + { + print ''; + if (!$i) + { + $totalarray['nbfield']++; + $posconciliatecol = $totalarray['nbfield']; + } + } - if (!empty($arrayfields['b.conciliated']['checked'])) - { - print ''; - if (!$i) $totalarray['nbfield']++; - } + if (!empty($arrayfields['b.conciliated']['checked'])) + { + print ''; + if (!$i) $totalarray['nbfield']++; + } - // Action edit/delete - print ''; - if (!$i) $totalarray['nbfield']++; + // Action edit/delete + print ''; + if (!$i) $totalarray['nbfield']++; - // Action column - print ''; - if (!$i) $totalarray['nbfield']++; + // Action column + print ''; + if (!$i) $totalarray['nbfield']++; print ""; @@ -1517,25 +1517,25 @@ if ($resql) // Show total line if (isset($totalarray['totaldebfield']) || isset($totalarray['totalcredfield'])) { - print ''; - $i = 0; - while ($i < $totalarray['nbfield']) - { - $i++; - if ($i == 1) - { - if ($num < $limit && empty($offset)) print ''; - else print ''; - } elseif ($totalarray['totaldebfield'] == $i) print ''; - elseif ($totalarray['totalcredfield'] == $i) print ''; - elseif ($i == $posconciliatecol) - { - print ''; - } else print ''; - } - print ''; + print ''; + $i = 0; + while ($i < $totalarray['nbfield']) + { + $i++; + if ($i == 1) + { + if ($num < $limit && empty($offset)) print ''; + else print ''; + } elseif ($totalarray['totaldebfield'] == $i) print ''; + elseif ($totalarray['totalcredfield'] == $i) print ''; + elseif ($i == $posconciliatecol) + { + print ''; + } else print ''; + } + print ''; } // If no record found @@ -1549,7 +1549,7 @@ if ($resql) print "
'; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print '    '; - $form->select_types_paiements(empty($search_type) ? '' : $search_type, 'search_type', '', 2, 1, 1, 0, 1, 'maxwidth100'); - print ''; + $form->select_types_paiements(empty($search_type) ? '' : $search_type, 'search_type', '', 2, 1, 1, 0, 1, 'maxwidth100'); + print ''; - $form->select_comptes($search_account, 'search_account', 0, '', 1, ($id > 0 || !empty($ref) ? ' disabled="disabled"' : ''), 0, 'maxwidth100'); - print ''; + $form->select_comptes($search_account, 'search_account', 0, '', 1, ($id > 0 || !empty($ref) ? ' disabled="disabled"' : ''), 0, 'maxwidth100'); + print ''; - print ''; - print ''; + print ''; + print ''; - print ''; - print ''; + print ''; + print ''; - print $form->selectyesno('search_conciliated', $search_conciliated, 1, false, 1); - print ''; + print $form->selectyesno('search_conciliated', $search_conciliated, 1, false, 1); + print ''; print ''; $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); print $searchpicto; - print '
'; - print ' '; - print '
'; + print ' '; + print ''; - print price(price2num($balance, 'MT'), 1, $langs); - print ''; + if (!empty($arrayfields['balancebefore']['checked'])) + { + print ''; print price(price2num($balance, 'MT'), 1, $langs); print ''; + print price(price2num($balance, 'MT'), 1, $langs); + print ''; print ''; @@ -1097,249 +1097,249 @@ if ($resql) print ''; print ' '; print '
'; - print $banklinestatic->getNomUrl(1); - print ''; + print $banklinestatic->getNomUrl(1); + print '"; + // Description + if (!empty($arrayfields['b.label']['checked'])) + { + print ""; - //print "rowid."&account=".$objp->fk_account."\">"; - $reg = array(); - preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthee on tente recherche de traduction - if ($reg[1] && $langs->trans($reg[1]) != $reg[1]) print $langs->trans($reg[1]); - else { - if ($objp->label == '(payment_salary)') { - print dol_trunc($langs->trans("SalaryPayment", 40)); - } else { - print dol_trunc($objp->label, 40); - } - } - //print " "; + //print "rowid."&account=".$objp->fk_account."\">"; + $reg = array(); + preg_match('/\((.+)\)/i', $objp->label, $reg); // Si texte entoure de parenthee on tente recherche de traduction + if ($reg[1] && $langs->trans($reg[1]) != $reg[1]) print $langs->trans($reg[1]); + else { + if ($objp->label == '(payment_salary)') { + print dol_trunc($langs->trans("SalaryPayment", 40)); + } else { + print dol_trunc($objp->label, 40); + } + } + //print " "; - // Add links after description - $links = $bankaccountstatic->get_url($objp->rowid); - $cachebankaccount = array(); - foreach ($links as $key=>$val) - { - print ''; - if ($links[$key]['type'] == 'withdraw') - { - $banktransferstatic->id = $links[$key]['url_id']; - $banktransferstatic->ref = $links[$key]['label']; - print ' '.$banktransferstatic->getNomUrl(0); - } elseif ($links[$key]['type'] == 'payment') - { - $paymentstatic->id = $links[$key]['url_id']; - $paymentstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment - print ' '.$paymentstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_supplier') - { - $paymentsupplierstatic->id = $links[$key]['url_id']; - $paymentsupplierstatic->ref = $links[$key]['url_id']; // FIXME This is id, not ref of payment - print ' '.$paymentsupplierstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_sc') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; - //print $langs->trans("SocialContributionPayment"); - print ''; - } elseif ($links[$key]['type'] == 'payment_vat') - { - $paymentvatstatic->id = $links[$key]['url_id']; - $paymentvatstatic->ref = $links[$key]['url_id']; - print ' '.$paymentvatstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_salary') - { - $paymentsalstatic->id = $links[$key]['url_id']; - $paymentsalstatic->ref = $links[$key]['url_id']; - print ' '.$paymentsalstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_loan') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; - print ''; - } elseif ($links[$key]['type'] == 'payment_donation') - { - print ''; - print ' '.img_object($langs->trans('ShowPayment'), 'payment').' '; - print ''; - } elseif ($links[$key]['type'] == 'payment_expensereport') - { - $paymentexpensereportstatic->id = $links[$key]['url_id']; - $paymentexpensereportstatic->ref = $links[$key]['url_id']; - print ' '.$paymentexpensereportstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'payment_various') - { - $paymentvariousstatic->id = $links[$key]['url_id']; - $paymentvariousstatic->ref = $links[$key]['url_id']; - print ' '.$paymentvariousstatic->getNomUrl(2); - } elseif ($links[$key]['type'] == 'banktransfert') - { - // Do not show link to transfer since there is no transfer card (avoid confusion). Can already be accessed from transaction detail. - if ($objp->amount > 0) - { - $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id = $banklinestatic->fk_account; - $bankstatic->label = $banklinestatic->bank_account_ref; - print ' ('.$langs->trans("TransferFrom").' '; - print $bankstatic->getNomUrl(1, 'transactions'); - print ' '.$langs->trans("toward").' '; - $bankstatic->id = $objp->bankid; - $bankstatic->label = $objp->bankref; - print $bankstatic->getNomUrl(1, ''); - print ')'; - } else { - $bankstatic->id = $objp->bankid; - $bankstatic->label = $objp->bankref; - print ' ('.$langs->trans("TransferFrom").' '; - print $bankstatic->getNomUrl(1, ''); - print ' '.$langs->trans("toward").' '; - $banklinestatic->fetch($links[$key]['url_id']); - $bankstatic->id = $banklinestatic->fk_account; - $bankstatic->label = $banklinestatic->bank_account_ref; - print $bankstatic->getNomUrl(1, 'transactions'); - print ')'; - } - //var_dump($links); - } elseif ($links[$key]['type'] == 'company') - { - } elseif ($links[$key]['type'] == 'user') - { - } elseif ($links[$key]['type'] == 'member') - { - } elseif ($links[$key]['type'] == 'sc') - { - } else { - // Show link with label $links[$key]['label'] - if (!empty($objp->label) && !empty($links[$key]['label'])) print ' - '; - print ''; - if (preg_match('/^\((.*)\)$/i', $links[$key]['label'], $reg)) - { - // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1] == 'paiement') $reg[1] = 'Payment'; - print ' '.$langs->trans($reg[1]); - } else { - print ' '.$links[$key]['label']; - } - print ''; - } - } - print ''; - print ''.dol_print_date($db->jdate($objp->do), "day").""; - print ' '; - print ''; - print ''; - print img_edit_remove()." "; - print ''; - print img_edit_add().""; - print ''; - print "'; + print ''.dol_print_date($db->jdate($objp->do), "day").""; + print ' '; + print ''; + print ''; + print img_edit_remove()." "; + print ''; + print img_edit_add().""; + print ''; + print "'; - print ''.dol_print_date($db->jdate($objp->dv), "day").""; - print ' '; - print ''; - print ''; - print img_edit_remove()." "; - print ''; - print img_edit_add().""; - print ''; - print "'; + print ''.dol_print_date($db->jdate($objp->dv), "day").""; + print ' '; + print ''; + print ''; + print img_edit_remove()." "; + print ''; + print img_edit_add().""; + print ''; + print "'; - $labeltype = ($langs->trans("PaymentTypeShort".$objp->fk_type) != "PaymentTypeShort".$objp->fk_type) ? $langs->trans("PaymentTypeShort".$objp->fk_type) : $langs->getLabelFromKey($db, $objp->fk_type, 'c_paiement', 'code', 'libelle', '', 1); - if ($labeltype == 'SOLD') print ' '; //$langs->trans("InitialBankBalance"); - else print $labeltype; - print "'; + $labeltype = ($langs->trans("PaymentTypeShort".$objp->fk_type) != "PaymentTypeShort".$objp->fk_type) ? $langs->trans("PaymentTypeShort".$objp->fk_type) : $langs->getLabelFromKey($db, $objp->fk_type, 'c_paiement', 'code', 'libelle', '', 1); + if ($labeltype == 'SOLD') print ' '; //$langs->trans("InitialBankBalance"); + else print $labeltype; + print "'.($objp->num_chq ? $objp->num_chq : "")."'.($objp->num_chq ? $objp->num_chq : "")."'; + if (!empty($arrayfields['bu.label']['checked'])) + { + print ''; if ($objp->url_id) { $companystatic->id = $objp->url_id; @@ -1357,157 +1357,157 @@ if ($resql) print ' '; } print ''; + // Bank account + if (!empty($arrayfields['ba.ref']['checked'])) + { + print ''; print $bankaccount->getNomUrl(1); print "'; - if ($objp->amount < 0) - { - print price($objp->amount * -1); - $totalarray['totaldeb'] += $objp->amount; - } - print "'; + if ($objp->amount < 0) + { + print price($objp->amount * -1); + $totalarray['totaldeb'] += $objp->amount; + } + print "'; - if ($objp->amount > 0) - { + // Credit + if (!empty($arrayfields['b.credit']['checked'])) + { + print ''; + if ($objp->amount > 0) + { print price($objp->amount); - $totalarray['totalcred'] += $objp->amount; - } - print " '.price($balancebefore).' '.price($balancebefore).'- '.price($balance).' '.price($balance).'- '.price($balancebefore).' '.price($balancebefore).'- '.price($balance).' '.price($balance).'-'; - // Transaction reconciliated or edit link - if ($bankaccount->canBeConciliated() > 0) - { - if ($objp->num_releve) - { - print ''.$objp->num_releve.''; - } - if (!$objp->conciliated && $action == 'reconcile') - { - if ($objp->num_releve) print ' '; - print 'rowid]) ? ' checked' : '').'>'; - } - } - print ''; + // Transaction reconciliated or edit link + if ($bankaccount->canBeConciliated() > 0) + { + if ($objp->num_releve) + { + print ''.$objp->num_releve.''; + } + if (!$objp->conciliated && $action == 'reconcile') + { + if ($objp->num_releve) print ' '; + print 'rowid]) ? ' checked' : '').'>'; + } + } + print ''; - print $objp->conciliated ? $langs->trans("Yes") : $langs->trans("No"); - print ''; + print $objp->conciliated ? $langs->trans("Yes") : $langs->trans("No"); + print ''; - // Transaction reconciliated or edit link - if ($objp->conciliated && $bankaccount->canBeConciliated() > 0) // If line not conciliated and account can be conciliated - { - print ''; - print img_edit(); - print ''; - } else { - if ($user->rights->banque->modifier || $user->rights->banque->consolidate) - { - print ''; - print img_edit(); - print ''; - } else { - print ''; - print img_view(); - print ''; - } - if ($bankaccount->canBeConciliated() > 0 && empty($objp->conciliated)) - { - if ($db->jdate($objp->dv) < ($now - $conf->bank->rappro->warning_delay)) - { - print ' '.img_warning($langs->trans("ReconciliationLate")); - } - } - if ($user->rights->banque->modifier) - { - print 'rowid.'&id='.$objp->bankid.'&page='.$page.'">'; - print img_delete('', 'class="marginleftonly"'); - print ''; - } - } - print ''; + // Transaction reconciliated or edit link + if ($objp->conciliated && $bankaccount->canBeConciliated() > 0) // If line not conciliated and account can be conciliated + { + print ''; + print img_edit(); + print ''; + } else { + if ($user->rights->banque->modifier || $user->rights->banque->consolidate) + { + print ''; + print img_edit(); + print ''; + } else { + print ''; + print img_view(); + print ''; + } + if ($bankaccount->canBeConciliated() > 0 && empty($objp->conciliated)) + { + if ($db->jdate($objp->dv) < ($now - $conf->bank->rappro->warning_delay)) + { + print ' '.img_warning($langs->trans("ReconciliationLate")); + } + } + if ($user->rights->banque->modifier) + { + print 'rowid.'&id='.$objp->bankid.'&page='.$page.'">'; + print img_delete('', 'class="marginleftonly"'); + print ''; + } + } + print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { - $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; - print ''; - } - print ''; + if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + { + $selected = 0; + if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + print ''; + } + print '
'.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price(-1 * $totalarray['totaldeb']).''.price($totalarray['totalcred']).''; - if ($user->rights->banque->consolidate && $action == 'reconcile') print ''; - print '
'.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price(-1 * $totalarray['totaldeb']).''.price($totalarray['totalcred']).''; + if ($user->rights->banque->consolidate && $action == 'reconcile') print ''; + print '
"; print ""; - print ''; + print ''; $db->free($resql); } else { dol_print_error($db); diff --git a/htdocs/compta/deplacement/card.php b/htdocs/compta/deplacement/card.php index 5b8b98135a1..fcd7c542eb2 100644 --- a/htdocs/compta/deplacement/card.php +++ b/htdocs/compta/deplacement/card.php @@ -31,7 +31,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/deplacement/class/deplacement.class.php' require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; if (!empty($conf->projet->enabled)) { - require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; } // Load translation files required by the page @@ -62,138 +62,138 @@ include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, if ($action == 'validate' && $user->rights->deplacement->creer) { - $object->fetch($id); - if ($object->statut == Deplacement::STATUS_DRAFT) - { - $result = $object->setStatut(1); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $object->fetch($id); + if ($object->statut == Deplacement::STATUS_DRAFT) + { + $result = $object->setStatut(1); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } elseif ($action == 'classifyrefunded' && $user->rights->deplacement->creer) { - $object->fetch($id); - if ($object->statut == Deplacement::STATUS_VALIDATED) - { - $result = $object->setStatut(Deplacement::STATUS_REFUNDED); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $object->fetch($id); + if ($object->statut == Deplacement::STATUS_VALIDATED) + { + $result = $object->setStatut(Deplacement::STATUS_REFUNDED); + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } elseif ($action == 'confirm_delete' && $confirm == "yes" && $user->rights->deplacement->supprimer) { - $result = $object->delete($id); - if ($result >= 0) - { - header("Location: index.php"); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->delete($id); + if ($result >= 0) + { + header("Location: index.php"); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } } elseif ($action == 'add' && $user->rights->deplacement->creer) { - if (!GETPOST('cancel', 'alpha')) - { - $error = 0; + if (!GETPOST('cancel', 'alpha')) + { + $error = 0; - $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount - $object->type = GETPOST('type', 'alpha'); - $object->socid = (int) GETPOST('socid', 'int'); - $object->fk_user = (int) GETPOST('fk_user', 'int'); - $object->note_private = GETPOST('note_private', 'alpha'); - $object->note_public = GETPOST('note_public', 'alpha'); - $object->statut = Deplacement::STATUS_DRAFT; + $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount + $object->type = GETPOST('type', 'alpha'); + $object->socid = (int) GETPOST('socid', 'int'); + $object->fk_user = (int) GETPOST('fk_user', 'int'); + $object->note_private = GETPOST('note_private', 'alpha'); + $object->note_public = GETPOST('note_public', 'alpha'); + $object->statut = Deplacement::STATUS_DRAFT; - if (!$object->date) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); - $error++; - } - if ($object->type == '-1') - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); - $error++; - } - if (!($object->fk_user > 0)) - { - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Person")), null, 'errors'); - $error++; - } + if (!$object->date) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); + $error++; + } + if ($object->type == '-1') + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); + $error++; + } + if (!($object->fk_user > 0)) + { + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Person")), null, 'errors'); + $error++; + } - if (!$error) - { - $id = $object->create($user); + if (!$error) + { + $id = $object->create($user); - if ($id > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'create'; - } - } else { - $action = 'create'; - } - } else { - header("Location: index.php"); - exit; - } + if ($id > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'create'; + } + } else { + $action = 'create'; + } + } else { + header("Location: index.php"); + exit; + } } // Update record elseif ($action == 'update' && $user->rights->deplacement->creer) { - if (!GETPOST('cancel', 'alpha')) - { - $result = $object->fetch($id); + if (!GETPOST('cancel', 'alpha')) + { + $result = $object->fetch($id); - $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount - $object->type = GETPOST('type', 'alpha'); - $object->socid = (int) GETPOST('socid', 'int'); - $object->fk_user = (int) GETPOST('fk_user', 'int'); - $object->note_private = GETPOST('note_private', 'alpha'); - $object->note_public = GETPOST('note_public', 'alpha'); + $object->date = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + $object->km = price2num(GETPOST('km', 'alpha'), 'MU'); // Not 'int', it may be a formated amount + $object->type = GETPOST('type', 'alpha'); + $object->socid = (int) GETPOST('socid', 'int'); + $object->fk_user = (int) GETPOST('fk_user', 'int'); + $object->note_private = GETPOST('note_private', 'alpha'); + $object->note_public = GETPOST('note_public', 'alpha'); - $result = $object->update($user); + $result = $object->update($user); - if ($result > 0) - { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } else { - header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); - exit; - } + if ($result > 0) + { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } else { + header("Location: ".$_SERVER["PHP_SELF"]."?id=".$id); + exit; + } } // Set into a project elseif ($action == 'classin' && $user->rights->deplacement->creer) { - $object->fetch($id); - $result = $object->setProject(GETPOST('projectid', 'int')); - if ($result < 0) dol_print_error($db, $object->error); + $object->fetch($id); + $result = $object->setProject(GETPOST('projectid', 'int')); + if ($result < 0) dol_print_error($db, $object->error); } // Set fields elseif ($action == 'setdated' && $user->rights->deplacement->creer) { - $dated = dol_mktime(GETPOST('datedhour', 'int'), GETPOST('datedmin', 'int'), GETPOST('datedsec', 'int'), GETPOST('datedmonth', 'int'), GETPOST('datedday', 'int'), GETPOST('datedyear', 'int')); - $object->fetch($id); - $result = $object->setValueFrom('dated', $dated, '', '', 'date', '', $user, 'DEPLACEMENT_MODIFY'); - if ($result < 0) dol_print_error($db, $object->error); + $dated = dol_mktime(GETPOST('datedhour', 'int'), GETPOST('datedmin', 'int'), GETPOST('datedsec', 'int'), GETPOST('datedmonth', 'int'), GETPOST('datedday', 'int'), GETPOST('datedyear', 'int')); + $object->fetch($id); + $result = $object->setValueFrom('dated', $dated, '', '', 'date', '', $user, 'DEPLACEMENT_MODIFY'); + if ($result < 0) dol_print_error($db, $object->error); } elseif ($action == 'setkm' && $user->rights->deplacement->creer) { - $object->fetch($id); - $result = $object->setValueFrom('km', GETPOST('km', 'int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY'); - if ($result < 0) dol_print_error($db, $object->error); + $object->fetch($id); + $result = $object->setValueFrom('km', GETPOST('km', 'int'), '', null, 'text', '', $user, 'DEPLACEMENT_MODIFY'); + if ($result < 0) dol_print_error($db, $object->error); } @@ -210,327 +210,327 @@ $form = new Form($db); */ if ($action == 'create') { - //WYSIWYG Editor - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + //WYSIWYG Editor + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - print load_fiche_titre($langs->trans("NewTrip")); + print load_fiche_titre($langs->trans("NewTrip")); - $datec = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + $datec = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - print '
'."\n"; - print ''; - print ''; + print ''."\n"; + print ''; + print ''; - print ''; + print '
'; - print ""; - print ''; + print ""; + print ''; - print ""; - print ''; + print ""; + print ''; - print ""; - print ''; + print ""; + print ''; - // Km - print ''; + // Km + print ''; - // Company - print ""; - print ''; + // Company + print ""; + print ''; - // Public note - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - // Private note - if (empty($user->socid)) - { - print ''; - print ''; - print ''; + print ''; + print ''; - } + print ''; + } - // Other attributes - $parameters = array(); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + // Other attributes + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; - print '
'.$langs->trans("Type").''; - $form->select_type_fees(GETPOST('type', 'int'), 'type', 1); - print '
'.$langs->trans("Type").''; + $form->select_type_fees(GETPOST('type', 'int'), 'type', 1); + print '
'.$langs->trans("Person").''; - print $form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); - print '
'.$langs->trans("Person").''; + print $form->select_dolusers(GETPOST('fk_user', 'int'), 'fk_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + print '
'.$langs->trans("Date").''; - print $form->selectDate($datec ? $datec : -1, '', '', '', '', 'add', 1, 1); - print '
'.$langs->trans("Date").''; + print $form->selectDate($datec ? $datec : -1, '', '', '', '', 'add', 1, 1); + print '
'.$langs->trans("FeesKilometersOrAmout").'
'.$langs->trans("FeesKilometersOrAmout").'
'.$langs->trans("CompanyVisited").''; - print $form->select_company(GETPOST('socid', 'int'), 'socid', '', 1); - print '
'.$langs->trans("CompanyVisited").''; + print $form->select_company(GETPOST('socid', 'int'), 'socid', '', 1); + print '
'.$langs->trans('NotePublic').''; + // Public note + print '
'.$langs->trans('NotePublic').''; - $doleditor = new DolEditor('note_public', GETPOST('note_public', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('note_public', GETPOST('note_public', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + print $doleditor->Create(1); - print '
'.$langs->trans('NotePrivate').''; + // Private note + if (empty($user->socid)) + { + print '
'.$langs->trans('NotePrivate').''; - $doleditor = new DolEditor('note_private', GETPOST('note_private', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('note_private', GETPOST('note_private', 'restricthtml'), '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + print $doleditor->Create(1); - print '
'; + print '
'; - print '
'; + print '
'; print ''; print '     '; - print ''; + print ''; print '
'; - print ''; + print ''; } elseif ($id) { - $result = $object->fetch($id); - if ($result > 0) - { - $head = trip_prepare_head($object); + $result = $object->fetch($id); + if ($result > 0) + { + $head = trip_prepare_head($object); - dol_fiche_head($head, 'card', $langs->trans("TripCard"), 0, 'trip'); + dol_fiche_head($head, 'card', $langs->trans("TripCard"), 0, 'trip'); - if ($action == 'edit' && $user->rights->deplacement->creer) - { - //WYSIWYG Editor - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + if ($action == 'edit' && $user->rights->deplacement->creer) + { + //WYSIWYG Editor + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $soc = new Societe($db); - if ($object->socid) - { - $soc->fetch($object->socid); - } + $soc = new Societe($db); + if ($object->socid) + { + $soc->fetch($object->socid); + } - print '
'."\n"; - print ''; - print ''; - print ''; + print ''."\n"; + print ''; + print ''; + print ''; - print ''; + print '
'; - // Ref - print ""; - print ''; + // Ref + print ""; + print ''; - // Type - print ""; - print ''; + // Type + print ""; + print ''; - // Who - print ""; - print ''; + // Who + print ""; + print ''; - // Date - print ''; + // Date + print ''; - // Km - print ''; + // Km + print ''; - // Where - print ""; - print ''; + // Where + print ""; + print ''; - // Public note - print ''; - print ''; + print '"; + print ""; - // Private note - if (empty($user->socid)) - { - print ''; - print ''; + print '"; - } + print ""; + } - // Other attributes - $parameters = array(); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + // Other attributes + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; - print '
'.$langs->trans("Ref").''; - print $object->ref; - print '
'.$langs->trans("Ref").''; + print $object->ref; + print '
'.$langs->trans("Type").''; - $form->select_type_fees(GETPOST('type', 'int') ?GETPOST('type', 'int') : $object->type, 'type', 0); - print '
'.$langs->trans("Type").''; + $form->select_type_fees(GETPOST('type', 'int') ?GETPOST('type', 'int') : $object->type, 'type', 0); + print '
'.$langs->trans("Person").''; - print $form->select_dolusers(GETPOST('fk_user', 'int') ?GETPOST('fk_user', 'int') : $object->fk_user, 'fk_user', 0, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); - print '
'.$langs->trans("Person").''; + print $form->select_dolusers(GETPOST('fk_user', 'int') ?GETPOST('fk_user', 'int') : $object->fk_user, 'fk_user', 0, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300'); + print '
'.$langs->trans("Date").''; - print $form->selectDate($object->date, '', 0, 0, 0, 'update', 1, 0); - print '
'.$langs->trans("Date").''; + print $form->selectDate($object->date, '', 0, 0, 0, 'update', 1, 0); + print '
'.$langs->trans("FeesKilometersOrAmout").''; - print ''; - print '
'.$langs->trans("FeesKilometersOrAmout").''; + print ''; + print '
'.$langs->trans("CompanyVisited").''; - print $form->select_company($soc->id, 'socid', '', 1); - print '
'.$langs->trans("CompanyVisited").''; + print $form->select_company($soc->id, 'socid', '', 1); + print '
'.$langs->trans("NotePublic").''; + // Public note + print '
'.$langs->trans("NotePublic").''; - $doleditor = new DolEditor('note_public', $object->note_public, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('note_public', $object->note_public, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + print $doleditor->Create(1); - print "
'.$langs->trans("NotePrivate").''; + // Private note + if (empty($user->socid)) + { + print '
'.$langs->trans("NotePrivate").''; - $doleditor = new DolEditor('note_private', $object->note_private, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('note_private', $object->note_private, '', 200, 'dolibarr_notes', 'In', false, true, true, ROWS_8, '90%'); + print $doleditor->Create(1); - print "
'; + print ''; - print '
'; + print '
'; print ''; print '     '; - print ''; - print '
'; + print ''; + print '
'; - print '
'; + print ''; - print '
'; - } else { - /* + print '
'; + } else { + /* * Confirm delete trip */ - if ($action == 'delete') - { - print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteTrip"), $langs->trans("ConfirmDeleteTrip"), "confirm_delete"); - } + if ($action == 'delete') + { + print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id, $langs->trans("DeleteTrip"), $langs->trans("ConfirmDeleteTrip"), "confirm_delete"); + } - $soc = new Societe($db); - if ($object->socid) $soc->fetch($object->socid); + $soc = new Societe($db); + if ($object->socid) $soc->fetch($object->socid); - print ''; + print '
'; - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - // Ref - print ''; + // Ref + print ''; - $form->load_cache_types_fees(); + $form->load_cache_types_fees(); - // Type - print ''; + // Type + print ''; - // Who - print ''; + // Who + print ''; - // Date - print ''; + // Date + print ''; - // Km/Price - print '"; + // Km/Price + print '"; - // Where - print ''; - print ''; + // Where + print ''; + print ''; - // Project - if (!empty($conf->projet->enabled)) - { - $langs->load('projects'); - print ''; - print ''; + print ''; - print ''; - } + print '
'.$langs->trans("Ref").''; - print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', ''); - print '
'.$langs->trans("Ref").''; + print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref', ''); + print '
'; - print $form->editfieldkey("Type", 'type', $langs->trans($object->type), $object, $user->rights->deplacement->creer, 'select:types_fees'); - print ''; - print $form->editfieldval("Type", 'type', $form->cache_types_fees[$object->type], $object, $user->rights->deplacement->creer, 'select:types_fees'); - print '
'; + print $form->editfieldkey("Type", 'type', $langs->trans($object->type), $object, $user->rights->deplacement->creer, 'select:types_fees'); + print ''; + print $form->editfieldval("Type", 'type', $form->cache_types_fees[$object->type], $object, $user->rights->deplacement->creer, 'select:types_fees'); + print '
'.$langs->trans("Person").''; - $userfee = new User($db); - $userfee->fetch($object->fk_user); - print $userfee->getNomUrl(1); - print '
'.$langs->trans("Person").''; + $userfee = new User($db); + $userfee->fetch($object->fk_user); + print $userfee->getNomUrl(1); + print '
'; - print $form->editfieldkey("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker'); - print ''; - print $form->editfieldval("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker'); - print '
'; + print $form->editfieldkey("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker'); + print ''; + print $form->editfieldval("Date", 'dated', $object->date, $object, $user->rights->deplacement->creer, 'datepicker'); + print '
'; - print $form->editfieldkey("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6'); - print ''; - print $form->editfieldval("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6'); - print "
'; + print $form->editfieldkey("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6'); + print ''; + print $form->editfieldval("FeesKilometersOrAmout", 'km', $object->km, $object, $user->rights->deplacement->creer, 'numeric:6'); + print "
'.$langs->trans("CompanyVisited").''; - if ($soc->id) print $soc->getNomUrl(1); - print '
'.$langs->trans("CompanyVisited").''; + if ($soc->id) print $soc->getNomUrl(1); + print '
'; + // Project + if (!empty($conf->projet->enabled)) + { + $langs->load('projects'); + print '
'; - print ''; - if ($action != 'classify' && $user->rights->deplacement->creer) - { - print ''; - } - print '
'; - print $langs->trans('Project'); - print 'id.'">'; - print img_edit($langs->trans('SetProject'), 1); - print '
'; - print '
'; - if ($action == 'classify') - { - $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1); - } else { - $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0); - } - print '
'; + if ($action != 'classify' && $user->rights->deplacement->creer) + { + print ''; + } + print '
'; + print $langs->trans('Project'); + print 'id.'">'; + print img_edit($langs->trans('SetProject'), 1); + print '
'; + print ''; + if ($action == 'classify') + { + $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1); + } else { + $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0); + } + print ''; + print ''; + } - // Statut - print ''.$langs->trans("Status").''.$object->getLibStatut(4).''; + // Statut + print ''.$langs->trans("Status").''.$object->getLibStatut(4).''; - // Other attributes - $parameters = array('socid'=>$object->id); - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $parameters = array('socid'=>$object->id); + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - print "
"; + print "
"; - // Notes - $blocname = 'notes'; - $title = $langs->trans('Notes'); - include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; + // Notes + $blocname = 'notes'; + $title = $langs->trans('Notes'); + include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; - print '
'; + print ''; - /* + /* * Barre d'actions */ - print '
'; + print '
'; - if ($object->statut < Deplacement::STATUS_REFUNDED) // if not refunded - { - if ($user->rights->deplacement->creer) - { - print ''.$langs->trans('Modify').''; - } else { - print ''.$langs->trans('Modify').''; - } - } + if ($object->statut < Deplacement::STATUS_REFUNDED) // if not refunded + { + if ($user->rights->deplacement->creer) + { + print ''.$langs->trans('Modify').''; + } else { + print ''.$langs->trans('Modify').''; + } + } - if ($object->statut == Deplacement::STATUS_DRAFT) // if draft - { - if ($user->rights->deplacement->creer) - { - print ''.$langs->trans('Validate').''; - } else { - print ''.$langs->trans('Validate').''; - } - } + if ($object->statut == Deplacement::STATUS_DRAFT) // if draft + { + if ($user->rights->deplacement->creer) + { + print ''.$langs->trans('Validate').''; + } else { + print ''.$langs->trans('Validate').''; + } + } - if ($object->statut == Deplacement::STATUS_VALIDATED) // if validated - { - if ($user->rights->deplacement->creer) - { - print ''.$langs->trans('ClassifyRefunded').''; - } else { - print ''.$langs->trans('ClassifyRefunded').''; - } - } + if ($object->statut == Deplacement::STATUS_VALIDATED) // if validated + { + if ($user->rights->deplacement->creer) + { + print ''.$langs->trans('ClassifyRefunded').''; + } else { + print ''.$langs->trans('ClassifyRefunded').''; + } + } - if ($user->rights->deplacement->supprimer) - { - print ''.$langs->trans('Delete').''; - } else { - print ''.$langs->trans('Delete').''; - } + if ($user->rights->deplacement->supprimer) + { + print ''.$langs->trans('Delete').''; + } else { + print ''.$langs->trans('Delete').''; + } - print '
'; - } - } else { - dol_print_error($db); - } + print '
'; + } + } else { + dol_print_error($db); + } } // End of page diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 8199a62201b..4d30977bf6a 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -165,7 +165,7 @@ foreach ($object->fields as $key => $val) } // Add none object fields for "search in all" -if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { +if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $fieldstosearchall['s.nom'] = "ThirdParty"; } @@ -186,7 +186,7 @@ foreach ($object->fields as $key => $val) { // Add none object fields to fields for list $arrayfields['country.code_iso'] = array('label'=>"Country", 'position'=>22, 'checked'=>0); -if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { +if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $arrayfields['s.nom'] = array('label'=>"ThirdParty", 'position'=>25, 'checked'=>1); } diff --git a/htdocs/core/boxes/box_activity.php b/htdocs/core/boxes/box_activity.php index 0546f907b64..1585241b843 100644 --- a/htdocs/core/boxes/box_activity.php +++ b/htdocs/core/boxes/box_activity.php @@ -30,413 +30,413 @@ include_once DOL_DOCUMENT_ROOT.'/core/boxes/modules_boxes.php'; */ class box_activity extends ModeleBoxes { - public $boxcode = "activity"; - public $boximg = "object_bill"; - public $boxlabel = 'BoxGlobalActivity'; - public $depends = array("facture"); + public $boxcode = "activity"; + public $boximg = "object_bill"; + public $boxlabel = 'BoxGlobalActivity'; + public $depends = array("facture"); - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - public $param; - public $enabled = 1; + public $param; + public $enabled = 1; - public $info_box_head = array(); - public $info_box_contents = array(); + public $info_box_head = array(); + public $info_box_contents = array(); - /** - * Constructor - * - * @param DoliDB $db Database handler - * @param string $param More parameters - */ - public function __construct($db, $param) - { - global $conf, $user; + /** + * Constructor + * + * @param DoliDB $db Database handler + * @param string $param More parameters + */ + public function __construct($db, $param) + { + global $conf, $user; - $this->db = $db; + $this->db = $db; - // FIXME: Pb into some status - $this->enabled = ($conf->global->MAIN_FEATURES_LEVEL); // Not enabled by default due to bugs (see previous comments) + // FIXME: Pb into some status + $this->enabled = ($conf->global->MAIN_FEATURES_LEVEL); // Not enabled by default due to bugs (see previous comments) - $this->hidden = !((!empty($conf->facture->enabled) && $user->rights->facture->lire) - || (!empty($conf->commande->enabled) && $user->rights->commande->lire) - || (!empty($conf->propal->enabled) && $user->rights->propale->lire) - ); - } + $this->hidden = !((!empty($conf->facture->enabled) && $user->rights->facture->lire) + || (!empty($conf->commande->enabled) && $user->rights->commande->lire) + || (!empty($conf->propal->enabled) && $user->rights->propale->lire) + ); + } - /** - * Charge les donnees en memoire pour affichage ulterieur - * - * @param int $max Maximum number of records to load - * @return void - */ - public function loadBox($max = 5) - { - global $conf, $user, $langs; + /** + * Charge les donnees en memoire pour affichage ulterieur + * + * @param int $max Maximum number of records to load + * @return void + */ + public function loadBox($max = 5) + { + global $conf, $user, $langs; - include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - $totalnb = 0; - $line = 0; - $cachetime = 3600; - $fileid = '-e'.$conf->entity.'-u'.$user->id.'-s'.$user->socid.'-r'.($user->rights->societe->client->voir ? '1' : '0').'.cache'; - $now = dol_now(); - $nbofperiod = 3; + $totalnb = 0; + $line = 0; + $cachetime = 3600; + $fileid = '-e'.$conf->entity.'-u'.$user->id.'-s'.$user->socid.'-r'.($user->rights->societe->client->voir ? '1' : '0').'.cache'; + $now = dol_now(); + $nbofperiod = 3; - if (!empty($conf->global->MAIN_BOX_ACTIVITY_DURATION)) $nbofperiod = $conf->global->MAIN_BOX_ACTIVITY_DURATION; - $textHead = $langs->trans("Activity").' - '.$langs->trans("LastXMonthRolling", $nbofperiod); - $this->info_box_head = array( - 'text' => $textHead, - 'limit'=> dol_strlen($textHead), - ); + if (!empty($conf->global->MAIN_BOX_ACTIVITY_DURATION)) $nbofperiod = $conf->global->MAIN_BOX_ACTIVITY_DURATION; + $textHead = $langs->trans("Activity").' - '.$langs->trans("LastXMonthRolling", $nbofperiod); + $this->info_box_head = array( + 'text' => $textHead, + 'limit'=> dol_strlen($textHead), + ); - // compute the year limit to show - $tmpdate = dol_time_plus_duree(dol_now(), -1 * $nbofperiod, "m"); + // compute the year limit to show + $tmpdate = dol_time_plus_duree(dol_now(), -1 * $nbofperiod, "m"); - // list the summary of the propals - if (!empty($conf->propal->enabled) && $user->rights->propale->lire) - { - include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; - $propalstatic = new Propal($this->db); + // list the summary of the propals + if (!empty($conf->propal->enabled) && $user->rights->propale->lire) + { + include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; + $propalstatic = new Propal($this->db); - $cachedir = DOL_DATA_ROOT.'/propale/temp'; - $filename = '/boxactivity-propal'.$fileid; - $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); - $data = array(); - if ($refresh) - { - $sql = "SELECT p.fk_statut, SUM(p.total) as Mnttot, COUNT(*) as nb"; - $sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= ")"; - $sql .= " WHERE p.entity IN (".getEntity('propal').")"; - $sql .= " AND p.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - $sql .= " AND p.datep >= '".$this->db->idate($tmpdate)."'"; - $sql .= " AND p.date_cloture IS NULL"; // just unclosed - $sql .= " GROUP BY p.fk_statut"; - $sql .= " ORDER BY p.fk_statut DESC"; + $cachedir = DOL_DATA_ROOT.'/propale/temp'; + $filename = '/boxactivity-propal'.$fileid; + $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); + $data = array(); + if ($refresh) + { + $sql = "SELECT p.fk_statut, SUM(p.total) as Mnttot, COUNT(*) as nb"; + $sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."propal as p"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ")"; + $sql .= " WHERE p.entity IN (".getEntity('propal').")"; + $sql .= " AND p.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; + $sql .= " AND p.datep >= '".$this->db->idate($tmpdate)."'"; + $sql .= " AND p.date_cloture IS NULL"; // just unclosed + $sql .= " GROUP BY p.fk_statut"; + $sql .= " ORDER BY p.fk_statut DESC"; - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); + $result = $this->db->query($sql); + if ($result) + { + $num = $this->db->num_rows($result); - $j = 0; - while ($j < $num) { - $data[$j] = $this->db->fetch_object($result); - $j++; - } - if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { - dol_filecache($cachedir, $filename, $data); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } else { - $data = dol_readcachefile($cachedir, $filename); - } + $j = 0; + while ($j < $num) { + $data[$j] = $this->db->fetch_object($result); + $j++; + } + if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { + dol_filecache($cachedir, $filename, $data); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } else { + $data = dol_readcachefile($cachedir, $filename); + } - if (!empty($data)) - { - $j = 0; - while ($j < count($data)) - { - $this->info_box_contents[$line][0] = array( - 'td' => 'class="left" width="16"', - 'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&leftmenu=propals&search_status=".$data[$j]->fk_statut, - 'tooltip' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), - 'logo' => 'object_propal' - ); + if (!empty($data)) + { + $j = 0; + while ($j < count($data)) + { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="left" width="16"', + 'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&leftmenu=propals&search_status=".$data[$j]->fk_statut, + 'tooltip' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), + 'logo' => 'object_propal' + ); - $this->info_box_contents[$line][1] = array( - 'td' => '', - 'text' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), - ); + $this->info_box_contents[$line][1] = array( + 'td' => '', + 'text' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), + ); - $this->info_box_contents[$line][2] = array( - 'td' => 'class="right"', - 'text' => $data[$j]->nb, - 'tooltip' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), - 'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&leftmenu=propals&search_status=".$data[$j]->fk_statut, - ); - $totalnb += $data[$j]->nb; + $this->info_box_contents[$line][2] = array( + 'td' => 'class="right"', + 'text' => $data[$j]->nb, + 'tooltip' => $langs->trans("Proposals")." ".$propalstatic->LibStatut($data[$j]->fk_statut, 0), + 'url' => DOL_URL_ROOT."/comm/propal/list.php?mainmenu=commercial&leftmenu=propals&search_status=".$data[$j]->fk_statut, + ); + $totalnb += $data[$j]->nb; - $this->info_box_contents[$line][3] = array( - 'td' => 'class="nowraponall right"', - 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), - ); - $this->info_box_contents[$line][4] = array( - 'td' => 'class="right" width="18"', - 'text' => $propalstatic->LibStatut($data[$j]->fk_statut, 3), - ); + $this->info_box_contents[$line][3] = array( + 'td' => 'class="nowraponall right"', + 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), + ); + $this->info_box_contents[$line][4] = array( + 'td' => 'class="right" width="18"', + 'text' => $propalstatic->LibStatut($data[$j]->fk_statut, 3), + ); - $line++; - $j++; - } - } - } + $line++; + $j++; + } + } + } - // list the summary of the orders - if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { - include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; - $commandestatic = new Commande($this->db); + // list the summary of the orders + if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { + include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; + $commandestatic = new Commande($this->db); - $langs->load("orders"); + $langs->load("orders"); - $cachedir = DOL_DATA_ROOT.'/commande/temp'; - $filename = '/boxactivity-order'.$fileid; - $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); - $data = array(); + $cachedir = DOL_DATA_ROOT.'/commande/temp'; + $filename = '/boxactivity-order'.$fileid; + $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); + $data = array(); - if ($refresh) { - $sql = "SELECT c.fk_statut, sum(c.total_ttc) as Mnttot, count(*) as nb"; - $sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= ")"; - $sql .= " WHERE c.entity IN (".getEntity('commande').")"; - $sql .= " AND c.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - $sql .= " AND c.date_commande >= '".$this->db->idate($tmpdate)."'"; - $sql .= " GROUP BY c.fk_statut"; - $sql .= " ORDER BY c.fk_statut DESC"; + if ($refresh) { + $sql = "SELECT c.fk_statut, sum(c.total_ttc) as Mnttot, count(*) as nb"; + $sql .= " FROM (".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."commande as c"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ")"; + $sql .= " WHERE c.entity IN (".getEntity('commande').")"; + $sql .= " AND c.fk_soc = s.rowid"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; + $sql .= " AND c.date_commande >= '".$this->db->idate($tmpdate)."'"; + $sql .= " GROUP BY c.fk_statut"; + $sql .= " ORDER BY c.fk_statut DESC"; - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $j = 0; - while ($j < $num) { - $data[$j] = $this->db->fetch_object($result); - $j++; - } - if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { - dol_filecache($cachedir, $filename, $data); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } else { - $data = dol_readcachefile($cachedir, $filename); - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $j = 0; + while ($j < $num) { + $data[$j] = $this->db->fetch_object($result); + $j++; + } + if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { + dol_filecache($cachedir, $filename, $data); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } else { + $data = dol_readcachefile($cachedir, $filename); + } - if (!empty($data)) { - $j = 0; - while ($j < count($data)) { - $this->info_box_contents[$line][0] = array( - 'td' => 'class="left" width="16"', - 'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&leftmenu=orders&search_status=".$data[$j]->fk_statut, - 'tooltip' => $langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), - 'logo' => 'object_order', - ); + if (!empty($data)) { + $j = 0; + while ($j < count($data)) { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="left" width="16"', + 'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&leftmenu=orders&search_status=".$data[$j]->fk_statut, + 'tooltip' => $langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), + 'logo' => 'object_order', + ); - $this->info_box_contents[$line][1] = array( - 'td' => '', - 'text' =>$langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), - ); + $this->info_box_contents[$line][1] = array( + 'td' => '', + 'text' =>$langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), + ); - $this->info_box_contents[$line][2] = array( - 'td' => 'class="right"', - 'text' => $data[$j]->nb, - 'tooltip' => $langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), - 'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&leftmenu=orders&search_status=".$data[$j]->fk_statut, - ); - $totalnb += $data[$j]->nb; + $this->info_box_contents[$line][2] = array( + 'td' => 'class="right"', + 'text' => $data[$j]->nb, + 'tooltip' => $langs->trans("Orders")." ".$commandestatic->LibStatut($data[$j]->fk_statut, 0, 0), + 'url' => DOL_URL_ROOT."/commande/list.php?mainmenu=commercial&leftmenu=orders&search_status=".$data[$j]->fk_statut, + ); + $totalnb += $data[$j]->nb; - $this->info_box_contents[$line][3] = array( - 'td' => 'class="nowraponall right"', - 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), - ); - $this->info_box_contents[$line][4] = array( - 'td' => 'class="right" width="18"', - 'text' => $commandestatic->LibStatut($data[$j]->fk_statut, 0, 3), - ); + $this->info_box_contents[$line][3] = array( + 'td' => 'class="nowraponall right"', + 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), + ); + $this->info_box_contents[$line][4] = array( + 'td' => 'class="right" width="18"', + 'text' => $commandestatic->LibStatut($data[$j]->fk_statut, 0, 3), + ); - $line++; - $j++; - } - } - } + $line++; + $j++; + } + } + } - // list the summary of the bills - if (!empty($conf->facture->enabled) && $user->rights->facture->lire) - { - include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; - $facturestatic = new Facture($this->db); + // list the summary of the bills + if (!empty($conf->facture->enabled) && $user->rights->facture->lire) + { + include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; + $facturestatic = new Facture($this->db); - // part 1 - $cachedir = DOL_DATA_ROOT.'/facture/temp'; - $filename = '/boxactivity-invoice'.$fileid; + // part 1 + $cachedir = DOL_DATA_ROOT.'/facture/temp'; + $filename = '/boxactivity-invoice'.$fileid; - $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); - $data = array(); - if ($refresh) - { - $sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb"; - $sql .= " FROM (".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - $sql .= ")"; - $sql .= " WHERE f.entity IN (".getEntity('invoice').')'; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; - $sql .= " AND f.fk_soc = s.rowid"; - $sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=1"; - $sql .= " GROUP BY f.fk_statut"; - $sql .= " ORDER BY f.fk_statut DESC"; + $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); + $data = array(); + if ($refresh) + { + $sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb"; + $sql .= " FROM (".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + $sql .= ")"; + $sql .= " WHERE f.entity IN (".getEntity('invoice').')'; + if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) $sql .= " AND s.rowid = ".$user->socid; + $sql .= " AND f.fk_soc = s.rowid"; + $sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=1"; + $sql .= " GROUP BY f.fk_statut"; + $sql .= " ORDER BY f.fk_statut DESC"; - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $j = 0; - while ($j < $num) { - $data[$j] = $this->db->fetch_object($result); - $j++; - } - if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { - dol_filecache($cachedir, $filename, $data); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } else { - $data = dol_readcachefile($cachedir, $filename); - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $j = 0; + while ($j < $num) { + $data[$j] = $this->db->fetch_object($result); + $j++; + } + if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { + dol_filecache($cachedir, $filename, $data); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } else { + $data = dol_readcachefile($cachedir, $filename); + } - if (!empty($data)) { - $j = 0; - while ($j < count($data)) { - $billurl = "search_status=2&paye=1&year=".$data[$j]->annee; - $this->info_box_contents[$line][0] = array( - 'td' => 'class="left" width="16"', - 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0), - 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", - 'logo' => 'bill', - ); + if (!empty($data)) { + $j = 0; + while ($j < count($data)) { + $billurl = "search_status=2&paye=1&year=".$data[$j]->annee; + $this->info_box_contents[$line][0] = array( + 'td' => 'class="left" width="16"', + 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0), + 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", + 'logo' => 'bill', + ); - $this->info_box_contents[$line][1] = array( - 'td' => '', - 'text' => $langs->trans("Bills")." ".$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0)." ".$data[$j]->annee, - ); + $this->info_box_contents[$line][1] = array( + 'td' => '', + 'text' => $langs->trans("Bills")." ".$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0)." ".$data[$j]->annee, + ); - $this->info_box_contents[$line][2] = array( - 'td' => 'class="right"', - 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0), - 'text' => $data[$j]->nb, - 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", - ); + $this->info_box_contents[$line][2] = array( + 'td' => 'class="right"', + 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(1, $data[$j]->fk_statut, 0), + 'text' => $data[$j]->nb, + 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", + ); - $this->info_box_contents[$line][3] = array( - 'td' => 'class="nowraponall right"', - 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency) - ); + $this->info_box_contents[$line][3] = array( + 'td' => 'class="nowraponall right"', + 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency) + ); - // We add only for the current year - $totalnb += $data[$j]->nb; + // We add only for the current year + $totalnb += $data[$j]->nb; - $this->info_box_contents[$line][4] = array( - 'td' => 'class="right" width="18"', - 'text' => $facturestatic->LibStatut(1, $data[$j]->fk_statut, 3), - ); - $line++; - $j++; - } - if (count($data) == 0) - $this->info_box_contents[$line][0] = array( - 'td' => 'class="center"', - 'text'=>$langs->trans("NoRecordedInvoices"), - ); - } + $this->info_box_contents[$line][4] = array( + 'td' => 'class="right" width="18"', + 'text' => $facturestatic->LibStatut(1, $data[$j]->fk_statut, 3), + ); + $line++; + $j++; + } + if (count($data) == 0) + $this->info_box_contents[$line][0] = array( + 'td' => 'class="center"', + 'text'=>$langs->trans("NoRecordedInvoices"), + ); + } - // part 2 - $cachedir = DOL_DATA_ROOT.'/facture/temp'; - $filename = '/boxactivity-invoice2'.$fileid; + // part 2 + $cachedir = DOL_DATA_ROOT.'/facture/temp'; + $filename = '/boxactivity-invoice2'.$fileid; - $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); + $refresh = dol_cache_refresh($cachedir, $filename, $cachetime); - $data = array(); - if ($refresh) { - $sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb"; - $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; - $sql .= " WHERE f.entity IN (".getEntity('invoice').')'; - $sql .= " AND f.fk_soc = s.rowid"; - $sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=0"; - $sql .= " GROUP BY f.fk_statut"; - $sql .= " ORDER BY f.fk_statut DESC"; + $data = array(); + if ($refresh) { + $sql = "SELECT f.fk_statut, SUM(f.total_ttc) as Mnttot, COUNT(*) as nb"; + $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,".MAIN_DB_PREFIX."facture as f"; + $sql .= " WHERE f.entity IN (".getEntity('invoice').')'; + $sql .= " AND f.fk_soc = s.rowid"; + $sql .= " AND f.datef >= '".$this->db->idate($tmpdate)."' AND f.paye=0"; + $sql .= " GROUP BY f.fk_statut"; + $sql .= " ORDER BY f.fk_statut DESC"; - $result = $this->db->query($sql); - if ($result) { - $num = $this->db->num_rows($result); - $j = 0; - while ($j < $num) { - $data[$j] = $this->db->fetch_object($result); - $j++; - } - if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { - dol_filecache($cachedir, $filename, $data); - } - $this->db->free($result); - } else { - dol_print_error($this->db); - } - } else { - $data = dol_readcachefile($cachedir, $filename); - } + $result = $this->db->query($sql); + if ($result) { + $num = $this->db->num_rows($result); + $j = 0; + while ($j < $num) { + $data[$j] = $this->db->fetch_object($result); + $j++; + } + if (!empty($conf->global->MAIN_ACTIVATE_FILECACHE)) { + dol_filecache($cachedir, $filename, $data); + } + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } else { + $data = dol_readcachefile($cachedir, $filename); + } - if (!empty($data)) { - $alreadypaid = -1; + if (!empty($data)) { + $alreadypaid = -1; - $j = 0; - while ($j < count($data)) { - $billurl = "search_status=".$data[$j]->fk_statut."&paye=0"; - $this->info_box_contents[$line][0] = array( - 'td' => 'class="left" width="16"', - 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), - 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", - 'logo' => 'bill', - ); + $j = 0; + while ($j < count($data)) { + $billurl = "search_status=".$data[$j]->fk_statut."&paye=0"; + $this->info_box_contents[$line][0] = array( + 'td' => 'class="left" width="16"', + 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), + 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", + 'logo' => 'bill', + ); - $this->info_box_contents[$line][1] = array( - 'td' => '', - 'text' => $langs->trans("Bills")." ".$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), - ); + $this->info_box_contents[$line][1] = array( + 'td' => '', + 'text' => $langs->trans("Bills")." ".$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), + ); - $this->info_box_contents[$line][2] = array( - 'td' => 'class="right"', - 'text' => $data[$j]->nb, - 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), - 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", - ); - $totalnb += $data[$j]->nb; - $this->info_box_contents[$line][3] = array( - 'td' => 'class="nowraponall right"', - 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), - ); - $this->info_box_contents[$line][4] = array( - 'td' => 'class="right" width="18"', - 'text' => $facturestatic->LibStatut(0, $data[$j]->fk_statut, 3, $alreadypaid), - ); - $line++; - $j++; - } - if (count($data) == 0) { - $this->info_box_contents[$line][0] = array( - 'td' => 'class="center"', - 'text'=>$langs->trans("NoRecordedInvoices"), - ); - } - } - } + $this->info_box_contents[$line][2] = array( + 'td' => 'class="right"', + 'text' => $data[$j]->nb, + 'tooltip' => $langs->trans('Bills').' '.$facturestatic->LibStatut(0, $data[$j]->fk_statut, 0), + 'url' => DOL_URL_ROOT."/compta/facture/list.php?".$billurl."&mainmenu=accountancy&leftmenu=customers_bills", + ); + $totalnb += $data[$j]->nb; + $this->info_box_contents[$line][3] = array( + 'td' => 'class="nowraponall right"', + 'text' => price($data[$j]->Mnttot, 1, $langs, 0, 0, -1, $conf->currency), + ); + $this->info_box_contents[$line][4] = array( + 'td' => 'class="right" width="18"', + 'text' => $facturestatic->LibStatut(0, $data[$j]->fk_statut, 3, $alreadypaid), + ); + $line++; + $j++; + } + if (count($data) == 0) { + $this->info_box_contents[$line][0] = array( + 'td' => 'class="center"', + 'text'=>$langs->trans("NoRecordedInvoices"), + ); + } + } + } // Add the sum in the bottom of the boxes $this->info_box_contents[$line][0] = array('tr' => 'class="liste_total_wrap"'); @@ -444,19 +444,19 @@ class box_activity extends ModeleBoxes $this->info_box_contents[$line][2] = array('td' => 'class="liste_total right" ', 'text' => $totalnb); $this->info_box_contents[$line][3] = array('td' => 'class="liste_total right" ', 'text' => ''); $this->info_box_contents[$line][4] = array('td' => 'class="liste_total right" ', 'text' => ""); - } + } - /** - * Method to show box - * - * @param array $head Array with properties of box title - * @param array $contents Array with properties of box lines - * @param int $nooutput No print, only return string - * @return string - */ - public function showBox($head = null, $contents = null, $nooutput = 0) - { - return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); - } + /** + * Method to show box + * + * @param array $head Array with properties of box title + * @param array $contents Array with properties of box lines + * @param int $nooutput No print, only return string + * @return string + */ + public function showBox($head = null, $contents = null, $nooutput = 0) + { + return parent::showBox($this->info_box_head, $this->info_box_contents, $nooutput); + } } diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index f25a0694f7d..6015bbceece 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -40,199 +40,199 @@ abstract class CommonDocGenerator */ public $error = ''; - /** - * @var string[] Array of error strings - */ - public $errors = array(); + /** + * @var string[] Array of error strings + */ + public $errors = array(); /** - * @var DoliDB Database handler. - */ + * @var DoliDB Database handler. + */ protected $db; - /** - * @var Extrafields object - */ + /** + * @var Extrafields object + */ public $extrafieldsCache; /** * Constructor * * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + */ + public function __construct($db) + { + $this->db = $db; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param User $user User - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function get_substitutionarray_user($user, $outputlangs) - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param User $user User + * @param Translate $outputlangs Language object for output + * @return array Array of substitution key->code + */ + public function get_substitutionarray_user($user, $outputlangs) + { + // phpcs:enable + global $conf; - $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo; + $logotouse = $conf->user->dir_output.'/'.get_exdir($user->id, 2, 0, 1, $user, 'user').'/'.$user->photo; - return array( - 'myuser_lastname'=>$user->lastname, - 'myuser_firstname'=>$user->firstname, - 'myuser_fullname'=>$user->getFullName($outputlangs, 1), - 'myuser_login'=>$user->login, - 'myuser_phone'=>$user->office_phone, - 'myuser_address'=>$user->address, - 'myuser_zip'=>$user->zip, - 'myuser_town'=>$user->town, - 'myuser_country'=>$user->country, - 'myuser_country_code'=>$user->country_code, - 'myuser_state'=>$user->state, - 'myuser_state_code'=>$user->state_code, - 'myuser_fax'=>$user->office_fax, - 'myuser_mobile'=>$user->user_mobile, - 'myuser_email'=>$user->email, - 'myuser_logo'=>$logotouse, - 'myuser_job'=>$user->job, - 'myuser_web'=>'' // url not exist in $user object - ); - } + return array( + 'myuser_lastname'=>$user->lastname, + 'myuser_firstname'=>$user->firstname, + 'myuser_fullname'=>$user->getFullName($outputlangs, 1), + 'myuser_login'=>$user->login, + 'myuser_phone'=>$user->office_phone, + 'myuser_address'=>$user->address, + 'myuser_zip'=>$user->zip, + 'myuser_town'=>$user->town, + 'myuser_country'=>$user->country, + 'myuser_country_code'=>$user->country_code, + 'myuser_state'=>$user->state, + 'myuser_state_code'=>$user->state_code, + 'myuser_fax'=>$user->office_fax, + 'myuser_mobile'=>$user->user_mobile, + 'myuser_email'=>$user->email, + 'myuser_logo'=>$logotouse, + 'myuser_job'=>$user->job, + 'myuser_web'=>'' // url not exist in $user object + ); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Societe $mysoc Object thirdparty - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function get_substitutionarray_mysoc($mysoc, $outputlangs) - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Societe $mysoc Object thirdparty + * @param Translate $outputlangs Language object for output + * @return array Array of substitution key->code + */ + public function get_substitutionarray_mysoc($mysoc, $outputlangs) + { + // phpcs:enable + global $conf; - if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code)) - { - $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code); - } - if (empty($mysoc->country) && !empty($mysoc->country_code)) - { - $mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code); - } - if (empty($mysoc->state) && !empty($mysoc->state_code)) - { - $mysoc->state = getState($mysoc->state_code, 0); - } + if (empty($mysoc->forme_juridique) && !empty($mysoc->forme_juridique_code)) + { + $mysoc->forme_juridique = getFormeJuridiqueLabel($mysoc->forme_juridique_code); + } + if (empty($mysoc->country) && !empty($mysoc->country_code)) + { + $mysoc->country = $outputlangs->transnoentitiesnoconv("Country".$mysoc->country_code); + } + if (empty($mysoc->state) && !empty($mysoc->state_code)) + { + $mysoc->state = getState($mysoc->state_code, 0); + } - $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; + $logotouse = $conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small; - return array( - 'mycompany_logo'=>$logotouse, - 'mycompany_name'=>$mysoc->name, - 'mycompany_email'=>$mysoc->email, - 'mycompany_phone'=>$mysoc->phone, - 'mycompany_fax'=>$mysoc->fax, - 'mycompany_address'=>$mysoc->address, - 'mycompany_zip'=>$mysoc->zip, - 'mycompany_town'=>$mysoc->town, - 'mycompany_country'=>$mysoc->country, - 'mycompany_country_code'=>$mysoc->country_code, - 'mycompany_state'=>$mysoc->state, - 'mycompany_state_code'=>$mysoc->state_code, - 'mycompany_web'=>$mysoc->url, - 'mycompany_juridicalstatus'=>$mysoc->forme_juridique, - 'mycompany_managers'=>$mysoc->managers, - 'mycompany_capital'=>$mysoc->capital, - 'mycompany_barcode'=>$mysoc->barcode, - 'mycompany_idprof1'=>$mysoc->idprof1, - 'mycompany_idprof2'=>$mysoc->idprof2, - 'mycompany_idprof3'=>$mysoc->idprof3, - 'mycompany_idprof4'=>$mysoc->idprof4, - 'mycompany_idprof5'=>$mysoc->idprof5, - 'mycompany_idprof6'=>$mysoc->idprof6, - 'mycompany_vatnumber'=>$mysoc->tva_intra, + return array( + 'mycompany_logo'=>$logotouse, + 'mycompany_name'=>$mysoc->name, + 'mycompany_email'=>$mysoc->email, + 'mycompany_phone'=>$mysoc->phone, + 'mycompany_fax'=>$mysoc->fax, + 'mycompany_address'=>$mysoc->address, + 'mycompany_zip'=>$mysoc->zip, + 'mycompany_town'=>$mysoc->town, + 'mycompany_country'=>$mysoc->country, + 'mycompany_country_code'=>$mysoc->country_code, + 'mycompany_state'=>$mysoc->state, + 'mycompany_state_code'=>$mysoc->state_code, + 'mycompany_web'=>$mysoc->url, + 'mycompany_juridicalstatus'=>$mysoc->forme_juridique, + 'mycompany_managers'=>$mysoc->managers, + 'mycompany_capital'=>$mysoc->capital, + 'mycompany_barcode'=>$mysoc->barcode, + 'mycompany_idprof1'=>$mysoc->idprof1, + 'mycompany_idprof2'=>$mysoc->idprof2, + 'mycompany_idprof3'=>$mysoc->idprof3, + 'mycompany_idprof4'=>$mysoc->idprof4, + 'mycompany_idprof5'=>$mysoc->idprof5, + 'mycompany_idprof6'=>$mysoc->idprof6, + 'mycompany_vatnumber'=>$mysoc->tva_intra, 'mycompany_object'=>$mysoc->object, - 'mycompany_note_private'=>$mysoc->note_private, - //'mycompany_note_public'=>$mysoc->note_public, // Only private not exists for "mysoc" but both for thirdparties - ); - } + 'mycompany_note_private'=>$mysoc->note_private, + //'mycompany_note_public'=>$mysoc->note_public, // Only private not exists for "mysoc" but both for thirdparties + ); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Societe $object Object - * @param Translate $outputlangs Language object for output - * @param string $array_key Name of the key for return array - * @return array Array of substitution key->code - */ - public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company') - { - // phpcs:enable - global $conf, $extrafields; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Societe $object Object + * @param Translate $outputlangs Language object for output + * @param string $array_key Name of the key for return array + * @return array Array of substitution key->code + */ + public function get_substitutionarray_thirdparty($object, $outputlangs, $array_key = 'company') + { + // phpcs:enable + global $conf, $extrafields; - if (empty($object->country) && !empty($object->country_code)) - { - $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code); - } - if (empty($object->state) && !empty($object->state_code)) - { - $object->state = getState($object->state_code, 0); - } + if (empty($object->country) && !empty($object->country_code)) + { + $object->country = $outputlangs->transnoentitiesnoconv("Country".$object->country_code); + } + if (empty($object->state) && !empty($object->state_code)) + { + $object->state = getState($object->state_code, 0); + } - $array_thirdparty = array( - 'company_name'=>$object->name, - 'company_name_alias' => $object->name_alias, - 'company_email'=>$object->email, - 'company_phone'=>$object->phone, - 'company_fax'=>$object->fax, - 'company_address'=>$object->address, - 'company_zip'=>$object->zip, - 'company_town'=>$object->town, - 'company_country'=>$object->country, - 'company_country_code'=>$object->country_code, - 'company_state'=>$object->state, - 'company_state_code'=>$object->state_code, - 'company_web'=>$object->url, - 'company_barcode'=>$object->barcode, - 'company_vatnumber'=>$object->tva_intra, - 'company_customercode'=>$object->code_client, - 'company_suppliercode'=>$object->code_fournisseur, - 'company_customeraccountancycode'=>$object->code_compta, - 'company_supplieraccountancycode'=>$object->code_compta_fournisseur, - 'company_juridicalstatus'=>$object->forme_juridique, - 'company_outstanding_limit'=>$object->outstanding_limit, - 'company_capital'=>$object->capital, - 'company_idprof1'=>$object->idprof1, - 'company_idprof2'=>$object->idprof2, - 'company_idprof3'=>$object->idprof3, - 'company_idprof4'=>$object->idprof4, - 'company_idprof5'=>$object->idprof5, - 'company_idprof6'=>$object->idprof6, - 'company_note_public'=>$object->note_public, - 'company_note_private'=>$object->note_private, - 'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''), - 'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '') - ); + $array_thirdparty = array( + 'company_name'=>$object->name, + 'company_name_alias' => $object->name_alias, + 'company_email'=>$object->email, + 'company_phone'=>$object->phone, + 'company_fax'=>$object->fax, + 'company_address'=>$object->address, + 'company_zip'=>$object->zip, + 'company_town'=>$object->town, + 'company_country'=>$object->country, + 'company_country_code'=>$object->country_code, + 'company_state'=>$object->state, + 'company_state_code'=>$object->state_code, + 'company_web'=>$object->url, + 'company_barcode'=>$object->barcode, + 'company_vatnumber'=>$object->tva_intra, + 'company_customercode'=>$object->code_client, + 'company_suppliercode'=>$object->code_fournisseur, + 'company_customeraccountancycode'=>$object->code_compta, + 'company_supplieraccountancycode'=>$object->code_compta_fournisseur, + 'company_juridicalstatus'=>$object->forme_juridique, + 'company_outstanding_limit'=>$object->outstanding_limit, + 'company_capital'=>$object->capital, + 'company_idprof1'=>$object->idprof1, + 'company_idprof2'=>$object->idprof2, + 'company_idprof3'=>$object->idprof3, + 'company_idprof4'=>$object->idprof4, + 'company_idprof5'=>$object->idprof5, + 'company_idprof6'=>$object->idprof6, + 'company_note_public'=>$object->note_public, + 'company_note_private'=>$object->note_private, + 'company_default_bank_iban'=>(is_object($object->bank_account) ? $object->bank_account->iban : ''), + 'company_default_bank_bic'=>(is_object($object->bank_account) ? $object->bank_account->bic : '') + ); - // Retrieve extrafields - if (is_array($object->array_options) && count($object->array_options)) - { - $object->fetch_optionals(); + // Retrieve extrafields + if (is_array($object->array_options) && count($object->array_options)) + { + $object->fetch_optionals(); - $array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs); - } + $array_thirdparty = $this->fill_substitutionarray_with_extrafields($object, $array_thirdparty, $extrafields, $array_key, $outputlangs); + } return $array_thirdparty; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define array with couple substitution key => substitution value * @@ -241,9 +241,9 @@ abstract class CommonDocGenerator * @param string $array_key Name of the key for return array * @return array Array of substitution key->code */ - public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object') - { - // phpcs:enable + public function get_substitutionarray_contact($object, $outputlangs, $array_key = 'object') + { + // phpcs:enable global $conf, $extrafields; if (empty($object->country) && !empty($object->country_code)) @@ -285,67 +285,67 @@ abstract class CommonDocGenerator $array_key.'_civility' => $object->civility, ); - // Retrieve extrafields - if (is_array($object->array_options) && count($object->array_options)) - { - $object->fetch_optionals(); + // Retrieve extrafields + if (is_array($object->array_options) && count($object->array_options)) + { + $object->fetch_optionals(); - $array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs); - } + $array_contact = $this->fill_substitutionarray_with_extrafields($object, $array_contact, $extrafields, $array_key, $outputlangs); + } return $array_contact; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Translate $outputlangs Language object for output - * @return array Array of substitution key->code - */ - public function get_substitutionarray_other($outputlangs) - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Translate $outputlangs Language object for output + * @return array Array of substitution key->code + */ + public function get_substitutionarray_other($outputlangs) + { + // phpcs:enable + global $conf; - $now = dol_now('gmt'); // gmt - $array_other = array( - // Date in default language - 'current_date'=>dol_print_date($now, 'day', 'tzuser'), - 'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'), + $now = dol_now('gmt'); // gmt + $array_other = array( + // Date in default language + 'current_date'=>dol_print_date($now, 'day', 'tzuser'), + 'current_datehour'=>dol_print_date($now, 'dayhour', 'tzuser'), 'current_server_date'=>dol_print_date($now, 'day', 'tzserver'), 'current_server_datehour'=>dol_print_date($now, 'dayhour', 'tzserver'), - // Date in requested output language - 'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs), + // Date in requested output language + 'current_date_locale'=>dol_print_date($now, 'day', 'tzuser', $outputlangs), 'current_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzuser', $outputlangs), 'current_server_date_locale'=>dol_print_date($now, 'day', 'tzserver', $outputlangs), 'current_server_datehour_locale'=>dol_print_date($now, 'dayhour', 'tzserver', $outputlangs), - ); + ); - foreach ($conf->global as $key => $val) - { - if (isASecretKey($key)) $newval = '*****forbidden*****'; - else $newval = $val; - $array_other['__['.$key.']__'] = $newval; - } + foreach ($conf->global as $key => $val) + { + if (isASecretKey($key)) $newval = '*****forbidden*****'; + else $newval = $val; + $array_other['__['.$key.']__'] = $newval; + } - return $array_other; - } + return $array_other; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define array with couple substitution key => substitution value * * @param Object $object Main object to use as data source * @param Translate $outputlangs Lang object to use for output - * @param string $array_key Name of the key for return array + * @param string $array_key Name of the key for return array * @return array Array of substitution */ public function get_substitutionarray_object($object, $outputlangs, $array_key = 'object') { - // phpcs:enable + // phpcs:enable global $conf, $extrafields; $sumpayed = $sumdeposit = $sumcreditnote = ''; @@ -381,11 +381,11 @@ abstract class CommonDocGenerator $array_key.'_ref_supplier'=>(!empty($object->ref_fournisseur) ? $object->ref_fournisseur : (empty($object->ref_supplier) ? '' : $object->ref_supplier)), $array_key.'_source_invoice_ref'=>$invoice_source->ref, // Dates - $array_key.'_hour'=>dol_print_date($date, 'hour'), + $array_key.'_hour'=>dol_print_date($date, 'hour'), $array_key.'_date'=>dol_print_date($date, 'day'), $array_key.'_date_rfc'=>dol_print_date($date, 'dayrfc'), $array_key.'_date_limit'=>(!empty($object->date_lim_reglement) ?dol_print_date($object->date_lim_reglement, 'day') : ''), - $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''), + $array_key.'_date_end'=>(!empty($object->fin_validite) ?dol_print_date($object->fin_validite, 'day') : ''), $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), $array_key.'_date_modification'=>(!empty($object->date_modification) ?dol_print_date($object->date_modification, 'day') : ''), $array_key.'_date_validation'=>(!empty($object->date_validation) ?dol_print_date($object->date_validation, 'dayhour') : ''), @@ -397,7 +397,7 @@ abstract class CommonDocGenerator $array_key.'_payment_term_code'=>$object->cond_reglement_code, $array_key.'_payment_term'=>($outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) != 'PaymentCondition'.$object->cond_reglement_code ? $outputlangs->transnoentitiesnoconv('PaymentCondition'.$object->cond_reglement_code) : ($object->cond_reglement_doc ? $object->cond_reglement_doc : $object->cond_reglement)), - $array_key.'_incoterms'=>(method_exists($object, 'display_incoterms') ? $object->display_incoterms() : ''), + $array_key.'_incoterms'=>(method_exists($object, 'display_incoterms') ? $object->display_incoterms() : ''), $array_key.'_bank_iban'=>$bank_account->iban, $array_key.'_bank_bic'=>$bank_account->bic, @@ -416,8 +416,8 @@ abstract class CommonDocGenerator $array_key.'_multicurrency_code' => price2num($object->multicurrency_code), $array_key.'_multicurrency_tx' => price2num($object->multicurrency_tx), - $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht), - $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva), + $array_key.'_multicurrency_total_ht' => price2num($object->multicurrency_total_ht), + $array_key.'_multicurrency_total_tva' => price2num($object->multicurrency_total_tva), $array_key.'_multicurrency_total_ttc' => price2num($object->multicurrency_total_ttc), $array_key.'_multicurrency_total_ht_locale' => price($object->multicurrency_total_ht, 0, $outputlangs), $array_key.'_multicurrency_total_tva_locale' => price($object->multicurrency_total_tva, 0, $outputlangs), @@ -472,11 +472,11 @@ abstract class CommonDocGenerator $totalUp = 0; foreach ($object->lines as $line) { - // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility + // $line->tva_tx format depends on database field accuraty, no reliable. This is kept for backward compatibility if (empty($resarray[$array_key.'_total_vat_'.$line->tva_tx])) $resarray[$array_key.'_total_vat_'.$line->tva_tx] = 0; $resarray[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; $resarray[$array_key.'_total_vat_locale_'.$line->tva_tx] = price($resarray[$array_key.'_total_vat_'.$line->tva_tx]); - // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example) + // $vatformated is vat without not expected chars (so 20, or 8.5 or 5.99 for example) $vatformated = vatrate($line->tva_tx); if (empty($resarray[$array_key.'_total_vat_'.$vatformated])) $resarray[$array_key.'_total_vat_'.$vatformated] = 0; $resarray[$array_key.'_total_vat_'.$vatformated] += $line->total_tva; @@ -514,7 +514,7 @@ abstract class CommonDocGenerator return $resarray; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Define array with couple substitution key => substitution value * @@ -525,7 +525,7 @@ abstract class CommonDocGenerator */ public function get_substitutionarray_lines($line, $outputlangs, $linenumber = 0) { - // phpcs:enable + // phpcs:enable global $conf; $resarray = array( @@ -537,9 +537,9 @@ abstract class CommonDocGenerator 'line_product_type'=>$line->product_type, 'line_desc'=>$line->desc, 'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits), - 'line_localtax1_rate'=>vatrate($line->localtax1_tx), - 'line_localtax2_rate'=>vatrate($line->localtax1_tx), - 'line_up'=>price2num($line->subprice), + 'line_localtax1_rate'=>vatrate($line->localtax1_tx), + 'line_localtax2_rate'=>vatrate($line->localtax1_tx), + 'line_up'=>price2num($line->subprice), 'line_up_locale'=>price($line->subprice, 0, $outputlangs), 'line_total_up'=>price2num($line->subprice * $line->qty), 'line_total_up_locale'=>price($line->subprice * $line->qty, 0, $outputlangs), @@ -551,31 +551,31 @@ abstract class CommonDocGenerator 'line_price_ht_locale'=>price($line->total_ht, 0, $outputlangs), 'line_price_ttc_locale'=>price($line->total_ttc, 0, $outputlangs), 'line_price_vat_locale'=>price($line->total_tva, 0, $outputlangs), - // Dates + // Dates 'line_date_start'=>dol_print_date($line->date_start, 'day'), 'line_date_start_locale'=>dol_print_date($line->date_start, 'day', 'tzserver', $outputlangs), - 'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'), - 'line_date_end'=>dol_print_date($line->date_end, 'day'), - 'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs), - 'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'), + 'line_date_start_rfc'=>dol_print_date($line->date_start, 'dayrfc'), + 'line_date_end'=>dol_print_date($line->date_end, 'day'), + 'line_date_end_locale'=>dol_print_date($line->date_end, 'day', 'tzserver', $outputlangs), + 'line_date_end_rfc'=>dol_print_date($line->date_end, 'dayrfc'), - 'line_multicurrency_code' => price2num($line->multicurrency_code), - 'line_multicurrency_subprice' => price2num($line->multicurrency_subprice), - 'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht), - 'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva), - 'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc), - 'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs), - 'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs), - 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), - 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), + 'line_multicurrency_code' => price2num($line->multicurrency_code), + 'line_multicurrency_subprice' => price2num($line->multicurrency_subprice), + 'line_multicurrency_total_ht' => price2num($line->multicurrency_total_ht), + 'line_multicurrency_total_tva' => price2num($line->multicurrency_total_tva), + 'line_multicurrency_total_ttc' => price2num($line->multicurrency_total_ttc), + 'line_multicurrency_subprice_locale' => price($line->multicurrency_subprice, 0, $outputlangs), + 'line_multicurrency_total_ht_locale' => price($line->multicurrency_total_ht, 0, $outputlangs), + 'line_multicurrency_total_tva_locale' => price($line->multicurrency_total_tva, 0, $outputlangs), + 'line_multicurrency_total_ttc_locale' => price($line->multicurrency_total_ttc, 0, $outputlangs), ); - // Units + // Units if ($conf->global->PRODUCT_USE_UNITS) { - $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long')); - $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short')); - } + $resarray['line_unit'] = $outputlangs->trans($line->getLabelOfUnit('long')); + $resarray['line_unit_short'] = $outputlangs->trans($line->getLabelOfUnit('short')); + } // Retrieve extrafields $extrafieldkey = $line->table_element; @@ -585,14 +585,14 @@ abstract class CommonDocGenerator $extrafields->fetch_name_optionals_label($extrafieldkey, true); $line->fetch_optionals(); - $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); + $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); - // Check if the current line belongs to a supplier order - if (get_class($line) == 'CommandeFournisseurLigne') - { - // Add the product supplier extrafields to the substitutions - $extrafields->fetch_name_optionals_label("product_fournisseur_price"); - $extralabels = $extrafields->attributes["product_fournisseur_price"]['label']; + // Check if the current line belongs to a supplier order + if (get_class($line) == 'CommandeFournisseurLigne') + { + // Add the product supplier extrafields to the substitutions + $extrafields->fetch_name_optionals_label("product_fournisseur_price"); + $extralabels = $extrafields->attributes["product_fournisseur_price"]['label']; if (!empty($extralabels) && is_array($extralabels)) { @@ -619,7 +619,7 @@ abstract class CommonDocGenerator } } } - } + } // Load product data optional fields to the line -> enables to use "line_options_{extrafield}" if (isset($line->fk_product) && $line->fk_product > 0) @@ -633,158 +633,158 @@ abstract class CommonDocGenerator return $resarray; } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Expedition $object Main object to use as data source - * @param Translate $outputlangs Lang object to use for output - * @param array $array_key Name of the key for return array - * @return array Array of substitution - */ - public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object') - { - // phpcs:enable - global $conf, $extrafields; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Expedition $object Main object to use as data source + * @param Translate $outputlangs Lang object to use for output + * @param array $array_key Name of the key for return array + * @return array Array of substitution + */ + public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object') + { + // phpcs:enable + global $conf, $extrafields; dol_include_once('/core/lib/product.lib.php'); $object->list_delivery_methods($object->shipping_method_id); $calculatedVolume = ($object->trueWidth * $object->trueHeight * $object->trueDepth); - $array_shipment = array( - $array_key.'_id'=>$object->id, - $array_key.'_ref'=>$object->ref, - $array_key.'_ref_ext'=>$object->ref_ext, - $array_key.'_ref_customer'=>$object->ref_customer, - $array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'), - $array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'), - $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), - $array_key.'_total_ht'=>price($object->total_ht), - $array_key.'_total_vat'=>price($object->total_tva), - $array_key.'_total_ttc'=>price($object->total_ttc), - $array_key.'_total_discount_ht' => price($object->getTotalDiscount()), - $array_key.'_note_private'=>$object->note_private, - $array_key.'_note'=>$object->note_public, - $array_key.'_tracking_number'=>$object->tracking_number, - $array_key.'_tracking_url'=>$object->tracking_url, - $array_key.'_shipping_method'=>$object->listmeths[0]['libelle'], - $array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units), - $array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units), - $array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units), - $array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units), - $array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'), - ); + $array_shipment = array( + $array_key.'_id'=>$object->id, + $array_key.'_ref'=>$object->ref, + $array_key.'_ref_ext'=>$object->ref_ext, + $array_key.'_ref_customer'=>$object->ref_customer, + $array_key.'_date_delivery'=>dol_print_date($object->date_delivery, 'day'), + $array_key.'_hour_delivery'=>dol_print_date($object->date_delivery, 'hour'), + $array_key.'_date_creation'=>dol_print_date($object->date_creation, 'day'), + $array_key.'_total_ht'=>price($object->total_ht), + $array_key.'_total_vat'=>price($object->total_tva), + $array_key.'_total_ttc'=>price($object->total_ttc), + $array_key.'_total_discount_ht' => price($object->getTotalDiscount()), + $array_key.'_note_private'=>$object->note_private, + $array_key.'_note'=>$object->note_public, + $array_key.'_tracking_number'=>$object->tracking_number, + $array_key.'_tracking_url'=>$object->tracking_url, + $array_key.'_shipping_method'=>$object->listmeths[0]['libelle'], + $array_key.'_weight'=>$object->trueWeight.' '.measuringUnitString(0, 'weight', $object->weight_units), + $array_key.'_width'=>$object->trueWidth.' '.measuringUnitString(0, 'size', $object->width_units), + $array_key.'_height'=>$object->trueHeight.' '.measuringUnitString(0, 'size', $object->height_units), + $array_key.'_depth'=>$object->trueDepth.' '.measuringUnitString(0, 'size', $object->depth_units), + $array_key.'_size'=>$calculatedVolume.' '.measuringUnitString(0, 'volume'), + ); - // Add vat by rates - foreach ($object->lines as $line) - { - if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0; - $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; - } + // Add vat by rates + foreach ($object->lines as $line) + { + if (empty($array_shipment[$array_key.'_total_vat_'.$line->tva_tx])) $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] = 0; + $array_shipment[$array_key.'_total_vat_'.$line->tva_tx] += $line->total_tva; + } - // Retrieve extrafields - if (is_array($object->array_options) && count($object->array_options)) - { - $object->fetch_optionals(); + // Retrieve extrafields + if (is_array($object->array_options) && count($object->array_options)) + { + $object->fetch_optionals(); - $array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs); - } + $array_shipment = $this->fill_substitutionarray_with_extrafields($object, $array_shipment, $extrafields, $array_key, $outputlangs); + } - return $array_shipment; - } + return $array_shipment; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param ExpeditionLigne $line Object line - * @param Translate $outputlangs Lang object to use for output - * @return array Substitution array - */ - public function get_substitutionarray_shipment_lines($line, $outputlangs) - { - // phpcs:enable - global $conf; - dol_include_once('/core/lib/product.lib.php'); + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param ExpeditionLigne $line Object line + * @param Translate $outputlangs Lang object to use for output + * @return array Substitution array + */ + public function get_substitutionarray_shipment_lines($line, $outputlangs) + { + // phpcs:enable + global $conf; + dol_include_once('/core/lib/product.lib.php'); - $resarray = array( - 'line_fulldesc'=>doc_getlinedesc($line, $outputlangs), - 'line_product_ref'=>$line->product_ref, - 'line_product_label'=>$line->product_label, - 'line_desc'=>$line->desc, - 'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits), - 'line_up'=>price($line->subprice), - 'line_total_up'=>price($line->subprice * $line->qty), - 'line_qty'=>$line->qty, - 'line_qty_shipped'=>$line->qty_shipped, - 'line_qty_asked'=>$line->qty_asked, - 'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''), - 'line_price_ht'=>price($line->total_ht), - 'line_price_ttc'=>price($line->total_ttc), - 'line_price_vat'=>price($line->total_tva), - 'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units), - 'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units), - 'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units), - 'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units), - ); + $resarray = array( + 'line_fulldesc'=>doc_getlinedesc($line, $outputlangs), + 'line_product_ref'=>$line->product_ref, + 'line_product_label'=>$line->product_label, + 'line_desc'=>$line->desc, + 'line_vatrate'=>vatrate($line->tva_tx, true, $line->info_bits), + 'line_up'=>price($line->subprice), + 'line_total_up'=>price($line->subprice * $line->qty), + 'line_qty'=>$line->qty, + 'line_qty_shipped'=>$line->qty_shipped, + 'line_qty_asked'=>$line->qty_asked, + 'line_discount_percent'=>($line->remise_percent ? $line->remise_percent.'%' : ''), + 'line_price_ht'=>price($line->total_ht), + 'line_price_ttc'=>price($line->total_ttc), + 'line_price_vat'=>price($line->total_tva), + 'line_weight'=>empty($line->weight) ? '' : $line->weight * $line->qty_shipped.' '.measuringUnitString(0, 'weight', $line->weight_units), + 'line_length'=>empty($line->length) ? '' : $line->length * $line->qty_shipped.' '.measuringUnitString(0, 'size', $line->length_units), + 'line_surface'=>empty($line->surface) ? '' : $line->surface * $line->qty_shipped.' '.measuringUnitString(0, 'surface', $line->surface_units), + 'line_volume'=>empty($line->volume) ? '' : $line->volume * $line->qty_shipped.' '.measuringUnitString(0, 'volume', $line->volume_units), + ); - // Retrieve extrafields - $extrafieldkey = $line->element; - $array_key = "line"; - require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - $extrafields = new ExtraFields($this->db); - $extrafields->fetch_name_optionals_label($extrafieldkey, true); - $line->fetch_optionals(); + // Retrieve extrafields + $extrafieldkey = $line->element; + $array_key = "line"; + require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + $extrafields = new ExtraFields($this->db); + $extrafields->fetch_name_optionals_label($extrafieldkey, true); + $line->fetch_optionals(); - $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); + $resarray = $this->fill_substitutionarray_with_extrafields($line, $resarray, $extrafields, $array_key, $outputlangs); - return $resarray; - } + return $resarray; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Define array with couple substitution key => substitution value - * - * @param Object $object Dolibarr Object - * @param Translate $outputlangs Language object for output - * @param boolean $recursive Want to fetch child array or child object - * @return array Array of substitution key->code - */ - public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true) - { - // phpcs:enable - $array_other = array(); - if (!empty($object)) { - foreach ($object as $key => $value) { - if (!empty($value)) { - if (!is_array($value) && !is_object($value)) { - $array_other['object_'.$key] = $value; - } - if (is_array($value) && $recursive) { - $array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false); - } - } - } - } - return $array_other; - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Define array with couple substitution key => substitution value + * + * @param Object $object Dolibarr Object + * @param Translate $outputlangs Language object for output + * @param boolean $recursive Want to fetch child array or child object + * @return array Array of substitution key->code + */ + public function get_substitutionarray_each_var_object(&$object, $outputlangs, $recursive = true) + { + // phpcs:enable + $array_other = array(); + if (!empty($object)) { + foreach ($object as $key => $value) { + if (!empty($value)) { + if (!is_array($value) && !is_object($value)) { + $array_other['object_'.$key] = $value; + } + if (is_array($value) && $recursive) { + $array_other['object_'.$key] = $this->get_substitutionarray_each_var_object($value, $outputlangs, false); + } + } + } + } + return $array_other; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Fill array with couple extrafield key => extrafield value - * - * @param Object $object Object with extrafields (must have $object->array_options filled) - * @param array $array_to_fill Substitution array - * @param Extrafields $extrafields Extrafields object - * @param string $array_key Prefix for name of the keys into returned array - * @param Translate $outputlangs Lang object to use for output - * @return array Substitution array - */ - public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs) - { - // phpcs:enable + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Fill array with couple extrafield key => extrafield value + * + * @param Object $object Object with extrafields (must have $object->array_options filled) + * @param array $array_to_fill Substitution array + * @param Extrafields $extrafields Extrafields object + * @param string $array_key Prefix for name of the keys into returned array + * @param Translate $outputlangs Lang object to use for output + * @return array Substitution array + */ + public function fill_substitutionarray_with_extrafields($object, $array_to_fill, $extrafields, $array_key, $outputlangs) + { + // phpcs:enable global $conf; if (is_array($extrafields->attributes[$object->table_element]['label'])) { @@ -875,671 +875,671 @@ abstract class CommonDocGenerator * @param int $hidebottom Hide bottom * @return void */ - public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0) - { - if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y); - $pdf->line($x + $l, $y, $x + $l, $y + $h); - if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h); - $pdf->line($x, $y + $h, $x, $y); - } - - - /** - * uasort callback function to Sort columns fields - * - * @param array $a PDF lines array fields configs - * @param array $b PDF lines array fields configs - * @return int Return compare result - */ - public function columnSort($a, $b) - { - if (empty($a['rank'])) { $a['rank'] = 0; } - if (empty($b['rank'])) { $b['rank'] = 0; } - if ($a['rank'] == $b['rank']) { - return 0; - } - return ($a['rank'] > $b['rank']) ? -1 : 1; - } - - /** - * Prepare Array Column Field - * - * @param object $object common object - * @param Translate $outputlangs langs - * @param int $hidedetails Do not show line details - * @param int $hidedesc Do not show desc - * @param int $hideref Do not show ref - * @return null - */ - public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) - { - global $conf; - - $this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); - - - // Sorting - uasort($this->cols, array($this, 'columnSort')); - - // Positionning - $curX = $this->page_largeur - $this->marge_droite; // start from right - - // Array width - $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche; - - // Count flexible column - $totalDefinedColWidth = 0; - $countFlexCol = 0; - foreach ($this->cols as $colKey =>& $colDef) - { - if (!$this->getColumnStatus($colKey)) continue; // continue if disabled - - if (!empty($colDef['scale'])) { - // In case of column width is defined by percentage - $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100); - } - - if (empty($colDef['width'])) { - $countFlexCol++; - } else { - $totalDefinedColWidth += $colDef['width']; - } - } - - foreach ($this->cols as $colKey =>& $colDef) - { - // setting empty conf with default - if (!empty($colDef['title'])) { - $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']); - } else { - $colDef['title'] = $this->defaultTitlesFieldsStyle; - } - - // setting empty conf with default - if (!empty($colDef['content'])) { - $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']); - } else { - $colDef['content'] = $this->defaultContentsFieldsStyle; - } - - if ($this->getColumnStatus($colKey)) - { - // In case of flexible column - if (empty($colDef['width'])) { - $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol; - } - - // Set positions - $lastX = $curX; - $curX = $lastX - $colDef['width']; - $colDef['xStartPos'] = $curX; - $colDef['xEndPos'] = $lastX; - } - } - } - - /** - * get column content width from column key - * - * @param string $colKey the column key - * @return float width in mm - */ - public function getColumnContentWidth($colKey) - { - $colDef = $this->cols[$colKey]; - return $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1]; - } - - - /** - * get column content X (abscissa) left position from column key - * - * @param string $colKey the column key - * @return float X position in mm - */ - public function getColumnContentXStart($colKey) - { - $colDef = $this->cols[$colKey]; - return $colDef['xStartPos'] + $colDef['content']['padding'][3]; - } - - /** - * get column position rank from column key - * - * @param string $colKey the column key - * @return int rank on success and -1 on error - */ - public function getColumnRank($colKey) - { - if (!isset($this->cols[$colKey]['rank'])) return -1; - return $this->cols[$colKey]['rank']; - } - - /** - * get column position rank from column key - * - * @param string $newColKey the new column key - * @param array $defArray a single column definition array - * @param string $targetCol target column used to place the new column beside - * @param bool $insertAfterTarget insert before or after target column ? - * @return int new rank on success and -1 on error - */ - public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false) - { - // prepare wanted rank - $rank = -1; - - // try to get rank from target column - if (!empty($targetCol)) { - $rank = $this->getColumnRank($targetCol); - if ($rank >= 0 && $insertAfterTarget) { $rank++; } - } - - // get rank from new column definition - if ($rank < 0 && !empty($defArray['rank'])) { - $rank = $defArray['rank']; - } - - // error: no rank - if ($rank < 0) { return -1; } - - foreach ($this->cols as $colKey =>& $colDef) - { - if ($rank <= $colDef['rank']) - { - $colDef['rank'] = $colDef['rank'] + 1; - } - } - - $defArray['rank'] = $rank; - $this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys - - return $rank; - } - - - /** - * print standard column content - * - * @param TCPDF $pdf pdf object - * @param float $curY curent Y position - * @param string $colKey the column key - * @param string $columnText column text - * @return null - */ - public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '') - { - global $hookmanager; - - $parameters = array( - 'curY' => &$curY, - 'columnText' => $columnText, - 'colKey' => $colKey, - 'pdf' => &$pdf, - ); - $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (!$reshook) - { - if (empty($columnText)) return; - $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position - $colDef = $this->cols[$colKey]; - // save curent cell padding - $curentCellPaddinds = $pdf->getCellPaddings(); - // set cell padding with column content definition - $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); - $pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']); - - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - } - } - - - /** - * print description column content - * - * @param TCPDF $pdf pdf object - * @param float $curY curent Y position - * @param string $colKey the column key - * @param object $object CommonObject - * @param int $i the $object->lines array key - * @param Translate $outputlangs Output language - * @param int $hideref hide ref - * @param int $hidedesc hide desc - * @param int $issupplierline if object need supplier product - * @return null - */ - public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0) + public function printRect($pdf, $x, $y, $l, $h, $hidetop = 0, $hidebottom = 0) { - // load desc col params - $colDef = $this->cols[$colKey]; - // save curent cell padding - $curentCellPaddinds = $pdf->getCellPaddings(); - // set cell padding with column content definition - $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); - - // line description - pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline); - $posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0]; - - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - - // Display extrafield if needed - $params = array( - 'display' => 'list', - 'printableEnable' => array(3), - 'printableEnableNotEmpty' => array(4) - ); - $extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params); - if (!empty($extrafieldDesc)) { - $this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc); - } - } - - /** - * get extrafield content for pdf writeHtmlCell compatibility - * usage for PDF line columns and object note block - * - * @param object $object common object - * @param string $extrafieldKey the extrafield key - * @return string - */ - public function getExtrafieldContent($object, $extrafieldKey) - { - global $hookmanager; - - if (empty($object->table_element)) { return; } - - $extrafieldsKeyPrefix = "options_"; - - // Cleanup extrafield key to remove prefix if present - $pos = strpos($extrafieldKey, $extrafieldsKeyPrefix); - if ($pos === 0) { - $extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix)); - } - - $extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey; + if (empty($hidetop) || $hidetop == -1) $pdf->line($x, $y, $x + $l, $y); + $pdf->line($x + $l, $y, $x + $l, $y + $h); + if (empty($hidebottom)) $pdf->line($x + $l, $y + $h, $x, $y + $h); + $pdf->line($x, $y + $h, $x, $y); + } - // Load extrafiels if not allready does - if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } - if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } - $extrafields = $this->extrafieldsCache; + /** + * uasort callback function to Sort columns fields + * + * @param array $a PDF lines array fields configs + * @param array $b PDF lines array fields configs + * @return int Return compare result + */ + public function columnSort($a, $b) + { + if (empty($a['rank'])) { $a['rank'] = 0; } + if (empty($b['rank'])) { $b['rank'] = 0; } + if ($a['rank'] == $b['rank']) { + return 0; + } + return ($a['rank'] > $b['rank']) ? -1 : 1; + } - $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element); + /** + * Prepare Array Column Field + * + * @param object $object common object + * @param Translate $outputlangs langs + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return null + */ + public function prepareArrayColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) + { + global $conf; - // TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ... - if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') { - // for lack of anything better we cleanup all html tags - $extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent); - } - - $parameters = array( - 'object' => $object, - 'extrafields' => $extrafields, - 'extrafieldKey' => $extrafieldKey, - 'extrafieldOutputContent' =>& $extrafieldOutputContent - ); - $reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if ($reshook) - { - $extrafieldOutputContent = $hookmanager->resPrint; - } - - return $extrafieldOutputContent; - } + $this->defineColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); - /** - * display extrafields columns content - * - * @param object $object line of common object - * @param Translate $outputlangs Output language - * @param array $params array of additionals parameters - * @return double max y value - */ - public function getExtrafieldsInHtml($object, $outputlangs, $params = array()) - { - global $hookmanager; + // Sorting + uasort($this->cols, array($this, 'columnSort')); - if (empty($object->table_element)) { - return; - } + // Positionning + $curX = $this->page_largeur - $this->marge_droite; // start from right - // Load extrafiels if not allready does - if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } - if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } - $extrafields = $this->extrafieldsCache; + // Array width + $arrayWidth = $this->page_largeur - $this->marge_droite - $this->marge_gauche; - $defaultParams = array( - 'style' => '', - 'display' => 'auto', // auto, table, list - 'printableEnable' => array(1), - 'printableEnableNotEmpty' => array(2), + // Count flexible column + $totalDefinedColWidth = 0; + $countFlexCol = 0; + foreach ($this->cols as $colKey =>& $colDef) + { + if (!$this->getColumnStatus($colKey)) continue; // continue if disabled - 'table' => array( - 'maxItemsInRow' => 2, - 'cellspacing' => 0, - 'cellpadding' => 0, - 'border' => 0, - 'labelcolwidth' => '25%', - 'arrayOfLineBreakType' => array('text', 'html') - ), + if (!empty($colDef['scale'])) { + // In case of column width is defined by percentage + $colDef['width'] = abs($arrayWidth * $colDef['scale'] / 100); + } - 'list' => array( - 'separator' => '
' - ), + if (empty($colDef['width'])) { + $countFlexCol++; + } else { + $totalDefinedColWidth += $colDef['width']; + } + } - 'auto' => array( - 'list' => 0, // 0 for default - 'table' => 4 // if there more than x extrafield to display - ), - ); + foreach ($this->cols as $colKey =>& $colDef) + { + // setting empty conf with default + if (!empty($colDef['title'])) { + $colDef['title'] = array_replace($this->defaultTitlesFieldsStyle, $colDef['title']); + } else { + $colDef['title'] = $this->defaultTitlesFieldsStyle; + } - $params = $params + $defaultParams; + // setting empty conf with default + if (!empty($colDef['content'])) { + $colDef['content'] = array_replace($this->defaultContentsFieldsStyle, $colDef['content']); + } else { + $colDef['content'] = $this->defaultContentsFieldsStyle; + } + + if ($this->getColumnStatus($colKey)) + { + // In case of flexible column + if (empty($colDef['width'])) { + $colDef['width'] = abs(($arrayWidth - $totalDefinedColWidth)) / $countFlexCol; + } + + // Set positions + $lastX = $curX; + $curX = $lastX - $colDef['width']; + $colDef['xStartPos'] = $curX; + $colDef['xEndPos'] = $lastX; + } + } + } + + /** + * get column content width from column key + * + * @param string $colKey the column key + * @return float width in mm + */ + public function getColumnContentWidth($colKey) + { + $colDef = $this->cols[$colKey]; + return $colDef['width'] - $colDef['content']['padding'][3] - $colDef['content']['padding'][1]; + } - /** - * @var $extrafields ExtraFields - */ + /** + * get column content X (abscissa) left position from column key + * + * @param string $colKey the column key + * @return float X position in mm + */ + public function getColumnContentXStart($colKey) + { + $colDef = $this->cols[$colKey]; + return $colDef['xStartPos'] + $colDef['content']['padding'][3]; + } - $html = ''; - $fields = array(); + /** + * get column position rank from column key + * + * @param string $colKey the column key + * @return int rank on success and -1 on error + */ + public function getColumnRank($colKey) + { + if (!isset($this->cols[$colKey]['rank'])) return -1; + return $this->cols[$colKey]['rank']; + } - if (is_array($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) - { - // Enable extrafield ? - $enabled = 0; - $disableOnEmpty = 0; - if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { - $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); - if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) { - $enabled = 1; - } + /** + * get column position rank from column key + * + * @param string $newColKey the new column key + * @param array $defArray a single column definition array + * @param string $targetCol target column used to place the new column beside + * @param bool $insertAfterTarget insert before or after target column ? + * @return int new rank on success and -1 on error + */ + public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false) + { + // prepare wanted rank + $rank = -1; - if (in_array($printable, $params['printableEnableNotEmpty'])) { - $disableOnEmpty = 1; - } - } + // try to get rank from target column + if (!empty($targetCol)) { + $rank = $this->getColumnRank($targetCol); + if ($rank >= 0 && $insertAfterTarget) { $rank++; } + } - if (empty($enabled)) { - continue; - } + // get rank from new column definition + if ($rank < 0 && !empty($defArray['rank'])) { + $rank = $defArray['rank']; + } - $field = new stdClass(); - $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]); - $field->content = $this->getExtrafieldContent($object, $key); - $field->label = $outputlangs->transnoentities($label); - $field->type = $extrafields->attributes[$object->table_element]['type'][$key]; + // error: no rank + if ($rank < 0) { return -1; } - // dont display if empty - if ($disableOnEmpty && empty($field->content)) { - continue; - } + foreach ($this->cols as $colKey =>& $colDef) + { + if ($rank <= $colDef['rank']) + { + $colDef['rank'] = $colDef['rank'] + 1; + } + } - $fields[] = $field; - } - } + $defArray['rank'] = $rank; + $this->cols[$newColKey] = $defArray; // array_replace is used to preserve keys - if (!empty($fields)) - { - // Sort extrafields by rank - uasort($fields, function ($a, $b) { - return ($a->rank > $b->rank) ? 1 : -1; + return $rank; + } + + + /** + * print standard column content + * + * @param TCPDF $pdf pdf object + * @param float $curY curent Y position + * @param string $colKey the column key + * @param string $columnText column text + * @return null + */ + public function printStdColumnContent($pdf, &$curY, $colKey, $columnText = '') + { + global $hookmanager; + + $parameters = array( + 'curY' => &$curY, + 'columnText' => $columnText, + 'colKey' => $colKey, + 'pdf' => &$pdf, + ); + $reshook = $hookmanager->executeHooks('printStdColumnContent', $parameters, $this); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if (!$reshook) + { + if (empty($columnText)) return; + $pdf->SetXY($this->getColumnContentXStart($colKey), $curY); // Set curent position + $colDef = $this->cols[$colKey]; + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); + // set cell padding with column content definition + $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); + $pdf->writeHTMLCell($colDef['width'], 2, $colDef['xStartPos'], $curY, $columnText, 0, 1, 0, true, $colDef['content']['align']); + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + } + } + + + /** + * print description column content + * + * @param TCPDF $pdf pdf object + * @param float $curY curent Y position + * @param string $colKey the column key + * @param object $object CommonObject + * @param int $i the $object->lines array key + * @param Translate $outputlangs Output language + * @param int $hideref hide ref + * @param int $hidedesc hide desc + * @param int $issupplierline if object need supplier product + * @return null + */ + public function printColDescContent($pdf, &$curY, $colKey, $object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $issupplierline = 0) + { + // load desc col params + $colDef = $this->cols[$colKey]; + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); + // set cell padding with column content definition + $pdf->setCellPaddings($colDef['content']['padding'][3], $colDef['content']['padding'][0], $colDef['content']['padding'][1], $colDef['content']['padding'][2]); + + // line description + pdf_writelinedesc($pdf, $object, $i, $outputlangs, $colDef['width'], 3, $colDef['xStartPos'], $curY, $hideref, $hidedesc, $issupplierline); + $posYAfterDescription = $pdf->GetY() - $colDef['content']['padding'][0]; + + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + + // Display extrafield if needed + $params = array( + 'display' => 'list', + 'printableEnable' => array(3), + 'printableEnableNotEmpty' => array(4) + ); + $extrafieldDesc = $this->getExtrafieldsInHtml($object->lines[$i], $outputlangs, $params); + if (!empty($extrafieldDesc)) { + $this->printStdColumnContent($pdf, $posYAfterDescription, $colKey, $extrafieldDesc); + } + } + + /** + * get extrafield content for pdf writeHtmlCell compatibility + * usage for PDF line columns and object note block + * + * @param object $object common object + * @param string $extrafieldKey the extrafield key + * @return string + */ + public function getExtrafieldContent($object, $extrafieldKey) + { + global $hookmanager; + + if (empty($object->table_element)) { return; } + + $extrafieldsKeyPrefix = "options_"; + + // Cleanup extrafield key to remove prefix if present + $pos = strpos($extrafieldKey, $extrafieldsKeyPrefix); + if ($pos === 0) { + $extrafieldKey = substr($extrafieldKey, strlen($extrafieldsKeyPrefix)); + } + + $extrafieldOptionsKey = $extrafieldsKeyPrefix.$extrafieldKey; + + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + $extrafieldOutputContent = $extrafields->showOutputField($extrafieldKey, $object->array_options[$extrafieldOptionsKey], '', $object->table_element); + + // TODO : allow showOutputField to be pdf public friendly, ex: in a link to object, clean getNomUrl to remove link and images... like a getName methode ... + if ($extrafields->attributes[$object->table_element]['type'][$extrafieldKey] == 'link') { + // for lack of anything better we cleanup all html tags + $extrafieldOutputContent = dol_string_nohtmltag($extrafieldOutputContent); + } + + $parameters = array( + 'object' => $object, + 'extrafields' => $extrafields, + 'extrafieldKey' => $extrafieldKey, + 'extrafieldOutputContent' =>& $extrafieldOutputContent + ); + $reshook = $hookmanager->executeHooks('getPDFExtrafieldContent', $parameters, $this); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook) + { + $extrafieldOutputContent = $hookmanager->resPrint; + } + + return $extrafieldOutputContent; + } + + + /** + * display extrafields columns content + * + * @param object $object line of common object + * @param Translate $outputlangs Output language + * @param array $params array of additionals parameters + * @return double max y value + */ + public function getExtrafieldsInHtml($object, $outputlangs, $params = array()) + { + global $hookmanager; + + if (empty($object->table_element)) { + return; + } + + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; + + $defaultParams = array( + 'style' => '', + 'display' => 'auto', // auto, table, list + 'printableEnable' => array(1), + 'printableEnableNotEmpty' => array(2), + + 'table' => array( + 'maxItemsInRow' => 2, + 'cellspacing' => 0, + 'cellpadding' => 0, + 'border' => 0, + 'labelcolwidth' => '25%', + 'arrayOfLineBreakType' => array('text', 'html') + ), + + 'list' => array( + 'separator' => '
' + ), + + 'auto' => array( + 'list' => 0, // 0 for default + 'table' => 4 // if there more than x extrafield to display + ), + ); + + $params = $params + $defaultParams; + + + /** + * @var $extrafields ExtraFields + */ + + $html = ''; + $fields = array(); + + if (is_array($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) + { + // Enable extrafield ? + $enabled = 0; + $disableOnEmpty = 0; + if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { + $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); + if (in_array($printable, $params['printableEnable']) || in_array($printable, $params['printableEnableNotEmpty'])) { + $enabled = 1; + } + + if (in_array($printable, $params['printableEnableNotEmpty'])) { + $disableOnEmpty = 1; + } + } + + if (empty($enabled)) { + continue; + } + + $field = new stdClass(); + $field->rank = intval($extrafields->attributes[$object->table_element]['pos'][$key]); + $field->content = $this->getExtrafieldContent($object, $key); + $field->label = $outputlangs->transnoentities($label); + $field->type = $extrafields->attributes[$object->table_element]['type'][$key]; + + // dont display if empty + if ($disableOnEmpty && empty($field->content)) { + continue; + } + + $fields[] = $field; + } + } + + if (!empty($fields)) + { + // Sort extrafields by rank + uasort($fields, function ($a, $b) { + return ($a->rank > $b->rank) ? 1 : -1; }); - // define some HTML content with style - $html .= !empty($params['style']) ? '' : ''; + // define some HTML content with style + $html .= !empty($params['style']) ? '' : ''; - // auto select display format - if ($params['display'] == 'auto') { - $lastNnumbItems = 0; - foreach ($params['auto'] as $display => $numbItems) { - if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) { - $lastNnumbItems = $numbItems; - $params['display'] = $display; - } - } - } + // auto select display format + if ($params['display'] == 'auto') { + $lastNnumbItems = 0; + foreach ($params['auto'] as $display => $numbItems) { + if ($lastNnumbItems <= $numbItems && count($fields) > $numbItems) { + $lastNnumbItems = $numbItems; + $params['display'] = $display; + } + } + } - if ($params['display'] == 'list') { - // Display in list format - $i = 0; - foreach ($fields as $field) { - $html .= !empty($i) ? $params['list']['separator'] : ''; - $html .= ''.$field->label.' : '; - $html .= $field->content; - $i++; - } - } elseif ($params['display'] == 'table') { - // Display in table format - $html .= ''; + if ($params['display'] == 'list') { + // Display in list format + $i = 0; + foreach ($fields as $field) { + $html .= !empty($i) ? $params['list']['separator'] : ''; + $html .= ''.$field->label.' : '; + $html .= $field->content; + $i++; + } + } elseif ($params['display'] == 'table') { + // Display in table format + $html .= '
'; - $html .= ""; - $itemsInRow = 0; - $maxItemsInRow = $params['table']['maxItemsInRow']; - foreach ($fields as $field) { - //$html.= !empty($html)?'
':''; - if ($itemsInRow >= $maxItemsInRow) { - // start a new line - $html .= ""; - $itemsInRow = 0; - } + $html .= ""; + $itemsInRow = 0; + $maxItemsInRow = $params['table']['maxItemsInRow']; + foreach ($fields as $field) { + //$html.= !empty($html)?'
':''; + if ($itemsInRow >= $maxItemsInRow) { + // start a new line + $html .= ""; + $itemsInRow = 0; + } - // for some type we need line break - if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) { - if ($itemsInRow > 0) { - // close table row and empty cols - for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) { - $html .= ""; - } - $html .= ""; + // for some type we need line break + if (in_array($field->type, $params['table']['arrayOfLineBreakType'])) { + if ($itemsInRow > 0) { + // close table row and empty cols + for ($i = $itemsInRow; $i <= $maxItemsInRow; $i++) { + $html .= ""; + } + $html .= ""; - // start a new line - $html .= ""; - } + // start a new line + $html .= ""; + } - $itemsInRow = $maxItemsInRow; - $html .= '"; - } else { - $itemsInRow++; - $html .= '"; + $itemsInRow = $maxItemsInRow; + $html .= '"; + } else { + $itemsInRow++; + $html .= '"; - $html .= '"; - } - } - $html .= ""; + $html .= '"; + } + } + $html .= ""; - $html .= '
'; - $html .= ''.$field->label.' : '; - $html .= $field->content; - $html .= "'; - $html .= ''.$field->label.' :'; - $html .= "'; + $html .= ''.$field->label.' : '; + $html .= $field->content; + $html .= "'; + $html .= ''.$field->label.' :'; + $html .= "'; - $html .= $field->content; - $html .= "
'; + $html .= $field->content; + $html .= "
'; - } - } + $html .= ''; + } + } - return $html; - } + return $html; + } - /** - * get column status from column key - * - * @param string $colKey the column key - * @return float width in mm - */ - public function getColumnStatus($colKey) - { - if (!empty($this->cols[$colKey]['status'])) { - return true; - } else return false; - } + /** + * get column status from column key + * + * @param string $colKey the column key + * @return float width in mm + */ + public function getColumnStatus($colKey) + { + if (!empty($this->cols[$colKey]['status'])) { + return true; + } else return false; + } - /** - * Print standard column content - * - * @param TCPDI $pdf Pdf object - * @param float $tab_top Tab top position - * @param float $tab_height Default tab height - * @param Translate $outputlangs Output language - * @param int $hidetop Hide top - * @return float Height of col tab titles - */ - public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0) - { - global $hookmanager, $conf; + /** + * Print standard column content + * + * @param TCPDI $pdf Pdf object + * @param float $tab_top Tab top position + * @param float $tab_height Default tab height + * @param Translate $outputlangs Output language + * @param int $hidetop Hide top + * @return float Height of col tab titles + */ + public function pdfTabTitles(&$pdf, $tab_top, $tab_height, $outputlangs, $hidetop = 0) + { + global $hookmanager, $conf; - foreach ($this->cols as $colKey => $colDef) { - $parameters = array( - 'colKey' => $colKey, - 'pdf' => $pdf, - 'outputlangs' => $outputlangs, - 'tab_top' => $tab_top, - 'tab_height' => $tab_height, - 'hidetop' => $hidetop - ); + foreach ($this->cols as $colKey => $colDef) { + $parameters = array( + 'colKey' => $colKey, + 'pdf' => $pdf, + 'outputlangs' => $outputlangs, + 'tab_top' => $tab_top, + 'tab_height' => $tab_height, + 'hidetop' => $hidetop + ); - $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook - if ($reshook < 0) { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - } elseif (empty($reshook)) { - if (!$this->getColumnStatus($colKey)) continue; + $reshook = $hookmanager->executeHooks('pdfTabTitles', $parameters, $this); // Note that $object may have been modified by hook + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } elseif (empty($reshook)) { + if (!$this->getColumnStatus($colKey)) continue; - // get title label - $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']); + // get title label + $colDef['title']['label'] = !empty($colDef['title']['label']) ? $colDef['title']['label'] : $outputlangs->transnoentities($colDef['title']['textkey']); - // Add column separator - if (!empty($colDef['border-left'])) { - $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height); - } + // Add column separator + if (!empty($colDef['border-left'])) { + $pdf->line($colDef['xStartPos'], $tab_top, $colDef['xStartPos'], $tab_top + $tab_height); + } - if (empty($hidetop)) { - // save curent cell padding - $curentCellPaddinds = $pdf->getCellPaddings(); + if (empty($hidetop)) { + // save curent cell padding + $curentCellPaddinds = $pdf->getCellPaddings(); - // Add space for lines (more if we need to show a second alternative language) - global $outputlangsbis; - if (is_object($outputlangsbis)) { - // set cell padding with column title definition - $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5); - } else { - // set cell padding with column title definition - $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]); - } + // Add space for lines (more if we need to show a second alternative language) + global $outputlangsbis; + if (is_object($outputlangsbis)) { + // set cell padding with column title definition + $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], 0.5); + } else { + // set cell padding with column title definition + $pdf->setCellPaddings($colDef['title']['padding'][3], $colDef['title']['padding'][0], $colDef['title']['padding'][1], $colDef['title']['padding'][2]); + } - $pdf->SetXY($colDef['xStartPos'], $tab_top); - $textWidth = $colDef['width']; - $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']); + $pdf->SetXY($colDef['xStartPos'], $tab_top); + $textWidth = $colDef['width']; + $pdf->MultiCell($textWidth, 2, $colDef['title']['label'], '', $colDef['title']['align']); - // Add variant of translation if $outputlangsbis is an object - if (is_object($outputlangsbis) && trim($colDef['title']['label'])) { - $pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]); - $pdf->SetXY($colDef['xStartPos'], $pdf->GetY()); - $textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']); - $pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']); - } + // Add variant of translation if $outputlangsbis is an object + if (is_object($outputlangsbis) && trim($colDef['title']['label'])) { + $pdf->setCellPaddings($colDef['title']['padding'][3], 0, $colDef['title']['padding'][1], $colDef['title']['padding'][2]); + $pdf->SetXY($colDef['xStartPos'], $pdf->GetY()); + $textbis = $outputlangsbis->transnoentities($colDef['title']['textkey']); + $pdf->MultiCell($textWidth, 2, $textbis, '', $colDef['title']['align']); + } - $this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight); + $this->tabTitleHeight = max($pdf->GetY() - $tab_top, $this->tabTitleHeight); - // restore cell padding - $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); - } - } - } + // restore cell padding + $pdf->setCellPaddings($curentCellPaddinds['L'], $curentCellPaddinds['T'], $curentCellPaddinds['R'], $curentCellPaddinds['B']); + } + } + } - return $this->tabTitleHeight; - } + return $this->tabTitleHeight; + } - /** - * Define Array Column Field for extrafields - * - * @param object $object common object det - * @param Translate $outputlangs langs - * @param int $hidedetails Do not show line details - * @return null - */ - public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0) - { - global $conf; + /** + * Define Array Column Field for extrafields + * + * @param object $object common object det + * @param Translate $outputlangs langs + * @param int $hidedetails Do not show line details + * @return null + */ + public function defineColumnExtrafield($object, $outputlangs, $hidedetails = 0) + { + global $conf; - if (!empty($hidedetails)) { - return; - } + if (!empty($hidedetails)) { + return; + } - if (empty($object->table_element)) { - return; - } + if (empty($object->table_element)) { + return; + } - // Load extrafiels if not allready does - if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } - if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } - $extrafields = $this->extrafieldsCache; + // Load extrafiels if not allready does + if (empty($this->extrafieldsCache)) { $this->extrafieldsCache = new ExtraFields($this->db); } + if (empty($this->extrafieldsCache->attributes[$object->table_element])) { $this->extrafieldsCache->fetch_name_optionals_label($object->table_element); } + $extrafields = $this->extrafieldsCache; - if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) - { - // Dont display separator yet even is set to be displayed (not compatible yet) - if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') - { - continue; - } + if (!empty($extrafields->attributes[$object->table_element]) && is_array($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $label) + { + // Dont display separator yet even is set to be displayed (not compatible yet) + if ($extrafields->attributes[$object->table_element]['type'][$key] == 'separate') + { + continue; + } - // Enable extrafield ? - $enabled = 0; - if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { - $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); - if ($printable === 1 || $printable === 2) { - $enabled = 1; - } - // Note : if $printable === 3 or 4 so, it's displayed after line description not in cols - } + // Enable extrafield ? + $enabled = 0; + if (!empty($extrafields->attributes[$object->table_element]['printable'][$key])) { + $printable = intval($extrafields->attributes[$object->table_element]['printable'][$key]); + if ($printable === 1 || $printable === 2) { + $enabled = 1; + } + // Note : if $printable === 3 or 4 so, it's displayed after line description not in cols + } - if (!$enabled) { continue; } // don't wast resourses if we don't need them... + if (!$enabled) { continue; } // don't wast resourses if we don't need them... - // Load language if required - if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]); + // Load language if required + if (!empty($extrafields->attributes[$object->table_element]['langfile'][$key])) $outputlangs->load($extrafields->attributes[$object->table_element]['langfile'][$key]); - // TODO : add more extrafield customisation capacities for PDF like width, rank... + // TODO : add more extrafield customisation capacities for PDF like width, rank... - // set column definition - $def = array( - 'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]), - 'width' => 25, // in mm - 'status' => boolval($enabled), - 'title' => array( - 'label' => $outputlangs->transnoentities($label) - ), - 'content' => array( - 'align' => 'C' - ), - 'border-left' => true, // add left line separator - ); + // set column definition + $def = array( + 'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]), + 'width' => 25, // in mm + 'status' => boolval($enabled), + 'title' => array( + 'label' => $outputlangs->transnoentities($label) + ), + 'content' => array( + 'align' => 'C' + ), + 'border-left' => true, // add left line separator + ); - $alignTypeRight = array('double', 'int', 'price'); - if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) { - $def['content']['align'] = 'R'; - } + $alignTypeRight = array('double', 'int', 'price'); + if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeRight)) { + $def['content']['align'] = 'R'; + } - $alignTypeLeft = array('text', 'html'); - if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) { - $def['content']['align'] = 'L'; - } + $alignTypeLeft = array('text', 'html'); + if (in_array($extrafields->attributes[$object->table_element]['type'][$key], $alignTypeLeft)) { + $def['content']['align'] = 'L'; + } - // for extrafields we use rank of extrafield to place it on PDF - $this->insertNewColumnDef("options_".$key, $def); - } - } - } + // for extrafields we use rank of extrafield to place it on PDF + $this->insertNewColumnDef("options_".$key, $def); + } + } + } } diff --git a/htdocs/core/class/hookmanager.class.php b/htdocs/core/class/hookmanager.class.php index 934c8d424a4..3c094ff5a6b 100644 --- a/htdocs/core/class/hookmanager.class.php +++ b/htdocs/core/class/hookmanager.class.php @@ -30,9 +30,9 @@ class HookManager { /** - * @var DoliDB Database handler. - */ - public $db; + * @var DoliDB Database handler. + */ + public $db; /** * @var string Error code (or message) @@ -44,18 +44,18 @@ class HookManager */ public $errors = array(); - // Context hookmanager was created for ('thirdpartycard', 'thirdpartydao', ...) - public $contextarray = array(); + // Context hookmanager was created for ('thirdpartycard', 'thirdpartydao', ...) + public $contextarray = array(); // Array with instantiated classes - public $hooks = array(); + public $hooks = array(); // Array result - public $resArray = array(); + public $resArray = array(); // Printable result - public $resPrint = ''; + public $resPrint = ''; // Nb of qualified hook ran - public $resNbOfHooks = 0; + public $resNbOfHooks = 0; /** * Constructor @@ -84,9 +84,9 @@ class HookManager global $conf; // Test if there is hooks to manage - if (!is_array($conf->modules_parts['hooks']) || empty($conf->modules_parts['hooks'])) return; + if (!is_array($conf->modules_parts['hooks']) || empty($conf->modules_parts['hooks'])) return; - // For backward compatibility + // For backward compatibility if (!is_array($arraycontext)) $arraycontext = array($arraycontext); $this->contextarray = array_unique(array_merge($arraycontext, $this->contextarray)); // All contexts are concatenated @@ -130,29 +130,29 @@ class HookManager return 1; } - /** - * Execute hooks (if they were initialized) for the given method - * - * @param string $method Name of method hooked ('doActions', 'printSearchForm', 'showInputField', ...) - * @param array $parameters Array of parameters - * @param Object $object Object to use hooks on - * @param string $action Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...) - * @return mixed For 'addreplace' hooks (doActions, formConfirm, formObjectOptions, pdf_xxx,...): Return 0 if we want to keep standard actions, >0 if we want to stop/replace standard actions, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller. - * For 'output' hooks (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...): Return 0, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller. - * All types can also return some values into an array ->results that will be finaly merged into this->resArray for caller. - * $this->error or this->errors are also defined by class called by this function if error. - */ + /** + * Execute hooks (if they were initialized) for the given method + * + * @param string $method Name of method hooked ('doActions', 'printSearchForm', 'showInputField', ...) + * @param array $parameters Array of parameters + * @param Object $object Object to use hooks on + * @param string $action Action code on calling page ('create', 'edit', 'view', 'add', 'update', 'delete'...) + * @return mixed For 'addreplace' hooks (doActions, formConfirm, formObjectOptions, pdf_xxx,...): Return 0 if we want to keep standard actions, >0 if we want to stop/replace standard actions, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller. + * For 'output' hooks (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...): Return 0, <0 if KO. Things to print are returned into ->resprints and set into ->resPrint. Things to return are returned into ->results by hook and set into ->resArray for caller. + * All types can also return some values into an array ->results that will be finaly merged into this->resArray for caller. + * $this->error or this->errors are also defined by class called by this function if error. + */ public function executeHooks($method, $parameters = array(), &$object = '', &$action = '') { - if (!is_array($this->hooks) || empty($this->hooks)) return 0; // No hook available, do nothing. + if (!is_array($this->hooks) || empty($this->hooks)) return 0; // No hook available, do nothing. - $parameters['context'] = join(':', $this->contextarray); - //dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']); + $parameters['context'] = join(':', $this->contextarray); + //dol_syslog(get_class($this).'::executeHooks method='.$method." action=".$action." context=".$parameters['context']); - // Define type of hook ('output' or 'addreplace'). - // TODO Remove hooks with type 'output'. All hooks must be converted into 'addreplace' hooks. - $hooktype = 'output'; - if (in_array( + // Define type of hook ('output' or 'addreplace'). + // TODO Remove hooks with type 'output'. All hooks must be converted into 'addreplace' hooks. + $hooktype = 'output'; + if (in_array( $method, array( 'addCalendarChoice', @@ -172,33 +172,33 @@ class HookManager 'formattachOptions', 'formBuilddocLineOptions', 'formatNotificationMessage', - 'formConfirm', + 'formConfirm', 'getAccessForbiddenMessage', 'getDirList', 'getFormMail', 'getFormatedCustomerRef', - 'getFormatedSupplierRef', + 'getFormatedSupplierRef', 'getIdProfUrl', 'getInputIdProf', 'moveUploadedFile', 'moreHtmlStatus', 'pdf_build_address', 'pdf_writelinedesc', - 'pdf_getlinenum', - 'pdf_getlineref', - 'pdf_getlineref_supplier', - 'pdf_getlinevatrate', - 'pdf_getlineupexcltax', - 'pdf_getlineupwithtax', - 'pdf_getlineqty', - 'pdf_getlineqty_asked', - 'pdf_getlineqty_shipped', - 'pdf_getlineqty_keeptoship', - 'pdf_getlineunit', - 'pdf_getlineremisepercent', - 'pdf_getlineprogress', - 'pdf_getlinetotalexcltax', - 'pdf_getlinetotalwithtax', + 'pdf_getlinenum', + 'pdf_getlineref', + 'pdf_getlineref_supplier', + 'pdf_getlinevatrate', + 'pdf_getlineupexcltax', + 'pdf_getlineupwithtax', + 'pdf_getlineqty', + 'pdf_getlineqty_asked', + 'pdf_getlineqty_shipped', + 'pdf_getlineqty_keeptoship', + 'pdf_getlineunit', + 'pdf_getlineremisepercent', + 'pdf_getlineprogress', + 'pdf_getlinetotalexcltax', + 'pdf_getlinetotalwithtax', 'paymentsupplierinvoices', 'printAddress', 'printEmail', @@ -213,88 +213,88 @@ class HookManager 'showLinkToObjectBlock', 'setContentSecurityPolicy', 'setHtmlTitle', - 'completeTabsHead' + 'completeTabsHead' ) )) $hooktype = 'addreplace'; - // Init return properties - $this->resPrint = ''; $this->resArray = array(); $this->resNbOfHooks = 0; + // Init return properties + $this->resPrint = ''; $this->resArray = array(); $this->resNbOfHooks = 0; - // Loop on each hook to qualify modules that have declared context - $modulealreadyexecuted = array(); - $resaction = 0; $error = 0; - foreach ($this->hooks as $context => $modules) // $this->hooks is an array with context as key and value is an array of modules that handle this context - { - if (!empty($modules)) - { - foreach ($modules as $module => $actionclassinstance) - { - //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
\n"; + // Loop on each hook to qualify modules that have declared context + $modulealreadyexecuted = array(); + $resaction = 0; $error = 0; + foreach ($this->hooks as $context => $modules) // $this->hooks is an array with context as key and value is an array of modules that handle this context + { + if (!empty($modules)) + { + foreach ($modules as $module => $actionclassinstance) + { + //print "Before hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
\n"; - // test to avoid running twice a hook, when a module implements several active contexts - if (in_array($module, $modulealreadyexecuted)) continue; + // test to avoid running twice a hook, when a module implements several active contexts + if (in_array($module, $modulealreadyexecuted)) continue; - // jump to next module/class if method does not exist - if (!method_exists($actionclassinstance, $method)) continue; + // jump to next module/class if method does not exist + if (!method_exists($actionclassinstance, $method)) continue; - $this->resNbOfHooks++; + $this->resNbOfHooks++; - $modulealreadyexecuted[$module] = $module; // Use the $currentcontext in method to avoid running twice + $modulealreadyexecuted[$module] = $module; // Use the $currentcontext in method to avoid running twice - // Clean class (an error may have been set from a previous call of another method for same module/hook) - $actionclassinstance->error = 0; - $actionclassinstance->errors = array(); + // Clean class (an error may have been set from a previous call of another method for same module/hook) + $actionclassinstance->error = 0; + $actionclassinstance->errors = array(); - dol_syslog(get_class($this)."::executeHooks Qualified hook found (hooktype=".$hooktype."). We call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", action=".$action." context=".$context, LOG_DEBUG); + dol_syslog(get_class($this)."::executeHooks Qualified hook found (hooktype=".$hooktype."). We call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", action=".$action." context=".$context, LOG_DEBUG); - // Add current context to avoid method execution in bad context, you can add this test in your method : eg if($currentcontext != 'formfile') return; - $parameters['currentcontext'] = $context; - // Hooks that must return int (hooks with type 'addreplace') - if ($hooktype == 'addreplace') - { - $resaction += $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) - if ($resaction < 0 || !empty($actionclassinstance->error) || (!empty($actionclassinstance->errors) && count($actionclassinstance->errors) > 0)) - { - $error++; - $this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors); - dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR); - } + // Add current context to avoid method execution in bad context, you can add this test in your method : eg if($currentcontext != 'formfile') return; + $parameters['currentcontext'] = $context; + // Hooks that must return int (hooks with type 'addreplace') + if ($hooktype == 'addreplace') + { + $resaction += $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) + if ($resaction < 0 || !empty($actionclassinstance->error) || (!empty($actionclassinstance->errors) && count($actionclassinstance->errors) > 0)) + { + $error++; + $this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors); + dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR); + } - if (isset($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results); - if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints; - } - // Generic hooks that return a string or array (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...) - else { - // TODO. this test should be done into the method of hook by returning nothing - if (is_array($parameters) && !empty($parameters['special_code']) && $parameters['special_code'] > 3 && $parameters['special_code'] != $actionclassinstance->module_number) continue; + if (isset($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results); + if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints; + } + // Generic hooks that return a string or array (printLeftBlock, formAddObjectLine, formBuilddocOptions, ...) + else { + // TODO. this test should be done into the method of hook by returning nothing + if (is_array($parameters) && !empty($parameters['special_code']) && $parameters['special_code'] > 3 && $parameters['special_code'] != $actionclassinstance->module_number) continue; - //dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG); - $resaction = $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) + //dol_syslog("Call method ".$method." of class ".get_class($actionclassinstance).", module=".$module.", hooktype=".$hooktype, LOG_DEBUG); + $resaction = $actionclassinstance->$method($parameters, $object, $action, $this); // $object and $action can be changed by method ($object->id during creation for example or $action to go back to other action for example) - if (!empty($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results); - if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints; - if (is_numeric($resaction) && $resaction < 0) - { - $error++; - $this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors); - dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR); - } - // TODO dead code to remove (do not enable this, but fix hook instead): result must not be a string but an int. you must use $actionclassinstance->resprints to return a string - if (!is_array($resaction) && !is_numeric($resaction)) - { - dol_syslog('Error: Bug into hook '.$method.' of module class '.get_class($actionclassinstance).'. Method must not return a string but an int (0=OK, 1=Replace, -1=KO) and set string into ->resprints', LOG_ERR); - if (empty($actionclassinstance->resprints)) { $this->resPrint .= $resaction; $resaction = 0; } - } - } + if (!empty($actionclassinstance->results) && is_array($actionclassinstance->results)) $this->resArray = array_merge($this->resArray, $actionclassinstance->results); + if (!empty($actionclassinstance->resprints)) $this->resPrint .= $actionclassinstance->resprints; + if (is_numeric($resaction) && $resaction < 0) + { + $error++; + $this->error = $actionclassinstance->error; $this->errors = array_merge($this->errors, (array) $actionclassinstance->errors); + dol_syslog("Error on hook module=".$module.", method ".$method.", class ".get_class($actionclassinstance).", hooktype=".$hooktype.(empty($this->error) ? '' : " ".$this->error).(empty($this->errors) ? '' : " ".join(",", $this->errors)), LOG_ERR); + } + // TODO dead code to remove (do not enable this, but fix hook instead): result must not be a string but an int. you must use $actionclassinstance->resprints to return a string + if (!is_array($resaction) && !is_numeric($resaction)) + { + dol_syslog('Error: Bug into hook '.$method.' of module class '.get_class($actionclassinstance).'. Method must not return a string but an int (0=OK, 1=Replace, -1=KO) and set string into ->resprints', LOG_ERR); + if (empty($actionclassinstance->resprints)) { $this->resPrint .= $resaction; $resaction = 0; } + } + } - //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
\n"; + //print "After hook ".get_class($actionclassinstance)." method=".$method." hooktype=".$hooktype." results=".count($actionclassinstance->results)." resprints=".count($actionclassinstance->resprints)." resaction=".$resaction."
\n"; - unset($actionclassinstance->results); - unset($actionclassinstance->resprints); - } - } - } + unset($actionclassinstance->results); + unset($actionclassinstance->resprints); + } + } + } - return ($error ? -1 : $resaction); + return ($error ? -1 : $resaction); } } diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index a6c458fc67b..e75653ae48b 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -38,693 +38,693 @@ */ class FormOther { - private $db; + private $db; - /** + /** * @var string Error code (or message) */ public $error; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + $this->db = $db; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML select list of export models - * - * @param string $selected Id modele pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $type Type des modeles recherches - * @param int $useempty Show an empty value in list - * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) - * @return void - */ - public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0, $fk_user = null) - { - // phpcs:enable - global $conf, $langs, $user; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML select list of export models + * + * @param string $selected Id modele pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $type Type des modeles recherches + * @param int $useempty Show an empty value in list + * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) + * @return void + */ + public function select_export_model($selected = '', $htmlname = 'exportmodelid', $type = '', $useempty = 0, $fk_user = null) + { + // phpcs:enable + global $conf, $langs, $user; - $sql = "SELECT rowid, label, fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; - $sql .= " WHERE type = '".$this->db->escape($type)."'"; + $sql = "SELECT rowid, label, fk_user"; + $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; + $sql .= " WHERE type = '".$this->db->escape($type)."'"; if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model - $sql .= " ORDER BY label"; - $result = $this->db->query($sql); - if ($result) - { - print ''; + if ($useempty) + { + print ''; + } - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($result); + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); - $label = $obj->label; - if ($obj->fk_user == 0) { - $label .= ' ('.$langs->trans("Everybody").')'; - } elseif (!empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) { - $tmpuser = new User($this->db); - $tmpuser->fetch($obj->fk_user); - $label .= ' ('.$tmpuser->getFullName($langs).')'; - } + $label = $obj->label; + if ($obj->fk_user == 0) { + $label .= ' ('.$langs->trans("Everybody").')'; + } elseif (!empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) { + $tmpuser = new User($this->db); + $tmpuser->fetch($obj->fk_user); + $label .= ' ('.$tmpuser->getFullName($langs).')'; + } - if ($selected == $obj->rowid) - { - print ''; - $i++; - } - print ""; - print ajax_combobox($htmlname); - } else { - dol_print_error($this->db); - } - } + if ($selected == $obj->rowid) + { + print ''; + $i++; + } + print ""; + print ajax_combobox($htmlname); + } else { + dol_print_error($this->db); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of export models - * - * @param string $selected Id modele pre-selectionne - * @param string $htmlname Nom de la zone select - * @param string $type Type des modeles recherches - * @param int $useempty Affiche valeur vide dans liste - * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) - * @return void - */ - public function select_import_model($selected = '', $htmlname = 'importmodelid', $type = '', $useempty = 0, $fk_user = null) - { - // phpcs:enable - global $conf, $langs, $user; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of export models + * + * @param string $selected Id modele pre-selectionne + * @param string $htmlname Nom de la zone select + * @param string $type Type des modeles recherches + * @param int $useempty Affiche valeur vide dans liste + * @param int $fk_user User that has created the template (this is set to null to get all export model when EXPORTS_SHARE_MODELS is on) + * @return void + */ + public function select_import_model($selected = '', $htmlname = 'importmodelid', $type = '', $useempty = 0, $fk_user = null) + { + // phpcs:enable + global $conf, $langs, $user; - $sql = "SELECT rowid, label, fk_user"; - $sql .= " FROM ".MAIN_DB_PREFIX."import_model"; - $sql .= " WHERE type = '".$this->db->escape($type)."'"; - if (!empty($fk_user)) $sql .= " AND fk_user IN (0, ".$fk_user.")"; // An export model - $sql .= " ORDER BY rowid"; - $result = $this->db->query($sql); - if ($result) - { - print ''; + if ($useempty) + { + print ''; + } - $num = $this->db->num_rows($result); - $i = 0; - while ($i < $num) - { - $obj = $this->db->fetch_object($result); + $num = $this->db->num_rows($result); + $i = 0; + while ($i < $num) + { + $obj = $this->db->fetch_object($result); - $label = $obj->label; - if ($obj->fk_user == 0) { - $label .= ' ('.$langs->trans("Everybody").')'; - } elseif (!empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) { - $tmpuser = new User($this->db); - $tmpuser->fetch($obj->fk_user); - $label .= ' ('.$tmpuser->getFullName($langs).')'; - } + $label = $obj->label; + if ($obj->fk_user == 0) { + $label .= ' ('.$langs->trans("Everybody").')'; + } elseif (!empty($conf->global->EXPORTS_SHARE_MODELS) && empty($fk_user) && is_object($user) && $user->id != $obj->fk_user) { + $tmpuser = new User($this->db); + $tmpuser->fetch($obj->fk_user); + $label .= ' ('.$tmpuser->getFullName($langs).')'; + } - if ($selected == $obj->rowid) - { - print ''; - $i++; - } - print ""; - print ajax_combobox($htmlname); - } else { - dol_print_error($this->db); - } - } + if ($selected == $obj->rowid) + { + print ''; + $i++; + } + print ""; + print ajax_combobox($htmlname); + } else { + dol_print_error($this->db); + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of ecotaxes with label - * - * @param string $selected Preselected ecotaxes - * @param string $htmlname Name of combo list - * @return integer - */ - public function select_ecotaxes($selected = '', $htmlname = 'ecotaxe_id') - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of ecotaxes with label + * + * @param string $selected Preselected ecotaxes + * @param string $htmlname Name of combo list + * @return integer + */ + public function select_ecotaxes($selected = '', $htmlname = 'ecotaxe_id') + { + // phpcs:enable + global $langs; - $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,"; - $sql .= " c.label as country"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid"; - $sql .= " ORDER BY country, e.organization ASC, e.code ASC"; + $sql = "SELECT e.rowid, e.code, e.label, e.price, e.organization,"; + $sql .= " c.label as country"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_ecotaxe as e,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE e.active = 1 AND e.fk_pays = c.rowid"; + $sql .= " ORDER BY country, e.organization ASC, e.code ASC"; - dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - print ''; - return 0; - } else { - dol_print_error($this->db); - return 1; - } - } + dol_syslog(get_class($this).'::select_ecotaxes', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + print ''; + return 0; + } else { + dol_print_error($this->db); + return 1; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return list of revenue stamp for country - * - * @param string $selected Value of preselected revenue stamp - * @param string $htmlname Name of combo list - * @param string $country_code Country Code - * @return string HTML select list - */ - public function select_revenue_stamp($selected = '', $htmlname = 'revenuestamp', $country_code = '') - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return list of revenue stamp for country + * + * @param string $selected Value of preselected revenue stamp + * @param string $htmlname Name of combo list + * @param string $country_code Country Code + * @return string HTML select list + */ + public function select_revenue_stamp($selected = '', $htmlname = 'revenuestamp', $country_code = '') + { + // phpcs:enable + global $langs; - $out = ''; + $out = ''; - $sql = "SELECT r.taux, r.revenuestamp_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE r.active = 1 AND r.fk_pays = c.rowid"; - $sql .= " AND c.code = '".$this->db->escape($country_code)."'"; + $sql = "SELECT r.taux, r.revenuestamp_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r,".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE r.active = 1 AND r.fk_pays = c.rowid"; + $sql .= " AND c.code = '".$this->db->escape($country_code)."'"; - dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $out .= ''; - return $out; - } else { - dol_print_error($this->db); - return ''; - } - } + dol_syslog(get_class($this).'::select_revenue_stamp', LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) + { + $out .= ''; + return $out; + } else { + dol_print_error($this->db); + return ''; + } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return a HTML select list to select a percent - * - * @param integer $selected pourcentage pre-selectionne - * @param string $htmlname nom de la liste deroulante - * @param int $disabled Disabled or not - * @param int $increment increment value - * @param int $start start value - * @param int $end end value - * @param int $showempty Add also an empty line - * @return string HTML select string - */ - public function select_percent($selected = 0, $htmlname = 'percent', $disabled = 0, $increment = 5, $start = 0, $end = 100, $showempty = 0) - { - // phpcs:enable - $return = ''; + if ($showempty) $return .= ''; - for ($i = $start; $i <= $end; $i += $increment) - { - if ($selected != '' && (int) $selected == $i) - { - $return .= ''; - } + for ($i = $start; $i <= $end; $i += $increment) + { + if ($selected != '' && (int) $selected == $i) + { + $return .= ''; + } - $return .= ''; + $return .= ''; - return $return; - } + return $return; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return select list for categories (to use in form search selectors) - * - * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. - * @param integer $selected Preselected value - * @param string $htmlname Name of combo list - * @param int $nocateg Show also an entry "Not categorized" - * @param int $showempty Add also an empty line - * @param string $morecss More CSS - * @return string Html combo list code - * @see select_all_categories() - */ - public function select_categories($type, $selected = 0, $htmlname = 'search_categ', $nocateg = 0, $showempty = 1, $morecss = '') - { - // phpcs:enable - global $conf, $langs; - require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return select list for categories (to use in form search selectors) + * + * @param int $type Type of category ('customer', 'supplier', 'contact', 'product', 'member'). Old mode (0, 1, 2, ...) is deprecated. + * @param integer $selected Preselected value + * @param string $htmlname Name of combo list + * @param int $nocateg Show also an entry "Not categorized" + * @param int $showempty Add also an empty line + * @param string $morecss More CSS + * @return string Html combo list code + * @see select_all_categories() + */ + public function select_categories($type, $selected = 0, $htmlname = 'search_categ', $nocateg = 0, $showempty = 1, $morecss = '') + { + // phpcs:enable + global $conf, $langs; + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; - // For backward compatibility - if (is_numeric($type)) - { - dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); - } + // For backward compatibility + if (is_numeric($type)) + { + dol_syslog(__METHOD__.': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING); + } - // Load list of "categories" - $static_categs = new Categorie($this->db); - $tab_categs = $static_categs->get_full_arbo($type); + // Load list of "categories" + $static_categs = new Categorie($this->db); + $tab_categs = $static_categs->get_full_arbo($type); - $moreforfilter = ''; - // Enhance with select2 - if ($conf->use_javascript_ajax) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $comboenhancement = ajax_combobox('select_categ_'.$htmlname); - $moreforfilter .= $comboenhancement; - } + $moreforfilter = ''; + // Enhance with select2 + if ($conf->use_javascript_ajax) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $comboenhancement = ajax_combobox('select_categ_'.$htmlname); + $moreforfilter .= $comboenhancement; + } - // Print a select with each of them - $moreforfilter .= ''; + if ($showempty) $moreforfilter .= ''; // Should use -1 to say nothing - if (is_array($tab_categs)) - { - foreach ($tab_categs as $categ) - { - $moreforfilter .= ''; - } - $moreforfilter .= ''; + if (is_array($tab_categs)) + { + foreach ($tab_categs as $categ) + { + $moreforfilter .= ''; + } + $moreforfilter .= ''; - return $moreforfilter; - } + return $moreforfilter; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return select list for categories (to use in form search selectors) - * - * @param string $selected Preselected value - * @param string $htmlname Name of combo list (example: 'search_sale') - * @param User $user Object user - * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status - * @param int $showempty 1=show also an empty value - * @param string $morecss More CSS - * @param int $norepresentative Show also an entry "Not categorized" - * @return string Html combo list code - */ - public function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '', $norepresentative = 0) - { - // phpcs:enable - global $conf, $langs, $hookmanager; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return select list for categories (to use in form search selectors) + * + * @param string $selected Preselected value + * @param string $htmlname Name of combo list (example: 'search_sale') + * @param User $user Object user + * @param int $showstatus 0=show user status only if status is disabled, 1=always show user status into label, -1=never show user status + * @param int $showempty 1=show also an empty value + * @param string $morecss More CSS + * @param int $norepresentative Show also an entry "Not categorized" + * @return string Html combo list code + */ + public function select_salesrepresentatives($selected, $htmlname, $user, $showstatus = 0, $showempty = 1, $morecss = '', $norepresentative = 0) + { + // phpcs:enable + global $conf, $langs, $hookmanager; - $langs->load('users'); + $langs->load('users'); - $out = ''; - // Enhance with select2 - if ($conf->use_javascript_ajax) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $out = ''; + // Enhance with select2 + if ($conf->use_javascript_ajax) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $comboenhancement = ajax_combobox($htmlname); - if ($comboenhancement) - { - $out .= $comboenhancement; - } - } + $comboenhancement = ajax_combobox($htmlname); + if ($comboenhancement) + { + $out .= $comboenhancement; + } + } - $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectSalesRep', array(), $this, $action); + $reshook = $hookmanager->executeHooks('addSQLWhereFilterOnSelectSalesRep', array(), $this, $action); - // Select each sales and print them in a select input - $out .= ''; + if ($showempty) $out .= ''; - // Get list of users allowed to be viewed - $sql_usr = "SELECT u.rowid, u.lastname, u.firstname, u.statut, u.login"; - $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u"; + // Get list of users allowed to be viewed + $sql_usr = "SELECT u.rowid, u.lastname, u.firstname, u.statut, u.login"; + $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u"; - if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { - $sql_usr .= " WHERE u.entity IS NOT NULL"; // Show all users - } else { - $sql_usr .= " WHERE EXISTS (SELECT ug.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug WHERE u.rowid = ug.fk_user AND ug.entity IN (".getEntity('usergroup')."))"; - $sql_usr .= " OR u.entity = 0"; // Show always superadmin - } - } else { - $sql_usr .= " WHERE u.entity IN (".getEntity('user').")"; - } + if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { + $sql_usr .= " WHERE u.entity IS NOT NULL"; // Show all users + } else { + $sql_usr .= " WHERE EXISTS (SELECT ug.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug WHERE u.rowid = ug.fk_user AND ug.entity IN (".getEntity('usergroup')."))"; + $sql_usr .= " OR u.entity = 0"; // Show always superadmin + } + } else { + $sql_usr .= " WHERE u.entity IN (".getEntity('user').")"; + } - if (empty($user->rights->user->user->lire)) $sql_usr .= " AND u.rowid = ".$user->id; - if (!empty($user->socid)) $sql_usr .= " AND u.fk_soc = ".$user->socid; + if (empty($user->rights->user->user->lire)) $sql_usr .= " AND u.rowid = ".$user->id; + if (!empty($user->socid)) $sql_usr .= " AND u.fk_soc = ".$user->socid; - //Add hook to filter on user (for exemple on usergroup define in custom modules) - if (!empty($reshook)) $sql_usr .= $hookmanager->resArray[0]; + //Add hook to filter on user (for exemple on usergroup define in custom modules) + if (!empty($reshook)) $sql_usr .= $hookmanager->resArray[0]; - // Add existing sales representatives of thirdparty of external user - if (empty($user->rights->user->user->lire) && $user->socid) - { - $sql_usr .= " UNION "; - $sql_usr .= "SELECT u2.rowid, u2.lastname, u2.firstname, u2.statut, u2.login"; - $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + // Add existing sales representatives of thirdparty of external user + if (empty($user->rights->user->user->lire) && $user->socid) + { + $sql_usr .= " UNION "; + $sql_usr .= "SELECT u2.rowid, u2.lastname, u2.firstname, u2.statut, u2.login"; + $sql_usr .= " FROM ".MAIN_DB_PREFIX."user as u2, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) - { - if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { - $sql_usr .= " WHERE u2.entity IS NOT NULL"; // Show all users - } else { - $sql_usr .= " WHERE EXISTS (SELECT ug2.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug2 WHERE u2.rowid = ug2.fk_user AND ug2.entity IN (".getEntity('usergroup')."))"; - } - } else { - $sql_usr .= " WHERE u2.entity IN (".getEntity('user').")"; - } + if (!empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) + { + if (!empty($user->admin) && empty($user->entity) && $conf->entity == 1) { + $sql_usr .= " WHERE u2.entity IS NOT NULL"; // Show all users + } else { + $sql_usr .= " WHERE EXISTS (SELECT ug2.fk_user FROM ".MAIN_DB_PREFIX."usergroup_user as ug2 WHERE u2.rowid = ug2.fk_user AND ug2.entity IN (".getEntity('usergroup')."))"; + } + } else { + $sql_usr .= " WHERE u2.entity IN (".getEntity('user').")"; + } - $sql_usr .= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->socid; + $sql_usr .= " AND u2.rowid = sc.fk_user AND sc.fk_soc=".$user->socid; - //Add hook to filter on user (for exemple on usergroup define in custom modules) - if (!empty($reshook)) $sql_usr .= $hookmanager->resArray[1]; - } - $sql_usr .= " ORDER BY statut DESC, lastname ASC"; // Do not use 'ORDER BY u.statut' here, not compatible with the UNION. - //print $sql_usr;exit; + //Add hook to filter on user (for exemple on usergroup define in custom modules) + if (!empty($reshook)) $sql_usr .= $hookmanager->resArray[1]; + } + $sql_usr .= " ORDER BY statut DESC, lastname ASC"; // Do not use 'ORDER BY u.statut' here, not compatible with the UNION. + //print $sql_usr;exit; - $resql_usr = $this->db->query($sql_usr); - if ($resql_usr) - { - while ($obj_usr = $this->db->fetch_object($resql_usr)) - { - $out .= ''; - } - $this->db->free($resql_usr); - } else { - dol_print_error($this->db); - } + $out .= ''; + } + $this->db->free($resql_usr); + } else { + dol_print_error($this->db); + } - if ($norepresentative) - { - $langs->load("companies"); - $out .= ''; - } + if ($norepresentative) + { + $langs->load("companies"); + $out .= ''; + } - $out .= ''; + $out .= ''; - return $out; - } + return $out; + } - /** - * Return list of project and tasks - * - * @param int $selectedtask Pre-selected task - * @param int $projectid Project id - * @param string $htmlname Name of html select - * @param int $modeproject 1 to restrict on projects owned by user - * @param int $modetask 1 to restrict on tasks associated to user - * @param int $mode 0=Return list of tasks and their projects, 1=Return projects and tasks if exists - * @param int $useempty 0=Allow empty values - * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id + /** + * Return list of project and tasks + * + * @param int $selectedtask Pre-selected task + * @param int $projectid Project id + * @param string $htmlname Name of html select + * @param int $modeproject 1 to restrict on projects owned by user + * @param int $modetask 1 to restrict on tasks associated to user + * @param int $mode 0=Return list of tasks and their projects, 1=Return projects and tasks if exists + * @param int $useempty 0=Allow empty values + * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id * @param string $filteronprojstatus Filter on project status ('-1'=no filter, '0,1'=Draft+Validated status) - * @param string $morecss More css - * @return void - */ - public function selectProjectTasks($selectedtask = '', $projectid = 0, $htmlname = 'task_parent', $modeproject = 0, $modetask = 0, $mode = 0, $useempty = 0, $disablechildoftaskid = 0, $filteronprojstatus = '', $morecss = '') - { - global $user, $langs; + * @param string $morecss More css + * @return void + */ + public function selectProjectTasks($selectedtask = '', $projectid = 0, $htmlname = 'task_parent', $modeproject = 0, $modetask = 0, $mode = 0, $useempty = 0, $disablechildoftaskid = 0, $filteronprojstatus = '', $morecss = '') + { + global $user, $langs; - require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; + require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; - //print $modeproject.'-'.$modetask; - $task = new Task($this->db); - $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus); - if ($tasksarray) - { - print ''; + //print $modeproject.'-'.$modetask; + $task = new Task($this->db); + $tasksarray = $task->getTasksArray($modetask ? $user : 0, $modeproject ? $user : 0, $projectid, 0, $mode, '', $filteronprojstatus); + if ($tasksarray) + { + print ''; - print ajax_combobox($htmlname); - } else { - print '
'.$langs->trans("NoProject").'
'; - } - } + print ajax_combobox($htmlname); + } else { + print '
'.$langs->trans("NoProject").'
'; + } + } - /** - * Write lines of a project (all lines of a project if parent = 0) - * - * @param int $inc Cursor counter - * @param int $parent Id of parent task we want to see - * @param array $lines Array of task lines - * @param int $level Level - * @param int $selectedtask Id selected task - * @param int $selectedproject Id selected project - * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id - * @return void - */ - private function _pLineSelect(&$inc, $parent, $lines, $level = 0, $selectedtask = 0, $selectedproject = 0, $disablechildoftaskid = 0) - { - global $langs, $user, $conf; + /** + * Write lines of a project (all lines of a project if parent = 0) + * + * @param int $inc Cursor counter + * @param int $parent Id of parent task we want to see + * @param array $lines Array of task lines + * @param int $level Level + * @param int $selectedtask Id selected task + * @param int $selectedproject Id selected project + * @param int $disablechildoftaskid 1=Disable task that are child of the provided task id + * @return void + */ + private function _pLineSelect(&$inc, $parent, $lines, $level = 0, $selectedtask = 0, $selectedproject = 0, $disablechildoftaskid = 0) + { + global $langs, $user, $conf; - $lastprojectid = 0; + $lastprojectid = 0; - $numlines = count($lines); - for ($i = 0; $i < $numlines; $i++) { - if ($lines[$i]->fk_parent == $parent) { - //var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id); // $lines[$i]->id may be empty if project has no lines + $numlines = count($lines); + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_parent == $parent) { + //var_dump($selectedproject."--".$selectedtask."--".$lines[$i]->fk_project."_".$lines[$i]->id); // $lines[$i]->id may be empty if project has no lines - // Break on a new project - if ($parent == 0) // We are on a task at first level - { - if ($lines[$i]->fk_project != $lastprojectid) // Break found on project - { - if ($i > 0) print ''; - print '\n"; + // Break on a new project + if ($parent == 0) // We are on a task at first level + { + if ($lines[$i]->fk_project != $lastprojectid) // Break found on project + { + if ($i > 0) print ''; + print '\n"; - $lastprojectid = $lines[$i]->fk_project; - $inc++; - } - } + $lastprojectid = $lines[$i]->fk_project; + $inc++; + } + } - $newdisablechildoftaskid = $disablechildoftaskid; + $newdisablechildoftaskid = $disablechildoftaskid; - // Print task - if (isset($lines[$i]->id)) // We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0 - { - // Check if we must disable entry - $disabled = 0; - if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid))) - { - $disabled++; - if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too - } + // Print task + if (isset($lines[$i]->id)) // We use isset because $lines[$i]->id may be null if project has no task and are on root project (tasks may be caught by a left join). We enter here only if '0' or >0 + { + // Check if we must disable entry + $disabled = 0; + if ($disablechildoftaskid && (($lines[$i]->id == $disablechildoftaskid || $lines[$i]->fk_parent == $disablechildoftaskid))) + { + $disabled++; + if ($lines[$i]->fk_parent == $disablechildoftaskid) $newdisablechildoftaskid = $lines[$i]->id; // If task is child of a disabled parent, we will propagate id to disable next child too + } - print '\n"; - $inc++; - } + print '\n"; + $inc++; + } - $level++; - if ($lines[$i]->id) $this->_pLineSelect($inc, $lines[$i]->id, $lines, $level, $selectedtask, $selectedproject, $newdisablechildoftaskid); - $level--; - } - } - } + $level++; + if ($lines[$i]->id) $this->_pLineSelect($inc, $lines[$i]->id, $lines, $level, $selectedtask, $selectedproject, $newdisablechildoftaskid); + $level--; + } + } + } - /** - * Output a HTML thumb of color or a text if not defined. - * - * @param string $color String with hex (FFFFFF) or comma RGB ('255,255,255') - * @param string $textifnotdefined Text to show if color not defined - * @return string HTML code for color thumb - * @see selectColor() - */ - public static function showColor($color, $textifnotdefined = '') - { - $textcolor = 'FFF'; - include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - if (colorIsLight($color)) $textcolor = '000'; + /** + * Output a HTML thumb of color or a text if not defined. + * + * @param string $color String with hex (FFFFFF) or comma RGB ('255,255,255') + * @param string $textifnotdefined Text to show if color not defined + * @return string HTML code for color thumb + * @see selectColor() + */ + public static function showColor($color, $textifnotdefined = '') + { + $textcolor = 'FFF'; + include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; + if (colorIsLight($color)) $textcolor = '000'; - $color = colorArrayToHex(colorStringToArray($color, array()), ''); + $color = colorArrayToHex(colorStringToArray($color, array()), ''); if ($color) print ''; else print $textifnotdefined; - } + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Output a HTML code to select a color - * - * @param string $set_color Pre-selected color - * @param string $prefix Name of HTML field - * @param string $form_name Deprecated. Not used. - * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code - * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') - * @return void - * @deprecated Use instead selectColor - * @see selectColor() - */ - public function select_color($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '') - { - // phpcs:enable - print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors); - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Output a HTML code to select a color + * + * @param string $set_color Pre-selected color + * @param string $prefix Name of HTML field + * @param string $form_name Deprecated. Not used. + * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code + * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') + * @return void + * @deprecated Use instead selectColor + * @see selectColor() + */ + public function select_color($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '') + { + // phpcs:enable + print $this->selectColor($set_color, $prefix, $form_name, $showcolorbox, $arrayofcolors); + } - /** - * Output a HTML code to select a color. Field will return an hexa color like '334455'. - * - * @param string $set_color Pre-selected color - * @param string $prefix Name of HTML field - * @param string $form_name Deprecated. Not used. - * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code - * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') - * @param string $morecss Add css style into input field - * @return string - * @see showColor() - */ - public static function selectColor($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '', $morecss = '') - { - // Deprecation warning - if ($form_name) { - dol_syslog(__METHOD__.": form_name parameter is deprecated", LOG_WARNING); - } + /** + * Output a HTML code to select a color. Field will return an hexa color like '334455'. + * + * @param string $set_color Pre-selected color + * @param string $prefix Name of HTML field + * @param string $form_name Deprecated. Not used. + * @param int $showcolorbox 1=Show color code and color box, 0=Show only color code + * @param array $arrayofcolors Array of colors. Example: array('29527A','5229A3','A32929','7A367A','B1365F','0D7813') + * @param string $morecss Add css style into input field + * @return string + * @see showColor() + */ + public static function selectColor($set_color = '', $prefix = 'f_color', $form_name = '', $showcolorbox = 1, $arrayofcolors = '', $morecss = '') + { + // Deprecation warning + if ($form_name) { + dol_syslog(__METHOD__.": form_name parameter is deprecated", LOG_WARNING); + } - global $langs, $conf; + global $langs, $conf; - $out = ''; + $out = ''; - if (!is_array($arrayofcolors) || count($arrayofcolors) < 1) - { - $langs->load("other"); - if (empty($conf->dol_use_jmobile) && !empty($conf->use_javascript_ajax)) - { - $out .= ''; - $out .= ''; - $out .= ''; + $out .= ''; - } - $out .= ''; - } else // In most cases, this is not used. We used instead function with no specific list of colors - { - if (empty($conf->dol_use_jmobile) && !empty($conf->use_javascript_ajax)) - { - $out .= ''; - $out .= ''; - $out .= ''; + $out .= ''; - } - $out .= ''; - } + } + $out .= ''; + } - return $out; - } + return $out; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Creation d'un icone de couleur - * - * @param string $color Couleur de l'image - * @param string $module Nom du module - * @param string $name Nom de l'image - * @param int $x Largeur de l'image en pixels - * @param int $y Hauteur de l'image en pixels - * @return void - */ - public function CreateColorIcon($color, $module, $name, $x = '12', $y = '12') - { - // phpcs:enable - global $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Creation d'un icone de couleur + * + * @param string $color Couleur de l'image + * @param string $module Nom du module + * @param string $name Nom de l'image + * @param int $x Largeur de l'image en pixels + * @param int $y Hauteur de l'image en pixels + * @return void + */ + public function CreateColorIcon($color, $module, $name, $x = '12', $y = '12') + { + // phpcs:enable + global $conf; - $file = $conf->$module->dir_temp.'/'.$name.'.png'; + $file = $conf->$module->dir_temp.'/'.$name.'.png'; - // On cree le repertoire contenant les icones - if (!file_exists($conf->$module->dir_temp)) - { - dol_mkdir($conf->$module->dir_temp); - } + // On cree le repertoire contenant les icones + if (!file_exists($conf->$module->dir_temp)) + { + dol_mkdir($conf->$module->dir_temp); + } - // On cree l'image en vraies couleurs - $image = imagecreatetruecolor($x, $y); + // On cree l'image en vraies couleurs + $image = imagecreatetruecolor($x, $y); - $color = substr($color, 1, 6); + $color = substr($color, 1, 6); - $rouge = hexdec(substr($color, 0, 2)); //conversion du canal rouge - $vert = hexdec(substr($color, 2, 2)); //conversion du canal vert - $bleu = hexdec(substr($color, 4, 2)); //conversion du canal bleu + $rouge = hexdec(substr($color, 0, 2)); //conversion du canal rouge + $vert = hexdec(substr($color, 2, 2)); //conversion du canal vert + $bleu = hexdec(substr($color, 4, 2)); //conversion du canal bleu - $couleur = imagecolorallocate($image, $rouge, $vert, $bleu); - //print $rouge.$vert.$bleu; - imagefill($image, 0, 0, $couleur); //on remplit l'image - // On cree la couleur et on l'attribue a une variable pour ne pas la perdre - ImagePng($image, $file); //renvoie une image sous format png - ImageDestroy($image); - } + $couleur = imagecolorallocate($image, $rouge, $vert, $bleu); + //print $rouge.$vert.$bleu; + imagefill($image, 0, 0, $couleur); //on remplit l'image + // On cree la couleur et on l'attribue a une variable pour ne pas la perdre + ImagePng($image, $file); //renvoie une image sous format png + ImageDestroy($image); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML combo list of week - * - * @param string $selected Preselected value - * @param string $htmlname Nom de la zone select - * @param int $useempty Affiche valeur vide dans liste - * @return string - */ - public function select_dayofweek($selected = '', $htmlname = 'weekid', $useempty = 0) - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML combo list of week + * + * @param string $selected Preselected value + * @param string $htmlname Nom de la zone select + * @param int $useempty Affiche valeur vide dans liste + * @return string + */ + public function select_dayofweek($selected = '', $htmlname = 'weekid', $useempty = 0) + { + // phpcs:enable + global $langs; - $week = array( - 0=>$langs->trans("Day0"), - 1=>$langs->trans("Day1"), - 2=>$langs->trans("Day2"), - 3=>$langs->trans("Day3"), - 4=>$langs->trans("Day4"), - 5=>$langs->trans("Day5"), - 6=>$langs->trans("Day6") - ); + $week = array( + 0=>$langs->trans("Day0"), + 1=>$langs->trans("Day1"), + 2=>$langs->trans("Day2"), + 3=>$langs->trans("Day3"), + 4=>$langs->trans("Day4"), + 5=>$langs->trans("Day5"), + 6=>$langs->trans("Day6") + ); - $select_week = ''; - return $select_week; - } + $select_week = ''; + return $select_week; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML combo list of month - * - * @param string $selected Preselected value - * @param string $htmlname Name of HTML select object - * @param int $useempty Show empty in list - * @param int $longlabel Show long label - * @param string $morecss More Css - * @return string - */ - public function select_month($selected = '', $htmlname = 'monthid', $useempty = 0, $longlabel = 0, $morecss = 'maxwidth50imp valignmiddle') - { - // phpcs:enable - global $langs; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML combo list of month + * + * @param string $selected Preselected value + * @param string $htmlname Name of HTML select object + * @param int $useempty Show empty in list + * @param int $longlabel Show long label + * @param string $morecss More Css + * @return string + */ + public function select_month($selected = '', $htmlname = 'monthid', $useempty = 0, $longlabel = 0, $morecss = 'maxwidth50imp valignmiddle') + { + // phpcs:enable + global $langs; - require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; - if ($longlabel) $montharray = monthArray($langs, 0); // Get array - else $montharray = monthArray($langs, 1); + if ($longlabel) $montharray = monthArray($langs, 0); // Get array + else $montharray = monthArray($langs, 1); - $select_month = ''; - return $select_month; - } + $select_month = ''; + return $select_month; + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return HTML combo list of years - * - * @param string $selected Preselected value (''=current year, -1=none, year otherwise) - * @param string $htmlname Name of HTML select object - * @param int $useempty Affiche valeur vide dans liste - * @param int $min_year Offset of minimum year into list (by default current year -10) - * @param int $max_year Offset of maximum year into list (by default current year + 5) - * @param int $offset Offset - * @param int $invert Invert - * @param string $option Option - * @param string $morecss More CSS - * @return string - */ - public function select_year($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') - { - // phpcs:enable - print $this->selectyear($selected, $htmlname, $useempty, $min_year, $max_year, $offset, $invert, $option, $morecss); - } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return HTML combo list of years + * + * @param string $selected Preselected value (''=current year, -1=none, year otherwise) + * @param string $htmlname Name of HTML select object + * @param int $useempty Affiche valeur vide dans liste + * @param int $min_year Offset of minimum year into list (by default current year -10) + * @param int $max_year Offset of maximum year into list (by default current year + 5) + * @param int $offset Offset + * @param int $invert Invert + * @param string $option Option + * @param string $morecss More CSS + * @return string + */ + public function select_year($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') + { + // phpcs:enable + print $this->selectyear($selected, $htmlname, $useempty, $min_year, $max_year, $offset, $invert, $option, $morecss); + } - /** - * Return HTML combo list of years - * - * @param string $selected Preselected value (''=current year, -1=none, year otherwise) - * @param string $htmlname Name of HTML select object - * @param int $useempty Affiche valeur vide dans liste - * @param int $min_year Offset of minimum year into list (by default current year -10) - * @param int $max_year Offset of maximum year into list (by default current year + 5) - * @param int $offset Offset - * @param int $invert Invert - * @param string $option Option - * @param string $morecss More css - * @return string - */ - public function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') - { - $out = ''; + /** + * Return HTML combo list of years + * + * @param string $selected Preselected value (''=current year, -1=none, year otherwise) + * @param string $htmlname Name of HTML select object + * @param int $useempty Affiche valeur vide dans liste + * @param int $min_year Offset of minimum year into list (by default current year -10) + * @param int $max_year Offset of maximum year into list (by default current year + 5) + * @param int $offset Offset + * @param int $invert Invert + * @param string $option Option + * @param string $morecss More css + * @return string + */ + public function selectyear($selected = '', $htmlname = 'yearid', $useempty = 0, $min_year = 10, $max_year = 5, $offset = 0, $invert = 0, $option = '', $morecss = 'valignmiddle maxwidth75imp') + { + $out = ''; - $currentyear = date("Y") + $offset; - $max_year = $currentyear + $max_year; - $min_year = $currentyear - $min_year; - if (empty($selected) && empty($useempty)) $selected = $currentyear; + $currentyear = date("Y") + $offset; + $max_year = $currentyear + $max_year; + $min_year = $currentyear - $min_year; + if (empty($selected) && empty($useempty)) $selected = $currentyear; - $out .= '\n"; + $out .= '\n"; - return $out; - } + return $out; + } - /** - * Get array with HTML tabs with boxes of a particular area including personalized choices of user. - * Class 'Form' must be known. - * - * @param User $user Object User - * @param String $areacode Code of area for pages - 0 = Home page ... See getListOfPagesForBoxes() + /** + * Get array with HTML tabs with boxes of a particular area including personalized choices of user. + * Class 'Form' must be known. + * + * @param User $user Object User + * @param String $areacode Code of area for pages - 0 = Home page ... See getListOfPagesForBoxes() * @return array array('selectboxlist'=>, 'boxactivated'=>, 'boxlista'=>, 'boxlistb'=>) - */ - public static function getBoxesArea($user, $areacode) - { - global $conf, $langs, $db; + */ + public static function getBoxesArea($user, $areacode) + { + global $conf, $langs, $db; - include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; + include_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php'; - $confuserzone = 'MAIN_BOXES_'.$areacode; + $confuserzone = 'MAIN_BOXES_'.$areacode; - // $boxactivated will be array of boxes enabled into global setup - // $boxidactivatedforuser will be array of boxes choosed by user + // $boxactivated will be array of boxes enabled into global setup + // $boxidactivatedforuser will be array of boxes choosed by user - $selectboxlist = ''; - $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup) + $selectboxlist = ''; + $boxactivated = InfoBox::listBoxes($db, 'activated', $areacode, (empty($user->conf->$confuserzone) ?null:$user), array(), 0); // Search boxes of common+user (or common only if user has no specific setup) - $boxidactivatedforuser = array(); - foreach ($boxactivated as $box) - { - if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user - } + $boxidactivatedforuser = array(); + foreach ($boxactivated as $box) + { + if (empty($user->conf->$confuserzone) || $box->fk_user == $user->id) $boxidactivatedforuser[$box->id] = $box->id; // We keep only boxes to show for user + } - // Define selectboxlist - $arrayboxtoactivatelabel = array(); - if (!empty($user->conf->$confuserzone)) - { - $boxorder = ''; - $langs->load("boxes"); // Load label of boxes - foreach ($boxactivated as $box) - { - if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user - $label = $langs->transnoentitiesnoconv($box->boxlabel); - //if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')'; - if (preg_match('/graph/', $box->class) && $conf->browser->layout != 'phone') - { - $label = $label.' '; - } - $arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list - } - foreach ($boxidactivatedforuser as $boxid) - { - if (empty($boxorder)) $boxorder .= 'A:'; + // Define selectboxlist + $arrayboxtoactivatelabel = array(); + if (!empty($user->conf->$confuserzone)) + { + $boxorder = ''; + $langs->load("boxes"); // Load label of boxes + foreach ($boxactivated as $box) + { + if (!empty($boxidactivatedforuser[$box->id])) continue; // Already visible for user + $label = $langs->transnoentitiesnoconv($box->boxlabel); + //if (preg_match('/graph/',$box->class)) $label.=' ('.$langs->trans("Graph").')'; + if (preg_match('/graph/', $box->class) && $conf->browser->layout != 'phone') + { + $label = $label.' '; + } + $arrayboxtoactivatelabel[$box->id] = $label; // We keep only boxes not shown for user, to show into combo list + } + foreach ($boxidactivatedforuser as $boxid) + { + if (empty($boxorder)) $boxorder .= 'A:'; $boxorder .= $boxid.','; - } + } - //var_dump($boxidactivatedforuser); + //var_dump($boxidactivatedforuser); - // Class Form must have been already loaded - $selectboxlist .= ''."\n"; + // Class Form must have been already loaded + $selectboxlist .= ''."\n"; $selectboxlist .= '
'; $selectboxlist .= ''; $selectboxlist .= ''; @@ -1054,19 +1054,19 @@ class FormOther $selectboxlist .= ''; $selectboxlist .= ''; $selectboxlist .= Form::selectarray('boxcombo', $arrayboxtoactivatelabel, -1, $langs->trans("ChooseBoxToAdd").'...', 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth150onsmartphone', 0, 'hidden selected', 0, 1); - if (empty($conf->use_javascript_ajax)) $selectboxlist .= ' '; - $selectboxlist .= '
'; - if (!empty($conf->use_javascript_ajax)) - { - include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; - $selectboxlist .= ajax_combobox("boxcombo"); - } - } + if (empty($conf->use_javascript_ajax)) $selectboxlist .= ' '; + $selectboxlist .= ''; + if (!empty($conf->use_javascript_ajax)) + { + include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; + $selectboxlist .= ajax_combobox("boxcombo"); + } + } - // Javascript code for dynamic actions - if (!empty($conf->use_javascript_ajax)) - { - $selectboxlist .= ''."\n"; - } + $selectboxlist .= ''."\n"; + } - // Define boxlista and boxlistb - $nbboxactivated = count($boxidactivatedforuser); + // Define boxlista and boxlistb + $nbboxactivated = count($boxidactivatedforuser); - if ($nbboxactivated) - { - // Load translation files required by the page - $langs->loadLangs(array("boxes", "projects")); + if ($nbboxactivated) + { + // Load translation files required by the page + $langs->loadLangs(array("boxes", "projects")); - $emptybox = new ModeleBoxes($db); + $emptybox = new ModeleBoxes($db); - $boxlista .= "\n\n"; + $boxlista .= "\n\n"; - // Define $box_max_lines - $box_max_lines = 5; - if (!empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines = $conf->global->MAIN_BOXES_MAXLINES; + // Define $box_max_lines + $box_max_lines = 5; + if (!empty($conf->global->MAIN_BOXES_MAXLINES)) $box_max_lines = $conf->global->MAIN_BOXES_MAXLINES; - $ii = 0; - foreach ($boxactivated as $key => $box) - { - if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; + $ii = 0; + foreach ($boxactivated as $key => $box) + { + if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'A'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 - if (preg_match('/^A/i', $box->box_order)) // column A - { - $ii++; - //print 'box_id '.$boxactivated[$ii]->box_id.' '; - //print 'box_order '.$boxactivated[$ii]->box_order.'
'; - // Show box - $box->loadBox($box_max_lines); - $boxlista .= $box->showBox(null, null, 1); - } - } + if (preg_match('/^A/i', $box->box_order)) // column A + { + $ii++; + //print 'box_id '.$boxactivated[$ii]->box_id.' '; + //print 'box_order '.$boxactivated[$ii]->box_order.'
'; + // Show box + $box->loadBox($box_max_lines); + $boxlista .= $box->showBox(null, null, 1); + } + } - if ($conf->browser->layout != 'phone') - { - $emptybox->box_id = 'A'; - $emptybox->info_box_head = array(); - $emptybox->info_box_contents = array(); - $boxlista .= $emptybox->showBox(array(), array(), 1); - } - $boxlista .= "\n"; + if ($conf->browser->layout != 'phone') + { + $emptybox->box_id = 'A'; + $emptybox->info_box_head = array(); + $emptybox->info_box_contents = array(); + $boxlista .= $emptybox->showBox(array(), array(), 1); + } + $boxlista .= "\n"; - $boxlistb .= "\n\n"; + $boxlistb .= "\n\n"; - $ii = 0; - foreach ($boxactivated as $key => $box) - { - if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; - if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 - if (preg_match('/^B/i', $box->box_order)) // colonne B - { - $ii++; - //print 'box_id '.$boxactivated[$ii]->box_id.' '; - //print 'box_order '.$boxactivated[$ii]->box_order.'
'; - // Show box - $box->loadBox($box_max_lines); - $boxlistb .= $box->showBox(null, null, 1); - } - } + $ii = 0; + foreach ($boxactivated as $key => $box) + { + if ((!empty($user->conf->$confuserzone) && $box->fk_user == 0) || (empty($user->conf->$confuserzone) && $box->fk_user != 0)) continue; + if (empty($box->box_order) && $ii < ($nbboxactivated / 2)) $box->box_order = 'B'.sprintf("%02d", ($ii + 1)); // When box_order was not yet set to Axx or Bxx and is still 0 + if (preg_match('/^B/i', $box->box_order)) // colonne B + { + $ii++; + //print 'box_id '.$boxactivated[$ii]->box_id.' '; + //print 'box_order '.$boxactivated[$ii]->box_order.'
'; + // Show box + $box->loadBox($box_max_lines); + $boxlistb .= $box->showBox(null, null, 1); + } + } - if ($conf->browser->layout != 'phone') - { - $emptybox->box_id = 'B'; - $emptybox->info_box_head = array(); - $emptybox->info_box_contents = array(); - $boxlistb .= $emptybox->showBox(array(), array(), 1); - } + if ($conf->browser->layout != 'phone') + { + $emptybox->box_id = 'B'; + $emptybox->info_box_head = array(); + $emptybox->info_box_contents = array(); + $boxlistb .= $emptybox->showBox(array(), array(), 1); + } - $boxlistb .= "\n"; - } + $boxlistb .= "\n"; + } - return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb); - } + return array('selectboxlist'=>count($boxactivated) ? $selectboxlist : '', 'boxactivated'=>$boxactivated, 'boxlista'=>$boxlista, 'boxlistb'=>$boxlistb); + } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Return a HTML select list of a dictionary - * - * @param string $htmlname Name of select zone - * @param string $dictionarytable Dictionary table - * @param string $keyfield Field for key - * @param string $labelfield Label field - * @param string $selected Selected value - * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. - * @param string $moreattrib More attributes on HTML select tag - * @return void - */ - public function select_dictionary($htmlname, $dictionarytable, $keyfield = 'code', $labelfield = 'label', $selected = '', $useempty = 0, $moreattrib = '') - { - // phpcs:enable - global $langs, $conf; + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Return a HTML select list of a dictionary + * + * @param string $htmlname Name of select zone + * @param string $dictionarytable Dictionary table + * @param string $keyfield Field for key + * @param string $labelfield Label field + * @param string $selected Selected value + * @param int $useempty 1=Add an empty value in list, 2=Add an empty value in list only if there is more than 2 entries. + * @param string $moreattrib More attributes on HTML select tag + * @return void + */ + public function select_dictionary($htmlname, $dictionarytable, $keyfield = 'code', $labelfield = 'label', $selected = '', $useempty = 0, $moreattrib = '') + { + // phpcs:enable + global $langs, $conf; - $langs->load("admin"); + $langs->load("admin"); - $sql = "SELECT rowid, ".$keyfield.", ".$labelfield; - $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable; - $sql .= " ORDER BY ".$labelfield; + $sql = "SELECT rowid, ".$keyfield.", ".$labelfield; + $sql .= " FROM ".MAIN_DB_PREFIX.$dictionarytable; + $sql .= " ORDER BY ".$labelfield; - dol_syslog(get_class($this)."::select_dictionary", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $num = $this->db->num_rows($result); - $i = 0; - if ($num) - { - print ''; + if ($useempty == 1 || ($useempty == 2 && $num > 1)) + { + print ''; + } - while ($i < $num) - { - $obj = $this->db->fetch_object($result); - if ($selected == $obj->rowid || $selected == $obj->$keyfield) - { - print ''; - $i++; - } - print ""; - } else { - print $langs->trans("DictionaryEmpty"); - } - } else { - dol_print_error($this->db); - } - } + while ($i < $num) + { + $obj = $this->db->fetch_object($result); + if ($selected == $obj->rowid || $selected == $obj->$keyfield) + { + print ''; + $i++; + } + print ""; + } else { + print $langs->trans("DictionaryEmpty"); + } + } else { + dol_print_error($this->db); + } + } - /** + /** * Return an html string with a select combo box to choose yes or no * * @param string $htmlname Name of html select field @@ -1278,7 +1278,7 @@ class FormOther * @param int $useempty 1=Add empty line * @return string See option */ - public function selectAutoManual($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0) + public function selectAutoManual($htmlname, $value = '', $option = 0, $disabled = false, $useempty = 0) { global $langs; diff --git a/htdocs/core/lib/ecm.lib.php b/htdocs/core/lib/ecm.lib.php index 3b0cef1a809..1f22e464358 100644 --- a/htdocs/core/lib/ecm.lib.php +++ b/htdocs/core/lib/ecm.lib.php @@ -146,30 +146,30 @@ function ecm_prepare_head_fm($object) */ function ecm_admin_prepare_head() { - global $langs, $conf; - $langs->load("ecm"); + global $langs, $conf; + $langs->load("ecm"); - $h = 0; - $head = array(); + $h = 0; + $head = array(); - $head[$h][0] = DOL_URL_ROOT."/admin/ecm.php"; - $head[$h][1] = $langs->trans("Setup"); - $head[$h][2] = 'ecm'; - $h++; + $head[$h][0] = DOL_URL_ROOT."/admin/ecm.php"; + $head[$h][1] = $langs->trans("Setup"); + $head[$h][2] = 'ecm'; + $h++; - $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_files_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsEcmFiles"); - $head[$h][2] = 'attributes_ecm_files'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_files_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsEcmFiles"); + $head[$h][2] = 'attributes_ecm_files'; + $h++; - $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_directories_extrafields.php'; - $head[$h][1] = $langs->trans("ExtraFieldsEcmDirectories"); - $head[$h][2] = 'attributes_ecm_directories'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/admin/ecm_directories_extrafields.php'; + $head[$h][1] = $langs->trans("ExtraFieldsEcmDirectories"); + $head[$h][2] = 'attributes_ecm_directories'; + $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin'); - complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin', 'remove'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'ecm_admin', 'remove'); - return $head; + return $head; } diff --git a/htdocs/core/lib/files.lib.php b/htdocs/core/lib/files.lib.php index 7f2fd4ce70d..63047ed0e7b 100644 --- a/htdocs/core/lib/files.lib.php +++ b/htdocs/core/lib/files.lib.php @@ -1533,7 +1533,7 @@ function dol_add_file_process($upload_dir, $allowoverwrite = 0, $donotupdatesess $nbok = 0; for ($i = 0; $i < $nbfile; $i++) { - if (empty($TFile['name'][$i])) continue; // For example, when submitting a form with no file name + if (empty($TFile['name'][$i])) continue; // For example, when submitting a form with no file name // Define $destfull (path to file including filename) and $destfile (only filename) $destfull = $upload_dir."/".$TFile['name'][$i]; @@ -2053,7 +2053,7 @@ function dol_uncompress($inputfile, $outputdir) for ($i = 0; $i < $zip->numFiles; $i++) { if (preg_match('/\.\./', $zip->getNameIndex($i))) { dol_syslog("Warning: Try to unzip a file with a transversal path ".$zip->getNameIndex($i), LOG_WARNING); - continue; // Discard the file + continue; // Discard the file } $zip->extractTo($outputdir.'/', array($zip->getNameIndex($i))); } diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 53d1b5fe40b..38e9d972760 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -84,8 +84,8 @@ function getEntity($element, $shared = 1, $currentobject = null) // fix different element names (France to English) switch ($element) { - case 'contrat': $element = 'contract'; break; // "/contrat/class/contrat.class.php" - case 'order_supplier': $element = 'supplier_order'; break; // "/fourn/class/fournisseur.commande.class.php" + case 'contrat': $element = 'contract'; break; // "/contrat/class/contrat.class.php" + case 'order_supplier': $element = 'supplier_order'; break; // "/fourn/class/fournisseur.commande.class.php" } if (is_object($mc)) @@ -1404,7 +1404,7 @@ function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab $tabsname = $moretabssuffix; if (empty($tabsname)) { $tabsname = str_replace("@", "", $picto); } $out .= '
'; - $out .= ''.$langs->trans("More").'... ('.$nbintab.')'; // Do not use "reposition" class in the "More". + $out .= ''.$langs->trans("More").'... ('.$nbintab.')'; // Do not use "reposition" class in the "More". $out .= '
'; $out .= $outmore; $out .= '
'; @@ -1415,7 +1415,7 @@ function dol_get_fiche_head($links = array(), $active = '', $title = '', $notab $out .= "$('#moretabs".$tabsname."').mouseenter( function() { var x = this.offsetLeft, y = this.offsetTop; console.log('mouseenter ".$left." x='+x+' y='+y+' window.innerWidth='+window.innerWidth); - if ((window.innerWidth - x) < ".($widthofpopup+10).") { + if ((window.innerWidth - x) < ".($widthofpopup + 10).") { $('#moretabsList".$tabsname."').css('".$right."','8px'); } $('#moretabsList".$tabsname."').css('".$left."','auto'); @@ -2808,7 +2808,7 @@ function getUserRemoteIP() $ip = $_SERVER['HTTP_CLIENT_IP']; // value is clean here } } else { - $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here + $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; // value is clean here } return $ip; } @@ -4048,7 +4048,7 @@ function dol_print_error($db = '', $error = '', $errors = null) } // Return a http error code if possible - if (! headers_sent()) { + if (!headers_sent()) { http_response_code(500); } @@ -7833,7 +7833,7 @@ function natural_search($fields, $value, $mode = 0, $nofirstand = 0) $numnewcrit = price2num($newcrit); if (is_numeric($numnewcrit)) { - $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric + $newres .= ($i2 > 0 ? ' OR ' : '').$field.' '.$operator.' '.$db->sanitize($numnewcrit); // should be a numeric } else { $newres .= ($i2 > 0 ? ' OR ' : '').'1 = 2'; // force false } @@ -7841,7 +7841,7 @@ function natural_search($fields, $value, $mode = 0, $nofirstand = 0) } } elseif ($mode == 2 || $mode == -2) { - $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer + $crit = preg_replace('/[^0-9,]/', '', $crit); // ID are always integer $newres .= ($i2 > 0 ? ' OR ' : '').$field." ".($mode == -2 ? 'NOT ' : ''); $newres .= $crit ? "IN (".$db->sanitize($db->escape($crit)).")" : "IN (0)"; if ($mode == -2) $newres .= ' OR '.$field.' IS NULL'; @@ -8979,8 +8979,8 @@ function readfileLowMemory($fullpath_original_file_osencoded, $method = -1) if ($method == -1) { $method = 0; - if (! empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1; - if (! empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2; + if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_FREAD)) $method = 1; + if (!empty($conf->global->MAIN_FORCE_READFILE_WITH_STREAM_COPY)) $method = 2; } // Be sure we don't have output buffering enabled to have readfile working correctly diff --git a/htdocs/core/lib/payments.lib.php b/htdocs/core/lib/payments.lib.php index 4fb593e354d..601dad3275d 100644 --- a/htdocs/core/lib/payments.lib.php +++ b/htdocs/core/lib/payments.lib.php @@ -29,30 +29,30 @@ function payment_prepare_head(Paiement $object) { - global $langs, $conf; + global $langs, $conf; - $h = 0; - $head = array(); + $h = 0; + $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$object->id; - $head[$h][1] = $langs->trans("Payment"); - $head[$h][2] = 'payment'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$object->id; + $head[$h][1] = $langs->trans("Payment"); + $head[$h][2] = 'payment'; + $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, 'payment'); + // 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, 'payment'); - $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/info.php?id='.$object->id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/compta/paiement/info.php?id='.$object->id; + $head[$h][1] = $langs->trans("Info"); + $head[$h][2] = 'info'; + $h++; - complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment', 'remove'); + complete_head_from_modules($conf, $langs, $object, $head, $h, 'payment', 'remove'); - return $head; + return $head; } /** @@ -64,30 +64,30 @@ function payment_prepare_head(Paiement $object) */ function bankline_prepare_head($id) { - global $langs, $conf; + global $langs, $conf; - $h = 0; - $head = array(); + $h = 0; + $head = array(); - $head[$h][0] = DOL_URL_ROOT.'/compta/bank/line.php?rowid='.$id; - $head[$h][1] = $langs->trans('BankTransaction'); - $head[$h][2] = 'bankline'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/compta/bank/line.php?rowid='.$id; + $head[$h][1] = $langs->trans('BankTransaction'); + $head[$h][2] = 'bankline'; + $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, null, $head, $h, 'bankline'); + // 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, null, $head, $h, 'bankline'); - $head[$h][0] = DOL_URL_ROOT.'/compta/bank/info.php?rowid='.$id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; + $head[$h][0] = DOL_URL_ROOT.'/compta/bank/info.php?rowid='.$id; + $head[$h][1] = $langs->trans("Info"); + $head[$h][2] = 'info'; + $h++; - complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline', 'remove'); + complete_head_from_modules($conf, $langs, null, $head, $h, 'bankline', 'remove'); - return $head; + return $head; } /** @@ -109,11 +109,11 @@ function payment_supplier_prepare_head(Paiement $object) $head[$h][2] = 'payment'; $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, 'payment_supplier'); + // 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, 'payment_supplier'); $head[$h][0] = DOL_URL_ROOT.'/fourn/paiement/info.php?id='.$object->id; $head[$h][1] = $langs->trans('Info'); @@ -170,7 +170,7 @@ function showOnlinePaymentUrl($type, $ref) global $langs; // Load translation files required by the page - $langs->loadLangs(array('payment', 'stripe')); + $langs->loadLangs(array('payment', 'stripe')); $servicename = $langs->transnoentitiesnoconv('Online'); @@ -194,7 +194,7 @@ function showOnlinePaymentUrl($type, $ref) */ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag = 'your_tag', $localorexternal = 0) { - global $conf, $dolibarr_main_url_root; + global $conf, $dolibarr_main_url_root; $ref = str_replace(' ', '', $ref); $out = ''; @@ -209,7 +209,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag if ($type == 'free') { - $out = $urltouse.'/public/payment/newpayment.php?amount='.($mode ? '' : '').$amount.($mode ? '' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?amount='.($mode ? '' : '').$amount.($mode ? '' : '').'&tag='.($mode ? '' : '').$freetag.($mode ? '' : ''); if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; @@ -218,7 +218,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag //if ($mode) $out.='&noidempotency=1'; } elseif ($type == 'order') { - $out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'order_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -234,7 +234,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag } } elseif ($type == 'invoice') { - $out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'invoice_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -250,7 +250,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag } } elseif ($type == 'contractline') { - $out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'contractline_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -266,7 +266,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag } } elseif ($type == 'member' || $type == 'membersubscription') { - $out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'member_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -283,7 +283,7 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag } if ($type == 'donation') { - $out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '' : ''); + $out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '' : ''); if ($mode == 1) $out .= 'donation_ref'; if ($mode == 0) $out .= urlencode($ref); $out .= ($mode ? '' : ''); @@ -319,82 +319,82 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag */ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0, $suffix = '', $object = null) { - global $conf; + global $conf; - // Juridical status - $line1 = ""; - if ($fromcompany->forme_juridique_code) - { - $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); - } - // Capital - if ($fromcompany->capital) - { - $line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency); - } - // Prof Id 1 - if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) - { - $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; - } - // Prof Id 2 - if ($fromcompany->idprof2) - { - $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2; - } + // Juridical status + $line1 = ""; + if ($fromcompany->forme_juridique_code) + { + $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); + } + // Capital + if ($fromcompany->capital) + { + $line1 .= ($line1 ? " - " : "").$langs->transnoentities("CapitalOf", $fromcompany->capital)." ".$langs->transnoentities("Currency".$conf->currency); + } + // Prof Id 1 + if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) + { + $field = $langs->transcountrynoentities("ProfId1", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; + } + // Prof Id 2 + if ($fromcompany->idprof2) + { + $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof2; + } - // Second line of company infos - $line2 = ""; - // Prof Id 3 - if ($fromcompany->idprof3) - { - $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; - } - // Prof Id 4 - if ($fromcompany->idprof4) - { - $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; - $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; - } - // IntraCommunautary VAT - if ($fromcompany->tva_intra != '') - { - $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; - } + // Second line of company infos + $line2 = ""; + // Prof Id 3 + if ($fromcompany->idprof3) + { + $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; + } + // Prof Id 4 + if ($fromcompany->idprof4) + { + $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); + if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; + } + // IntraCommunautary VAT + if ($fromcompany->tva_intra != '') + { + $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; + } - print '
'; + print '
'; - print '
'."\n"; - if ($addformmessage) - { - print ''; - print '
'; + print '
'."\n"; + if ($addformmessage) + { + print ''; + print '
'; - $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix; - if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); - elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM); + $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORM_'.$suffix; + if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); + elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORM)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORM); - // Add other message if VAT exists - if ($object->total_vat != 0 || $object->total_tva != 0) - { - $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix; - if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); - elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT); - } - } + // Add other message if VAT exists + if ($object->total_vat != 0 || $object->total_tva != 0) + { + $parammessageform = 'ONLINE_PAYMENT_MESSAGE_FORMIFVAT_'.$suffix; + if (!empty($conf->global->$parammessageform)) print $langs->transnoentities($conf->global->$parammessageform); + elseif (!empty($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT)) print $langs->transnoentities($conf->global->ONLINE_PAYMENT_MESSAGE_FORMIFVAT); + } + } - print '

'."\n"; - print $fromcompany->name.'
'; - print $line1; - if (strlen($line1.$line2) > 50) print '
'; - else print ' - '; - print $line2; - print '
'."\n"; + print '

'."\n"; + print $fromcompany->name.'
'; + print $line1; + if (strlen($line1.$line2) > 50) print '
'; + else print ' - '; + print $line2; + print '
'."\n"; } diff --git a/htdocs/core/lib/pdf.lib.php b/htdocs/core/lib/pdf.lib.php index 6232afe962e..db79efefc45 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -122,7 +122,7 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P') define('K_SMALL_RATIO', 2 / 3); define('K_THAI_TOPCHARS', true); define('K_TCPDF_CALLS_IN_HTML', true); - if (! empty($conf->global->TCPDF_THROW_ERRORS_INSTEAD_OF_DIE)) { + if (!empty($conf->global->TCPDF_THROW_ERRORS_INSTEAD_OF_DIE)) { define('K_TCPDF_THROW_EXCEPTION_ERROR', true); } else { define('K_TCPDF_THROW_EXCEPTION_ERROR', false); @@ -2140,11 +2140,11 @@ function pdf_getLinkedObjects($object, $outputlangs) if (empty($object->linkedObjects['commande']) && $object->element != 'commande') // There is not already a link to order and object is not the order, so we show also info with order { $elementobject->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); - if (! empty($elementobject->linkedObjectsIds['commande'])){ + if (!empty($elementobject->linkedObjectsIds['commande'])) { include_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $order = new Commande($db); $ret = $order->fetch(reset($elementobject->linkedObjectsIds['commande'])); - if ($ret < 1) { $order=null; } + if ($ret < 1) { $order = null; } } } if (!is_object($order)) diff --git a/htdocs/core/modules/modCommande.class.php b/htdocs/core/modules/modCommande.class.php index 95d8e35489f..0da6ac160b8 100644 --- a/htdocs/core/modules/modCommande.class.php +++ b/htdocs/core/modules/modCommande.class.php @@ -265,16 +265,16 @@ class modCommande extends DolibarrModules if (empty($user->rights->societe->client->voir)) $this->export_sql_end[$r] .= ' AND sc.fk_user = '.(empty($user) ? 0 : $user->id); // Imports //-------- - $r=0; + $r = 0; //Import Order Header $r++; - $this->import_code[$r] = 'commande_' . $r; + $this->import_code[$r] = 'commande_'.$r; $this->import_label[$r] = 'Sales Orders'; $this->import_icon[$r] = $this->picto; $this->import_entities_array[$r] = []; - $this->import_tables_array[$r] = ['c' => MAIN_DB_PREFIX . 'commande', 'extra' => MAIN_DB_PREFIX . 'commande_extrafields']; - $this->import_tables_creator_array[$r] = ['c' => 'fk_user_author']; // Fields to store import user id + $this->import_tables_array[$r] = ['c' => MAIN_DB_PREFIX.'commande', 'extra' => MAIN_DB_PREFIX.'commande_extrafields']; + $this->import_tables_creator_array[$r] = ['c' => 'fk_user_author']; // Fields to store import user id $this->import_fields_array[$r] = [ 'c.ref' => 'Document Ref*', 'c.ref_client' => 'RefCustomer', @@ -299,7 +299,7 @@ class modCommande extends DolibarrModules 'c.model_pdf' => 'Model' ]; - if (! empty($conf->multicurrency->enabled)) { + if (!empty($conf->multicurrency->enabled)) { $this->import_fields_array[$r]['c.multicurrency_code'] = 'Currency'; $this->import_fields_array[$r]['c.multicurrency_tx'] = 'CurrencyRate'; $this->import_fields_array[$r]['c.multicurrency_total_ht'] = 'MulticurrencyAmountHT'; @@ -309,23 +309,23 @@ class modCommande extends DolibarrModules // Add extra fields $import_extrafield_sample = []; - $sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'commande' AND entity IN (0, " . $conf->entity . ")"; + $sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'commande' AND entity IN (0, ".$conf->entity.")"; $resql = $this->db->query($sql); if ($resql) { while ($obj = $this->db->fetch_object($resql)) { - $fieldname = 'extra.' . $obj->name; + $fieldname = 'extra.'.$obj->name; $fieldlabel = ucfirst($obj->label); - $this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : ''); + $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : ''); $import_extrafield_sample[$fieldname] = $fieldlabel; } } // End add extra fields - $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'commande']; + $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'commande']; $this->import_regex_array[$r] = [ 'c.ref' => '(CPV\d{4}-\d{4}|CO\d{4}-\d{4}|PROV.{1,32}$)', - 'c.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency' + 'c.multicurrency_code' => 'code@'.MAIN_DB_PREFIX.'multicurrency' ]; $this->import_updatekeys_array[$r] = ['c.ref' => 'Ref']; @@ -359,7 +359,7 @@ class modCommande extends DolibarrModules $this->import_label[$r] = 'Order Details'; $this->import_icon[$r] = $this->picto; $this->import_entities_array[$r] = []; - $this->import_tables_array[$r] = ['cd' => MAIN_DB_PREFIX . 'commandedet', 'extra' => MAIN_DB_PREFIX . 'commandedet_extrafields']; + $this->import_tables_array[$r] = ['cd' => MAIN_DB_PREFIX.'commandedet', 'extra' => MAIN_DB_PREFIX.'commandedet_extrafields']; $this->import_fields_array[$r] = [ 'cd.fk_commande' => 'Document Ref*', 'cd.fk_parent_line' => 'PrParentLine', @@ -382,7 +382,7 @@ class modCommande extends DolibarrModules 'cd.rang' => 'LinePosition' ]; - if (! empty($conf->multicurrency->enabled)) { + if (!empty($conf->multicurrency->enabled)) { $this->import_fields_array[$r]['cd.multicurrency_code'] = 'Currency'; $this->import_fields_array[$r]['cd.multicurrency_subprice'] = 'CurrencyRate'; $this->import_fields_array[$r]['cd.multicurrency_total_ht'] = 'MulticurrencyAmountHT'; @@ -391,22 +391,22 @@ class modCommande extends DolibarrModules } // Add extra fields - $sql="SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'commandedet' AND entity IN (0, " . $conf->entity . ")"; + $sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'commandedet' AND entity IN (0, ".$conf->entity.")"; $resql = $this->db->query($sql); if ($resql) { while ($obj = $this->db->fetch_object($resql)) { - $fieldname = 'extra.' . $obj->name; + $fieldname = 'extra.'.$obj->name; $fieldlabel = ucfirst($obj->label); - $this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : ''); + $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : ''); } } // End add extra fields - $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'commandedet']; + $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'commandedet']; $this->import_regex_array[$r] = [ 'cd.product_type' => '[0|1]$', - 'cd.fk_product' => 'rowid@' . MAIN_DB_PREFIX . 'product', - 'cd.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency' + 'cd.fk_product' => 'rowid@'.MAIN_DB_PREFIX.'product', + 'cd.multicurrency_code' => 'code@'.MAIN_DB_PREFIX.'multicurrency' ]; $this->import_updatekeys_array[$r] = ['cd.fk_commande' => 'Sales Order Id', 'cd.fk_product' => 'Product Id']; $this->import_convertvalue_array[$r] = [ diff --git a/htdocs/core/modules/modFournisseur.class.php b/htdocs/core/modules/modFournisseur.class.php index 7d055082121..7f24cc035af 100644 --- a/htdocs/core/modules/modFournisseur.class.php +++ b/htdocs/core/modules/modFournisseur.class.php @@ -63,12 +63,12 @@ class modFournisseur extends DolibarrModules // Data directories to create when module is enabled $this->dirs = array( - "/fournisseur/temp", - "/fournisseur/commande", - "/fournisseur/commande/temp", - "/fournisseur/facture", - "/fournisseur/facture/temp" - ); + "/fournisseur/temp", + "/fournisseur/commande", + "/fournisseur/commande/temp", + "/fournisseur/facture", + "/fournisseur/facture/temp" + ); // Dependencies $this->depends = array("modSociete"); @@ -299,7 +299,7 @@ class modFournisseur extends DolibarrModules 'p.ref'=>'ProductRef', 'p.label'=>'ProductLabel', 'p.accountancy_code_buy'=>'ProductAccountancyBuyCode', 'project.rowid'=>'ProjectId', 'project.ref'=>'ProjectRef', 'project.title'=>'ProjectLabel' ); - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { $this->export_fields_array[$r]['f.multicurrency_code'] = 'Currency'; $this->export_fields_array[$r]['f.multicurrency_tx'] = 'CurrencyRate'; @@ -434,7 +434,7 @@ class modFournisseur extends DolibarrModules 'f.fk_statut'=>'InvoiceStatus', 'f.note_public'=>"InvoiceNote", 'p.rowid'=>'PaymentId', 'pf.amount'=>'AmountPayment', 'p.datep'=>'DatePayment', 'p.num_paiement'=>'PaymentNumber', 'p.fk_bank'=>'IdTransaction', 'project.rowid'=>'ProjectId', 'project.ref'=>'ProjectRef', 'project.title'=>'ProjectLabel' ); - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { $this->export_fields_array[$r]['f.multicurrency_code'] = 'Currency'; $this->export_fields_array[$r]['f.multicurrency_tx'] = 'CurrencyRate'; @@ -528,7 +528,7 @@ class modFournisseur extends DolibarrModules 'fd.total_tva'=>"LineTotalVAT", 'fd.product_type'=>'TypeOfLineServiceOrProduct', 'fd.ref'=>'RefSupplier', 'fd.fk_product'=>'ProductId', 'p.ref'=>'ProductRef', 'p.label'=>'ProductLabel', 'project.rowid'=>'ProjectId', 'project.ref'=>'ProjectRef', 'project.title'=>'ProjectLabel' ); - if (! empty($conf->multicurrency->enabled)) + if (!empty($conf->multicurrency->enabled)) { $this->export_fields_array[$r]['f.multicurrency_code'] = 'Currency'; $this->export_fields_array[$r]['f.multicurrency_tx'] = 'CurrencyRate'; @@ -654,15 +654,15 @@ class modFournisseur extends DolibarrModules //Import Supplier Invoice //-------- - $r=0; + $r = 0; $r++; - $this->import_code[$r] = $this->rights_class . '_' . $r; - $this->import_label[$r] = "Supplier Invoice"; // Translation key + $this->import_code[$r] = $this->rights_class.'_'.$r; + $this->import_label[$r] = "Supplier Invoice"; // Translation key $this->import_icon[$r] = $this->picto; - $this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon - $this->import_tables_array[$r] = ['f' => MAIN_DB_PREFIX . 'facture_fourn', 'extra' => MAIN_DB_PREFIX . 'facture_fourn_extrafields']; - $this->import_tables_creator_array[$r] = ['f' => 'fk_user_author']; // Fields to store import user id + $this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon + $this->import_tables_array[$r] = ['f' => MAIN_DB_PREFIX.'facture_fourn', 'extra' => MAIN_DB_PREFIX.'facture_fourn_extrafields']; + $this->import_tables_creator_array[$r] = ['f' => 'fk_user_author']; // Fields to store import user id $this->import_fields_array[$r] = [ 'f.ref' => 'InvoiceRef*', 'f.ref_supplier' => 'RefSupplier', @@ -697,19 +697,19 @@ class modFournisseur extends DolibarrModules } // Add extra fields $import_extrafield_sample = []; - $sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'facture_fourn' AND entity IN (0, " . $conf->entity . ")"; + $sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'facture_fourn' AND entity IN (0, ".$conf->entity.")"; $resql = $this->db->query($sql); if ($resql) { while ($obj = $this->db->fetch_object($resql)) { - $fieldname = 'extra.' . $obj->name; + $fieldname = 'extra.'.$obj->name; $fieldlabel = ucfirst($obj->label); - $this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : ''); + $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : ''); $import_extrafield_sample[$fieldname] = $fieldlabel; } } // End add extra fields - $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'facture_fourn']; - $this->import_regex_array[$r] = ['f.ref' => '(SI\d{4}-\d{4}|PROV.{1,32}$)', 'f.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency']; + $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'facture_fourn']; + $this->import_regex_array[$r] = ['f.ref' => '(SI\d{4}-\d{4}|PROV.{1,32}$)', 'f.multicurrency_code' => 'code@'.MAIN_DB_PREFIX.'multicurrency']; $import_sample = [ 'f.ref' => '(PROV001)', 'f.ref_supplier' => 'Supplier1', @@ -751,10 +751,10 @@ class modFournisseur extends DolibarrModules //Import Supplier Invoice Lines $r++; $this->import_code[$r] = $this->rights_class.'_'.$r; - $this->import_label[$r] = "Supplier Invoice Lines"; // Translation key + $this->import_label[$r] = "Supplier Invoice Lines"; // Translation key $this->import_icon[$r] = $this->picto; - $this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon - $this->import_tables_array[$r] = ['fd' => MAIN_DB_PREFIX . 'facture_fourn_det', 'extra' => MAIN_DB_PREFIX . 'facture_fourn_det_extrafields']; + $this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon + $this->import_tables_array[$r] = ['fd' => MAIN_DB_PREFIX.'facture_fourn_det', 'extra' => MAIN_DB_PREFIX.'facture_fourn_det_extrafields']; $this->import_fields_array[$r] = [ 'fd.fk_facture_fourn' => 'InvoiceRef*', 'fd.fk_parent_line' => 'FacParentLine', @@ -784,19 +784,19 @@ class modFournisseur extends DolibarrModules } // Add extra fields $import_extrafield_sample = []; - $sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'facture_fourn_det' AND entity IN (0, " . $conf->entity . ")"; + $sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'facture_fourn_det' AND entity IN (0, ".$conf->entity.")"; $resql = $this->db->query($sql); if ($resql) { while ($obj = $this->db->fetch_object($resql)) { - $fieldname = 'extra.' . $obj->name; + $fieldname = 'extra.'.$obj->name; $fieldlabel = ucfirst($obj->label); - $this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : ''); + $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : ''); $import_extrafield_sample[$fieldname] = $fieldlabel; } } // End add extra fields - $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'facture_fourn_det']; - $this->import_regex_array[$r] = ['fd.product_type' => '[0|1]$', 'fd.fk_product' => 'rowid@' . MAIN_DB_PREFIX . 'product', 'fd.multicurrency_code' => 'code@' . MAIN_DB_PREFIX . 'multicurrency']; + $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'facture_fourn_det']; + $this->import_regex_array[$r] = ['fd.product_type' => '[0|1]$', 'fd.fk_product' => 'rowid@'.MAIN_DB_PREFIX.'product', 'fd.multicurrency_code' => 'code@'.MAIN_DB_PREFIX.'multicurrency']; $import_sample = [ 'fd.fk_facture_fourn' => '(PROV001)', 'fd.fk_parent_line' => '', @@ -835,7 +835,7 @@ class modFournisseur extends DolibarrModules * The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database. * It also creates data directories * - * @param string $options Options when enabling module ('', 'noboxes') + * @param string $options Options when enabling module ('', 'noboxes') * @return int 1 if OK, 0 if KO */ public function init($options = '') diff --git a/htdocs/core/modules/modMrp.class.php b/htdocs/core/modules/modMrp.class.php index b7901e38fd7..012bb2d576a 100644 --- a/htdocs/core/modules/modMrp.class.php +++ b/htdocs/core/modules/modMrp.class.php @@ -33,155 +33,155 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; */ class modMrp extends DolibarrModules { - /** - * Constructor. Define names, constants, directories, boxes, permissions - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - global $langs, $conf; - $this->db = $db; + /** + * Constructor. Define names, constants, directories, boxes, permissions + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $langs, $conf; + $this->db = $db; - // Id for module (must be unique). - // Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id). - $this->numero = 660; - // Key text used to identify module (for permissions, menus, etc...) - $this->rights_class = 'mrp'; - // Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...' - // It is used to group modules by family in module setup page - $this->family = "products"; - // Module position in the family on 2 digits ('01', '10', '20', ...) - $this->module_position = '66'; - // Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this) - //$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily"))); - // Module label (no space allowed), used if translation string 'ModuleMrpName' not found (Mrp is name of module). - $this->name = preg_replace('/^mod/i', '', get_class($this)); - // Module description, used if translation string 'ModuleMrpDesc' not found (Mrp is name of module). - $this->description = "Module to Manage Manufacturing Orders (MO)"; - // Used only if file README.md and README-LL.md not found. - $this->descriptionlong = "Module to Manage Manufacturing Orders (MO)"; - // Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated' or a version string like 'x.y.z' - $this->version = 'dolibarr'; - // Url to the file with your last numberversion of this module - //$this->url_last_version = 'http://www.example.com/versionmodule.txt'; + // Id for module (must be unique). + // Use here a free id (See in Home -> System information -> Dolibarr for list of used modules id). + $this->numero = 660; + // Key text used to identify module (for permissions, menus, etc...) + $this->rights_class = 'mrp'; + // Family can be 'base' (core modules),'crm','financial','hr','projects','products','ecm','technic' (transverse modules),'interface' (link with external tools),'other','...' + // It is used to group modules by family in module setup page + $this->family = "products"; + // Module position in the family on 2 digits ('01', '10', '20', ...) + $this->module_position = '66'; + // Gives the possibility for the module, to provide his own family info and position of this family (Overwrite $this->family and $this->module_position. Avoid this) + //$this->familyinfo = array('myownfamily' => array('position' => '01', 'label' => $langs->trans("MyOwnFamily"))); + // Module label (no space allowed), used if translation string 'ModuleMrpName' not found (Mrp is name of module). + $this->name = preg_replace('/^mod/i', '', get_class($this)); + // Module description, used if translation string 'ModuleMrpDesc' not found (Mrp is name of module). + $this->description = "Module to Manage Manufacturing Orders (MO)"; + // Used only if file README.md and README-LL.md not found. + $this->descriptionlong = "Module to Manage Manufacturing Orders (MO)"; + // Possible values for version are: 'development', 'experimental', 'dolibarr', 'dolibarr_deprecated' or a version string like 'x.y.z' + $this->version = 'dolibarr'; + // Url to the file with your last numberversion of this module + //$this->url_last_version = 'http://www.example.com/versionmodule.txt'; - // Key used in llx_const table to save module status enabled/disabled (where MRP is value of property name of module in uppercase) - $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); - // Name of image file used for this module. - // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' - // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' - $this->picto = 'mrp'; - // Define some features supported by module (triggers, login, substitutions, menus, css, etc...) - $this->module_parts = array( - // Set this to 1 if module has its own trigger directory (core/triggers) - 'triggers' => 0, - // Set this to 1 if module has its own login method file (core/login) - 'login' => 0, - // Set this to 1 if module has its own substitution function file (core/substitutions) - 'substitutions' => 0, - // Set this to 1 if module has its own menus handler directory (core/menus) - 'menus' => 0, - // Set this to 1 if module overwrite template dir (core/tpl) - 'tpl' => 0, - // Set this to 1 if module has its own barcode directory (core/modules/barcode) - 'barcode' => 0, - // Set this to 1 if module has its own models directory (core/modules/xxx) - 'models' => 0, - // Set this to 1 if module has its own theme directory (theme) - 'theme' => 0, - // Set this to relative path of css file if module has its own css file - 'css' => array( - // '/mrp/css/mrp.css.php', - ), - // Set this to relative path of js file if module must load a js on all pages - 'js' => array( - // '/mrp/js/mrp.js.php', - ), - // Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context to 'all' - 'hooks' => array( - // 'data' => array( - // 'hookcontext1', - // 'hookcontext2', - // ), - // 'entity' => '0', - ), - // Set this to 1 if features of module are opened to external users - 'moduleforexternal' => 0, - ); - // Data directories to create when module is enabled. - // Example: this->dirs = array("/mrp/temp","/mrp/subdir"); - $this->dirs = array("/mrp/temp"); - // Config pages. Put here list of php page, stored into mrp/admin directory, to use to setup module. - $this->config_page_url = array("mrp.php"); - // Dependencies - // A condition to hide module - $this->hidden = false; - // List of module class names as string that must be enabled if this module is enabled. Example: array('always1'=>'modModuleToEnable1','always2'=>'modModuleToEnable2', 'FR1'=>'modModuleToEnableFR'...) - $this->depends = array('modBom'); - $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) - $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) - $this->langfiles = array("mrp"); - $this->phpmin = array(5, 5); // Minimum version of PHP required by module - $this->need_dolibarr_version = array(8, 0); // Minimum version of Dolibarr required by module - $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...) - $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...) - //$this->automatic_activation = array('FR'=>'MrpWasAutomaticallyActivatedBecauseOfYourCountryChoice'); - //$this->always_enabled = true; // If true, can't be disabled + // Key used in llx_const table to save module status enabled/disabled (where MRP is value of property name of module in uppercase) + $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); + // Name of image file used for this module. + // If file is in theme/yourtheme/img directory under name object_pictovalue.png, use this->picto='pictovalue' + // If file is in module/img directory under name object_pictovalue.png, use this->picto='pictovalue@module' + $this->picto = 'mrp'; + // Define some features supported by module (triggers, login, substitutions, menus, css, etc...) + $this->module_parts = array( + // Set this to 1 if module has its own trigger directory (core/triggers) + 'triggers' => 0, + // Set this to 1 if module has its own login method file (core/login) + 'login' => 0, + // Set this to 1 if module has its own substitution function file (core/substitutions) + 'substitutions' => 0, + // Set this to 1 if module has its own menus handler directory (core/menus) + 'menus' => 0, + // Set this to 1 if module overwrite template dir (core/tpl) + 'tpl' => 0, + // Set this to 1 if module has its own barcode directory (core/modules/barcode) + 'barcode' => 0, + // Set this to 1 if module has its own models directory (core/modules/xxx) + 'models' => 0, + // Set this to 1 if module has its own theme directory (theme) + 'theme' => 0, + // Set this to relative path of css file if module has its own css file + 'css' => array( + // '/mrp/css/mrp.css.php', + ), + // Set this to relative path of js file if module must load a js on all pages + 'js' => array( + // '/mrp/js/mrp.js.php', + ), + // Set here all hooks context managed by module. To find available hook context, make a "grep -r '>initHooks(' *" on source code. You can also set hook context to 'all' + 'hooks' => array( + // 'data' => array( + // 'hookcontext1', + // 'hookcontext2', + // ), + // 'entity' => '0', + ), + // Set this to 1 if features of module are opened to external users + 'moduleforexternal' => 0, + ); + // Data directories to create when module is enabled. + // Example: this->dirs = array("/mrp/temp","/mrp/subdir"); + $this->dirs = array("/mrp/temp"); + // Config pages. Put here list of php page, stored into mrp/admin directory, to use to setup module. + $this->config_page_url = array("mrp.php"); + // Dependencies + // A condition to hide module + $this->hidden = false; + // List of module class names as string that must be enabled if this module is enabled. Example: array('always1'=>'modModuleToEnable1','always2'=>'modModuleToEnable2', 'FR1'=>'modModuleToEnableFR'...) + $this->depends = array('modBom'); + $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...) + $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...) + $this->langfiles = array("mrp"); + $this->phpmin = array(5, 5); // Minimum version of PHP required by module + $this->need_dolibarr_version = array(8, 0); // Minimum version of Dolibarr required by module + $this->warnings_activation = array(); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...) + $this->warnings_activation_ext = array(); // Warning to show when we activate an external module. array('always'='text') or array('FR'='textfr','ES'='textes'...) + //$this->automatic_activation = array('FR'=>'MrpWasAutomaticallyActivatedBecauseOfYourCountryChoice'); + //$this->always_enabled = true; // If true, can't be disabled - // Constants - // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive) - // Example: $this->const=array(1 => array('MRP_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1), - // 2 => array('MRP_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1) - // ); - $this->const = array( - 1=>array('MRP_MO_ADDON_PDF', 'chaine', 'alpha', 'Name of PDF model of MO', 0), - 2=>array('MRP_MO_ADDON', 'chaine', 'mod_mo_standard', 'Name of numbering rules of MO', 0), - 3=>array('MRP_MO_ADDON_PDF_ODT_PATH', 'chaine', 'DOL_DATA_ROOT/doctemplates/mrps', '', 0) - ); + // Constants + // List of particular constants to add when module is enabled (key, 'chaine', value, desc, visible, 'current' or 'allentities', deleteonunactive) + // Example: $this->const=array(1 => array('MRP_MYNEWCONST1', 'chaine', 'myvalue', 'This is a constant to add', 1), + // 2 => array('MRP_MYNEWCONST2', 'chaine', 'myvalue', 'This is another constant to add', 0, 'current', 1) + // ); + $this->const = array( + 1=>array('MRP_MO_ADDON_PDF', 'chaine', 'alpha', 'Name of PDF model of MO', 0), + 2=>array('MRP_MO_ADDON', 'chaine', 'mod_mo_standard', 'Name of numbering rules of MO', 0), + 3=>array('MRP_MO_ADDON_PDF_ODT_PATH', 'chaine', 'DOL_DATA_ROOT/doctemplates/mrps', '', 0) + ); - // Some keys to add into the overwriting translation tables - /*$this->overwrite_translation = array( + // Some keys to add into the overwriting translation tables + /*$this->overwrite_translation = array( 'en_US:ParentCompany'=>'Parent company or reseller', 'fr_FR:ParentCompany'=>'Maison mère ou revendeur' )*/ - if (!isset($conf->mrp) || !isset($conf->mrp->enabled)) { - $conf->mrp = new stdClass(); - $conf->mrp->enabled = 0; - } + if (!isset($conf->mrp) || !isset($conf->mrp->enabled)) { + $conf->mrp = new stdClass(); + $conf->mrp->enabled = 0; + } - // Array to add new pages in new tabs - $this->tabs = array(); - // Example: - // $this->tabs[] = array('data'=>'objecttype:+tabname1:Title1:mylangfile@mrp:$user->rights->mrp->read:/mrp/mynewtab1.php?id=__ID__'); // To add a new tab identified by code tabname1 - // $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@mrp:$user->rights->othermodule->read:/mrp/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key. - // $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname - // - // Where objecttype can be - // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member) - // 'contact' to add a tab in contact view - // 'contract' to add a tab in contract view - // 'group' to add a tab in group view - // 'intervention' to add a tab in intervention view - // 'invoice' to add a tab in customer invoice view - // 'invoice_supplier' to add a tab in supplier invoice view - // 'member' to add a tab in fundation member view - // 'opensurveypoll' to add a tab in opensurvey poll view - // 'order' to add a tab in customer order view - // 'order_supplier' to add a tab in supplier order view - // 'payment' to add a tab in payment view - // 'payment_supplier' to add a tab in supplier payment view - // 'product' to add a tab in product view - // 'propal' to add a tab in propal view - // 'project' to add a tab in project view - // 'stock' to add a tab in stock view - // 'thirdparty' to add a tab in third party view - // 'user' to add a tab in user view + // Array to add new pages in new tabs + $this->tabs = array(); + // Example: + // $this->tabs[] = array('data'=>'objecttype:+tabname1:Title1:mylangfile@mrp:$user->rights->mrp->read:/mrp/mynewtab1.php?id=__ID__'); // To add a new tab identified by code tabname1 + // $this->tabs[] = array('data'=>'objecttype:+tabname2:SUBSTITUTION_Title2:mylangfile@mrp:$user->rights->othermodule->read:/mrp/mynewtab2.php?id=__ID__', // To add another new tab identified by code tabname2. Label will be result of calling all substitution functions on 'Title2' key. + // $this->tabs[] = array('data'=>'objecttype:-tabname:NU:conditiontoremove'); // To remove an existing tab identified by code tabname + // + // Where objecttype can be + // 'categories_x' to add a tab in category view (replace 'x' by type of category (0=product, 1=supplier, 2=customer, 3=member) + // 'contact' to add a tab in contact view + // 'contract' to add a tab in contract view + // 'group' to add a tab in group view + // 'intervention' to add a tab in intervention view + // 'invoice' to add a tab in customer invoice view + // 'invoice_supplier' to add a tab in supplier invoice view + // 'member' to add a tab in fundation member view + // 'opensurveypoll' to add a tab in opensurvey poll view + // 'order' to add a tab in customer order view + // 'order_supplier' to add a tab in supplier order view + // 'payment' to add a tab in payment view + // 'payment_supplier' to add a tab in supplier payment view + // 'product' to add a tab in product view + // 'propal' to add a tab in propal view + // 'project' to add a tab in project view + // 'stock' to add a tab in stock view + // 'thirdparty' to add a tab in third party view + // 'user' to add a tab in user view - // Dictionaries - $this->dictionaries = array(); - /* Example: + // Dictionaries + $this->dictionaries = array(); + /* Example: $this->dictionaries=array( 'langs'=>'mylangfile@mrp', // List of tables we want to see into dictonnary editor @@ -205,68 +205,68 @@ class modMrp extends DolibarrModules ); */ - // Boxes/Widgets - // Add here list of php file(s) stored in mrp/core/boxes that contains a class to show a widget. - $this->boxes = array( - 0 => array('file' => 'box_mos.php', 'note' => '', 'enabledbydefaulton' => 'Home') - ); + // Boxes/Widgets + // Add here list of php file(s) stored in mrp/core/boxes that contains a class to show a widget. + $this->boxes = array( + 0 => array('file' => 'box_mos.php', 'note' => '', 'enabledbydefaulton' => 'Home') + ); - // Cronjobs (List of cron jobs entries to add when module is enabled) - // unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week - $this->cronjobs = array( - // 0 => array( - // 'label' => 'MyJob label', - // 'jobtype' => 'method', - // 'class' => '/mrp/class/mo.class.php', - // 'objectname' => 'Mo', - // 'method' => 'doScheduledJob', - // 'parameters' => '', - // 'comment' => 'Comment', - // 'frequency' => 2, - // 'unitfrequency' => 3600, - // 'status' => 0, - // 'test' => '$conf->mrp->enabled', - // 'priority' => 50, - // ), - ); - // Example: $this->cronjobs=array( - // 0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'$conf->mrp->enabled', 'priority'=>50), - // 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'$conf->mrp->enabled', 'priority'=>50) - // ); + // Cronjobs (List of cron jobs entries to add when module is enabled) + // unit_frequency must be 60 for minute, 3600 for hour, 86400 for day, 604800 for week + $this->cronjobs = array( + // 0 => array( + // 'label' => 'MyJob label', + // 'jobtype' => 'method', + // 'class' => '/mrp/class/mo.class.php', + // 'objectname' => 'Mo', + // 'method' => 'doScheduledJob', + // 'parameters' => '', + // 'comment' => 'Comment', + // 'frequency' => 2, + // 'unitfrequency' => 3600, + // 'status' => 0, + // 'test' => '$conf->mrp->enabled', + // 'priority' => 50, + // ), + ); + // Example: $this->cronjobs=array( + // 0=>array('label'=>'My label', 'jobtype'=>'method', 'class'=>'/dir/class/file.class.php', 'objectname'=>'MyClass', 'method'=>'myMethod', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>2, 'unitfrequency'=>3600, 'status'=>0, 'test'=>'$conf->mrp->enabled', 'priority'=>50), + // 1=>array('label'=>'My label', 'jobtype'=>'command', 'command'=>'', 'parameters'=>'param1, param2', 'comment'=>'Comment', 'frequency'=>1, 'unitfrequency'=>3600*24, 'status'=>0, 'test'=>'$conf->mrp->enabled', 'priority'=>50) + // ); - // Permissions provided by this module - $this->rights = array(); - $r = 0; - // Add here entries to declare new permissions - /* BEGIN MODULEBUILDER PERMISSIONS */ - $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Read Manufacturing Order'; // Permission label - $this->rights[$r][4] = 'read'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) - $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) - $r++; - $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Create/Update Manufacturing Order'; // Permission label - $this->rights[$r][4] = 'write'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) - $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) - $r++; - $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) - $this->rights[$r][1] = 'Delete Manufacturing Order'; // Permission label - $this->rights[$r][4] = 'delete'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) - $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) - $r++; - /* END MODULEBUILDER PERMISSIONS */ + // Permissions provided by this module + $this->rights = array(); + $r = 0; + // Add here entries to declare new permissions + /* BEGIN MODULEBUILDER PERMISSIONS */ + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'Read Manufacturing Order'; // Permission label + $this->rights[$r][4] = 'read'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $r++; + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'Create/Update Manufacturing Order'; // Permission label + $this->rights[$r][4] = 'write'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $r++; + $this->rights[$r][0] = $this->numero + $r; // Permission id (must not be already used) + $this->rights[$r][1] = 'Delete Manufacturing Order'; // Permission label + $this->rights[$r][4] = 'delete'; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $this->rights[$r][5] = ''; // In php code, permission will be checked by test if ($user->rights->mrp->level1->level2) + $r++; + /* END MODULEBUILDER PERMISSIONS */ - // Main menu entries to add - $this->menu = array(); - $r = 0; - // Add here entries to declare new menus - /* BEGIN MODULEBUILDER TOPMENU */ + // Main menu entries to add + $this->menu = array(); + $r = 0; + // Add here entries to declare new menus + /* BEGIN MODULEBUILDER TOPMENU */ /* END MODULEBUILDER LEFTMENU MO */ - // Exports profiles provided by this module - $r = 1; - /* BEGIN MODULEBUILDER EXPORT MO */ - /* + // Exports profiles provided by this module + $r = 1; + /* BEGIN MODULEBUILDER EXPORT MO */ + /* $langs->load("mrp"); $this->export_code[$r]=$this->rights_class.'_'.$r; $this->export_label[$r]='MoLines'; // Translation key (used only if key ExportDataset_xxx_z not found) @@ -281,12 +281,12 @@ class modMrp extends DolibarrModules $this->export_sql_end[$r] .=' WHERE 1 = 1'; $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('mo').')'; $r++; */ - /* END MODULEBUILDER EXPORT MO */ + /* END MODULEBUILDER EXPORT MO */ - // Imports profiles provided by this module - $r = 1; - /* BEGIN MODULEBUILDER IMPORT MO */ - /* + // Imports profiles provided by this module + $r = 1; + /* BEGIN MODULEBUILDER IMPORT MO */ + /* $langs->load("mrp"); $this->export_code[$r]=$this->rights_class.'_'.$r; $this->export_label[$r]='MoLines'; // Translation key (used only if key ExportDataset_xxx_z not found) @@ -301,75 +301,75 @@ class modMrp extends DolibarrModules $this->export_sql_end[$r] .=' WHERE 1 = 1'; $this->export_sql_end[$r] .=' AND t.entity IN ('.getEntity('mo').')'; $r++; */ - /* END MODULEBUILDER IMPORT MO */ - } + /* END MODULEBUILDER IMPORT MO */ + } - /** - * Function called when module is enabled. - * The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database. - * It also creates data directories - * - * @param string $options Options when enabling module ('', 'noboxes') - * @return int 1 if OK, 0 if KO - */ - public function init($options = '') - { - global $conf, $langs; + /** + * Function called when module is enabled. + * The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database. + * It also creates data directories + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + public function init($options = '') + { + global $conf, $langs; - $result = $this->_load_tables('/mrp/sql/'); - if ($result < 0) return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default') + $result = $this->_load_tables('/mrp/sql/'); + if ($result < 0) return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default') - // Create extrafields during init - //include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; - //$extrafields = new ExtraFields($this->db); - //$result1=$extrafields->addExtraField('myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); - //$result2=$extrafields->addExtraField('myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); - //$result3=$extrafields->addExtraField('myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); - //$result4=$extrafields->addExtraField('myattr4', "New Attr 4 label", 'select', 1, 3, 'thirdparty', 0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1,'', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); - //$result5=$extrafields->addExtraField('myattr5', "New Attr 5 label", 'text', 1, 10, 'user', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); + // Create extrafields during init + //include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; + //$extrafields = new ExtraFields($this->db); + //$result1=$extrafields->addExtraField('myattr1', "New Attr 1 label", 'boolean', 1, 3, 'thirdparty', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); + //$result2=$extrafields->addExtraField('myattr2', "New Attr 2 label", 'varchar', 1, 10, 'project', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); + //$result3=$extrafields->addExtraField('myattr3', "New Attr 3 label", 'varchar', 1, 10, 'bank_account', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); + //$result4=$extrafields->addExtraField('myattr4', "New Attr 4 label", 'select', 1, 3, 'thirdparty', 0, 1, '', array('options'=>array('code1'=>'Val1','code2'=>'Val2','code3'=>'Val3')), 1,'', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); + //$result5=$extrafields->addExtraField('myattr5', "New Attr 5 label", 'text', 1, 10, 'user', 0, 0, '', '', 1, '', 0, 0, '', '', 'mrp', '$conf->mrp->enabled'); - // Permissions - $this->remove($options); + // Permissions + $this->remove($options); - $sql = array(); + $sql = array(); - // ODT template - $src = DOL_DOCUMENT_ROOT.'/install/doctemplates/mrps/template_mo.odt'; - $dirodt = DOL_DATA_ROOT.'/doctemplates/mrps'; - $dest = $dirodt.'/template_mo.odt'; + // ODT template + $src = DOL_DOCUMENT_ROOT.'/install/doctemplates/mrps/template_mo.odt'; + $dirodt = DOL_DATA_ROOT.'/doctemplates/mrps'; + $dest = $dirodt.'/template_mo.odt'; - if (file_exists($src) && !file_exists($dest)) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - dol_mkdir($dirodt); - $result = dol_copy($src, $dest, 0, 0); - if ($result < 0) - { - $langs->load("errors"); - $this->error = $langs->trans('ErrorFailToCopyFile', $src, $dest); - return 0; - } - } + if (file_exists($src) && !file_exists($dest)) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + dol_mkdir($dirodt); + $result = dol_copy($src, $dest, 0, 0); + if ($result < 0) + { + $langs->load("errors"); + $this->error = $langs->trans('ErrorFailToCopyFile', $src, $dest); + return 0; + } + } - $sql = array( - //"DELETE FROM ".MAIN_DB_PREFIX."document_model WHERE nom = '".$this->db->escape('standard')."' AND type = 'mo' AND entity = ".$conf->entity, - //"INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES('".$this->db->escape('standard')."', 'mo', ".$conf->entity.")" - ); + $sql = array( + //"DELETE FROM ".MAIN_DB_PREFIX."document_model WHERE nom = '".$this->db->escape('standard')."' AND type = 'mo' AND entity = ".$conf->entity, + //"INSERT INTO ".MAIN_DB_PREFIX."document_model (nom, type, entity) VALUES('".$this->db->escape('standard')."', 'mo', ".$conf->entity.")" + ); - return $this->_init($sql, $options); - } + return $this->_init($sql, $options); + } - /** - * Function called when module is disabled. - * Remove from database constants, boxes and permissions from Dolibarr database. - * Data directories are not deleted - * - * @param string $options Options when enabling module ('', 'noboxes') - * @return int 1 if OK, 0 if KO - */ - public function remove($options = '') - { - $sql = array(); - return $this->_remove($sql, $options); - } + /** + * Function called when module is disabled. + * Remove from database constants, boxes and permissions from Dolibarr database. + * Data directories are not deleted + * + * @param string $options Options when enabling module ('', 'noboxes') + * @return int 1 if OK, 0 if KO + */ + public function remove($options = '') + { + $sql = array(); + return $this->_remove($sql, $options); + } } diff --git a/htdocs/core/modules/modPropale.class.php b/htdocs/core/modules/modPropale.class.php index 4da02808251..5791998ff6a 100644 --- a/htdocs/core/modules/modPropale.class.php +++ b/htdocs/core/modules/modPropale.class.php @@ -262,11 +262,11 @@ class modPropale extends DolibarrModules $r++; $this->import_code[$r] = $this->rights_class.'_'.$r; - $this->import_label[$r] = 'Proposals'; // Translation key + $this->import_label[$r] = 'Proposals'; // Translation key $this->import_icon[$r] = $this->picto; - $this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon - $this->import_tables_array[$r] = ['c' => MAIN_DB_PREFIX . 'propal', 'extra' => MAIN_DB_PREFIX . 'propal_extrafields']; - $this->import_tables_creator_array[$r] = ['c'=>'fk_user_author']; // Fields to store import user id + $this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon + $this->import_tables_array[$r] = ['c' => MAIN_DB_PREFIX.'propal', 'extra' => MAIN_DB_PREFIX.'propal_extrafields']; + $this->import_tables_creator_array[$r] = ['c'=>'fk_user_author']; // Fields to store import user id $this->import_fields_array[$r] = [ 'c.ref' => 'Document Ref*', 'c.ref_client' => 'RefCustomer', @@ -282,7 +282,7 @@ class modPropale extends DolibarrModules 'c.date_livraison' => 'DeliveryDate', 'c.fk_user_valid' => 'ValidatedById' ]; - if (! empty($conf->multicurrency->enabled)) { + if (!empty($conf->multicurrency->enabled)) { $this->import_fields_array[$r]['c.multicurrency_code'] = 'Currency'; $this->import_fields_array[$r]['c.multicurrency_tx'] = 'CurrencyRate'; $this->import_fields_array[$r]['c.multicurrency_total_ht'] = 'MulticurrencyAmountHT'; @@ -291,18 +291,18 @@ class modPropale extends DolibarrModules } // Add extra fields $import_extrafield_sample = []; - $sql = "SELECT name, label, fieldrequired FROM " . MAIN_DB_PREFIX . "extrafields WHERE elementtype = 'propal' AND entity IN (0, " . $conf->entity . ")"; + $sql = "SELECT name, label, fieldrequired FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = 'propal' AND entity IN (0, ".$conf->entity.")"; $resql = $this->db->query($sql); if ($resql) { while ($obj = $this->db->fetch_object($resql)) { - $fieldname = 'extra.' . $obj->name; + $fieldname = 'extra.'.$obj->name; $fieldlabel = ucfirst($obj->label); - $this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : ''); + $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : ''); $import_extrafield_sample[$fieldname] = $fieldlabel; } } // End add extra fields - $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'propal']; + $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'propal']; $this->import_regex_array[$r] = ['c.ref' => '[^ ]']; $import_sample = [ 'c.ref' => 'PROV0077', @@ -339,12 +339,12 @@ class modPropale extends DolibarrModules //Import Proposal Lines $r++; $this->import_code[$r] = $this->rights_class.'line_'.$r; - $this->import_label[$r] = "ProposalLine"; // Translation key + $this->import_label[$r] = "ProposalLine"; // Translation key $this->import_icon[$r] = $this->picto; - $this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon + $this->import_entities_array[$r] = []; // We define here only fields that use another icon that the one defined into import_icon $this->import_tables_array[$r] = [ - 'cd' => MAIN_DB_PREFIX . 'propaldet', - 'extra' => MAIN_DB_PREFIX . 'propaldet_extrafields' + 'cd' => MAIN_DB_PREFIX.'propaldet', + 'extra' => MAIN_DB_PREFIX.'propaldet_extrafields' ]; $this->import_fields_array[$r] = [ 'cd.fk_propal' => 'Document Ref*', @@ -366,7 +366,7 @@ class modPropale extends DolibarrModules 'cd.date_end' => 'End Date', 'cd.buy_price_ht' => 'LineBuyPriceHT' ]; - if (! empty($conf->multicurrency->enabled)) { + if (!empty($conf->multicurrency->enabled)) { $this->import_fields_array[$r]['cd.multicurrency_code'] = 'Currency'; $this->import_fields_array[$r]['cd.multicurrency_subprice'] = 'CurrencyRate'; $this->import_fields_array[$r]['cd.multicurrency_total_ht'] = 'MulticurrencyAmountHT'; @@ -379,14 +379,14 @@ class modPropale extends DolibarrModules $resql = $this->db->query($sql); if ($resql) { while ($obj = $this->db->fetch_object($resql)) { - $fieldname = 'extra.' . $obj->name; + $fieldname = 'extra.'.$obj->name; $fieldlabel = ucfirst($obj->label); - $this->import_fields_array[$r][$fieldname] = $fieldlabel . ($obj->fieldrequired ? '*' : ''); + $this->import_fields_array[$r][$fieldname] = $fieldlabel.($obj->fieldrequired ? '*' : ''); $import_extrafield_sample[$fieldname] = $fieldlabel; } } // End add extra fields - $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-' . MAIN_DB_PREFIX . 'propaldet']; + $this->import_fieldshidden_array[$r] = ['extra.fk_object' => 'lastrowid-'.MAIN_DB_PREFIX.'propaldet']; $this->import_regex_array[$r] = ['cd.product_type' => '[0|1]$']; $import_sample = [ 'cd.fk_propal' => 'PROV(0001)', diff --git a/htdocs/core/modules/modWebServicesClient.class.php b/htdocs/core/modules/modWebServicesClient.class.php index 720a756a828..52a8889fbbb 100644 --- a/htdocs/core/modules/modWebServicesClient.class.php +++ b/htdocs/core/modules/modWebServicesClient.class.php @@ -30,54 +30,54 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php'; class modWebServicesClient extends DolibarrModules { - /** + /** * Constructor. Define names, constants, directories, boxes, permissions * * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - $this->numero = 2660; + */ + public function __construct($db) + { + $this->db = $db; + $this->numero = 2660; - $this->family = "interface"; - $this->module_position = '25'; - // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module) - $this->name = preg_replace('/^mod/i', '', get_class($this)); - $this->description = "Enable the web service client to call external supplier web services"; + $this->family = "interface"; + $this->module_position = '25'; + // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module) + $this->name = preg_replace('/^mod/i', '', get_class($this)); + $this->description = "Enable the web service client to call external supplier web services"; // Possible values for version are: 'development', 'experimental', 'dolibarr' or version - $this->version = 'experimental'; - // Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase) - $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); - // Name of image file used for this module. - $this->picto = 'technic'; + $this->version = 'experimental'; + // Key used in llx_const table to save module status enabled/disabled (where MYMODULE is value of property name of module in uppercase) + $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name); + // Name of image file used for this module. + $this->picto = 'technic'; - // Data directories to create when module is enabled - $this->dirs = array(); + // Data directories to create when module is enabled + $this->dirs = array(); - // Config pages - //$this->config_page_url = array(); + // Config pages + //$this->config_page_url = array(); - // Dependencies - $this->hidden = false; // A condition to hide module + // Dependencies + $this->hidden = false; // A condition to hide module $this->depends = array(); // List of module class names as string that must be enabled if this module is enabled $this->requiredby = array(); // List of module ids to disable if this one is disabled $this->conflictwith = array(); // List of module class names as string this module is in conflict with $this->phpmin = array(5, 4); // Minimum version of PHP required by module - $this->langfiles = array("other"); + $this->langfiles = array("other"); - // Constants - $this->const = array(); + // Constants + $this->const = array(); - // New pages on tabs - $this->tabs = array(); + // New pages on tabs + $this->tabs = array(); - // Boxes - $this->boxes = array(); + // Boxes + $this->boxes = array(); - // Permissions - $this->rights = array(); - $this->rights_class = 'syncsupplierwebservices'; - $r = 0; - } + // Permissions + $this->rights = array(); + $this->rights_class = 'syncsupplierwebservices'; + $r = 0; + } } diff --git a/htdocs/core/modules/printing/printgcp.modules.php b/htdocs/core/modules/printing/printgcp.modules.php index 0312aa061f8..e1f765110a8 100644 --- a/htdocs/core/modules/printing/printgcp.modules.php +++ b/htdocs/core/modules/printing/printgcp.modules.php @@ -35,478 +35,478 @@ use OAuth\OAuth2\Service\Google; */ class printing_printgcp extends PrintingDriver { - public $name = 'printgcp'; - public $desc = 'PrintGCPDesc'; + public $name = 'printgcp'; + public $desc = 'PrintGCPDesc'; - /** - * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png - */ - public $picto = 'printer'; - public $active = 'PRINTING_PRINTGCP'; - public $conf = array(); - public $google_id = ''; - public $google_secret = ''; + /** + * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png + */ + public $picto = 'printer'; + public $active = 'PRINTING_PRINTGCP'; + public $conf = array(); + public $google_id = ''; + public $google_secret = ''; - /** - * @var string Error code (or message) - */ - public $error = ''; + /** + * @var string Error code (or message) + */ + public $error = ''; - /** - * @var string[] Error codes (or messages) - */ - public $errors = array(); + /** + * @var string[] Error codes (or messages) + */ + public $errors = array(); - /** - * @var DoliDB Database handler. - */ - public $db; + /** + * @var DoliDB Database handler. + */ + public $db; - private $OAUTH_SERVICENAME_GOOGLE = 'Google'; + private $OAUTH_SERVICENAME_GOOGLE = 'Google'; - const LOGIN_URL = 'https://accounts.google.com/o/oauth2/token'; - const PRINTERS_SEARCH_URL = 'https://www.google.com/cloudprint/search'; - const PRINTERS_GET_JOBS = 'https://www.google.com/cloudprint/jobs'; - const PRINT_URL = 'https://www.google.com/cloudprint/submit'; + const LOGIN_URL = 'https://accounts.google.com/o/oauth2/token'; + const PRINTERS_SEARCH_URL = 'https://www.google.com/cloudprint/search'; + const PRINTERS_GET_JOBS = 'https://www.google.com/cloudprint/jobs'; + const PRINT_URL = 'https://www.google.com/cloudprint/submit'; - /** - * Constructor - * - * @param DoliDB $db Database handler - */ - public function __construct($db) - { - global $conf, $langs, $dolibarr_main_url_root; + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct($db) + { + global $conf, $langs, $dolibarr_main_url_root; - // Define $urlwithroot - $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); - $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file - //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current + // Define $urlwithroot + $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root)); + $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file + //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current - $this->db = $db; + $this->db = $db; - if (!$conf->oauth->enabled) { - $this->conf[] = array( - 'varname'=>'PRINTGCP_INFO', - 'info'=>$langs->transnoentitiesnoconv("WarningModuleNotActive", "OAuth"), - 'type'=>'info', - ); - } else { - $this->google_id = $conf->global->OAUTH_GOOGLE_ID; - $this->google_secret = $conf->global->OAUTH_GOOGLE_SECRET; - // Token storage - $storage = new DoliStorage($this->db, $this->conf); - //$storage->clearToken($this->OAUTH_SERVICENAME_GOOGLE); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - $urlwithroot.'/core/modules/oauth/google_oauthcallback.php' - ); - $access = ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? 'HasAccessToken' : 'NoAccessToken'); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - } - //var_dump($this->errors);exit; + if (!$conf->oauth->enabled) { + $this->conf[] = array( + 'varname'=>'PRINTGCP_INFO', + 'info'=>$langs->transnoentitiesnoconv("WarningModuleNotActive", "OAuth"), + 'type'=>'info', + ); + } else { + $this->google_id = $conf->global->OAUTH_GOOGLE_ID; + $this->google_secret = $conf->global->OAUTH_GOOGLE_SECRET; + // Token storage + $storage = new DoliStorage($this->db, $this->conf); + //$storage->clearToken($this->OAUTH_SERVICENAME_GOOGLE); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + $urlwithroot.'/core/modules/oauth/google_oauthcallback.php' + ); + $access = ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? 'HasAccessToken' : 'NoAccessToken'); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + } + //var_dump($this->errors);exit; - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if ($token_ok) { - $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); - } + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if ($token_ok) { + $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); + } - // Token expired so we refresh it - if ($token_ok && $expire) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - if ($this->google_id != '' && $this->google_secret != '') { - $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthConfigured', 'type'=>'info'); - $this->conf[] = array( - 'varname'=>'PRINTGCP_TOKEN_ACCESS', - 'info'=>$access, - 'type'=>'info', - 'renew'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), - 'delete'=>($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp') : '') - ); - if ($token_ok) { - $expiredat = ''; + // Token expired so we refresh it + if ($token_ok && $expire) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + if ($this->google_id != '' && $this->google_secret != '') { + $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthConfigured', 'type'=>'info'); + $this->conf[] = array( + 'varname'=>'PRINTGCP_TOKEN_ACCESS', + 'info'=>$access, + 'type'=>'info', + 'renew'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?state=userinfo_email,userinfo_profile,cloud_print&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), + 'delete'=>($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE) ? $urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp') : '') + ); + if ($token_ok) { + $expiredat = ''; - $refreshtoken = $token->getRefreshToken(); + $refreshtoken = $token->getRefreshToken(); - $endoflife = $token->getEndOfLife(); + $endoflife = $token->getEndOfLife(); - if ($endoflife == $token::EOL_NEVER_EXPIRES) - { - $expiredat = $langs->trans("Never"); - } elseif ($endoflife == $token::EOL_UNKNOWN) - { - $expiredat = $langs->trans("Unknown"); - } else { - $expiredat = dol_print_date($endoflife, "dayhour"); - } + if ($endoflife == $token::EOL_NEVER_EXPIRES) + { + $expiredat = $langs->trans("Never"); + } elseif ($endoflife == $token::EOL_UNKNOWN) + { + $expiredat = $langs->trans("Unknown"); + } else { + $expiredat = dol_print_date($endoflife, "dayhour"); + } - $this->conf[] = array('varname'=>'TOKEN_REFRESH', 'info'=>((!empty($refreshtoken)) ? 'Yes' : 'No'), 'type'=>'info'); - $this->conf[] = array('varname'=>'TOKEN_EXPIRED', 'info'=>($expire ? 'Yes' : 'No'), 'type'=>'info'); - $this->conf[] = array('varname'=>'TOKEN_EXPIRE_AT', 'info'=>($expiredat), 'type'=>'info'); - } - /* + $this->conf[] = array('varname'=>'TOKEN_REFRESH', 'info'=>((!empty($refreshtoken)) ? 'Yes' : 'No'), 'type'=>'info'); + $this->conf[] = array('varname'=>'TOKEN_EXPIRED', 'info'=>($expire ? 'Yes' : 'No'), 'type'=>'info'); + $this->conf[] = array('varname'=>'TOKEN_EXPIRE_AT', 'info'=>($expiredat), 'type'=>'info'); + } + /* if ($storage->hasAccessToken($this->OAUTH_SERVICENAME_GOOGLE)) { $this->conf[] = array('varname'=>'PRINTGCP_AUTHLINK', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'authlink'); $this->conf[] = array('varname'=>'DELETE_TOKEN', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?action=delete&token='.newToken().'&backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'delete'); } else { $this->conf[] = array('varname'=>'PRINTGCP_AUTHLINK', 'link'=>$urlwithroot.'/core/modules/oauth/google_oauthcallback.php?backtourl='.urlencode(DOL_URL_ROOT.'/printing/admin/printing.php?mode=setup&driver=printgcp'), 'type'=>'authlink'); }*/ - } else { - $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthNotConfigured', 'type'=>'info'); - } - } - // do not display submit button - $this->conf[] = array('enabled'=>0, 'type'=>'submit'); - } + } else { + $this->conf[] = array('varname'=>'PRINTGCP_INFO', 'info'=>'GoogleAuthNotConfigured', 'type'=>'info'); + } + } + // do not display submit button + $this->conf[] = array('enabled'=>0, 'type'=>'submit'); + } - /** - * Return list of available printers - * - * @return int 0 if OK, >0 if KO - */ - public function listAvailablePrinters() - { - global $conf, $langs; - $error = 0; - $langs->load('printing'); + /** + * Return list of available printers + * + * @return int 0 if OK, >0 if KO + */ + public function listAvailablePrinters() + { + global $conf, $langs; + $error = 0; + $langs->load('printing'); - $html = ''; - $html .= ''.$langs->trans('GCP_Name').''; - $html .= ''.$langs->trans('GCP_displayName').''; - $html .= ''.$langs->trans('GCP_Id').''; - $html .= ''.$langs->trans('GCP_OwnerName').''; - $html .= ''.$langs->trans('GCP_State').''; - $html .= ''.$langs->trans('GCP_connectionStatus').''; - $html .= ''.$langs->trans('GCP_Type').''; - $html .= ''.$langs->trans("Select").''; - $html .= ''."\n"; - $list = $this->getlistAvailablePrinters(); - //$html.= '
'.print_r($list,true).'
'; - foreach ($list['available'] as $printer_det) - { - $html .= ''; - $html .= ''.$printer_det['name'].''; - $html .= ''.$printer_det['displayName'].''; - $html .= ''.$printer_det['id'].''; // id to identify printer to use - $html .= ''.$printer_det['ownerName'].''; - $html .= ''.$printer_det['status'].''; - $html .= ''.$langs->trans('STATE_'.$printer_det['connectionStatus']).''; - $html .= ''.$langs->trans('TYPE_'.$printer_det['type']).''; - // Defaut - $html .= ''; - if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id']) - { - $html .= img_picto($langs->trans("Default"), 'on'); - } else $html .= ''.img_picto($langs->trans("Disabled"), 'off').''; - $html .= ''; - $html .= ''."\n"; - } - $this->resprint = $html; - return $error; - } + $html = ''; + $html .= ''.$langs->trans('GCP_Name').''; + $html .= ''.$langs->trans('GCP_displayName').''; + $html .= ''.$langs->trans('GCP_Id').''; + $html .= ''.$langs->trans('GCP_OwnerName').''; + $html .= ''.$langs->trans('GCP_State').''; + $html .= ''.$langs->trans('GCP_connectionStatus').''; + $html .= ''.$langs->trans('GCP_Type').''; + $html .= ''.$langs->trans("Select").''; + $html .= ''."\n"; + $list = $this->getlistAvailablePrinters(); + //$html.= '
'.print_r($list,true).'
'; + foreach ($list['available'] as $printer_det) + { + $html .= ''; + $html .= ''.$printer_det['name'].''; + $html .= ''.$printer_det['displayName'].''; + $html .= ''.$printer_det['id'].''; // id to identify printer to use + $html .= ''.$printer_det['ownerName'].''; + $html .= ''.$printer_det['status'].''; + $html .= ''.$langs->trans('STATE_'.$printer_det['connectionStatus']).''; + $html .= ''.$langs->trans('TYPE_'.$printer_det['type']).''; + // Defaut + $html .= ''; + if ($conf->global->PRINTING_GCP_DEFAULT == $printer_det['id']) + { + $html .= img_picto($langs->trans("Default"), 'on'); + } else $html .= ''.img_picto($langs->trans("Disabled"), 'off').''; + $html .= ''; + $html .= ''."\n"; + } + $this->resprint = $html; + return $error; + } - /** - * Return list of available printers - * - * @return array list of printers - */ - public function getlistAvailablePrinters() - { - $ret = array(); - // Token storage - $storage = new DoliStorage($this->db, $this->conf); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - // Check if we have auth token - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - } - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if ($token_ok) { - $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); - } + /** + * Return list of available printers + * + * @return array list of printers + */ + public function getlistAvailablePrinters() + { + $ret = array(); + // Token storage + $storage = new DoliStorage($this->db, $this->conf); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' + ); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + // Check if we have auth token + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + } + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if ($token_ok) { + $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); + } - // Token expired so we refresh it - if ($token_ok && $expire) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } - // Send a request with api - try { - $response = $apiService->request(self::PRINTERS_SEARCH_URL); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - print '
'.print_r($e->getMessage(), true).'
'; - } - //print '
'.print_r($response, true).'
'; - $responsedata = json_decode($response, true); - $printers = $responsedata['printers']; - // Check if we have printers? - if (count($printers) == 0) { - // We dont have printers so return blank array - $ret['available'] = array(); - } else { - // We have printers so returns printers as array - $ret['available'] = $printers; - } - return $ret; - } + // Token expired so we refresh it + if ($token_ok && $expire) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } + // Send a request with api + try { + $response = $apiService->request(self::PRINTERS_SEARCH_URL); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + print '
'.print_r($e->getMessage(), true).'
'; + } + //print '
'.print_r($response, true).'
'; + $responsedata = json_decode($response, true); + $printers = $responsedata['printers']; + // Check if we have printers? + if (count($printers) == 0) { + // We dont have printers so return blank array + $ret['available'] = array(); + } else { + // We have printers so returns printers as array + $ret['available'] = $printers; + } + return $ret; + } - /** - * Print selected file - * - * @param string $file file - * @param string $module module - * @param string $subdir subdir for file - * @return int 0 if OK, >0 if KO - */ - public function printFile($file, $module, $subdir = '') - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + /** + * Print selected file + * + * @param string $file file + * @param string $module module + * @param string $subdir subdir for file + * @return int 0 if OK, >0 if KO + */ + public function printFile($file, $module, $subdir = '') + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - global $conf, $user; - $error = 0; + global $conf, $user; + $error = 0; - $fileprint = $conf->{$module}->dir_output; - if ($subdir != '') { - $fileprint .= '/'.$subdir; - } - $fileprint .= '/'.$file; - $mimetype = dol_mimetype($fileprint); - // select printer uri for module order, propal,... - $sql = "SELECT rowid, printer_id, copy FROM ".MAIN_DB_PREFIX."printing WHERE module='".$this->db->escape($module)."' AND driver='printgcp' AND userid=".$user->id; - $result = $this->db->query($sql); - if ($result) - { - $obj = $this->db->fetch_object($result); - if ($obj) - { - $printer_id = $obj->printer_id; - } else { - if (!empty($conf->global->PRINTING_GCP_DEFAULT)) - { - $printer_id = $conf->global->PRINTING_GCP_DEFAULT; - } else { - $this->errors[] = 'NoDefaultPrinterDefined'; - $error++; - return $error; - } - } - } else { - dol_print_error($this->db); - } + $fileprint = $conf->{$module}->dir_output; + if ($subdir != '') { + $fileprint .= '/'.$subdir; + } + $fileprint .= '/'.$file; + $mimetype = dol_mimetype($fileprint); + // select printer uri for module order, propal,... + $sql = "SELECT rowid, printer_id, copy FROM ".MAIN_DB_PREFIX."printing WHERE module='".$this->db->escape($module)."' AND driver='printgcp' AND userid=".$user->id; + $result = $this->db->query($sql); + if ($result) + { + $obj = $this->db->fetch_object($result); + if ($obj) + { + $printer_id = $obj->printer_id; + } else { + if (!empty($conf->global->PRINTING_GCP_DEFAULT)) + { + $printer_id = $conf->global->PRINTING_GCP_DEFAULT; + } else { + $this->errors[] = 'NoDefaultPrinterDefined'; + $error++; + return $error; + } + } + } else { + dol_print_error($this->db); + } - $ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype); - $this->error = 'PRINTGCP: '.$ret['errormessage']; - if ($ret['status'] != 1) { - $error++; - } - return $error; - } + $ret = $this->sendPrintToPrinter($printer_id, $file, $fileprint, $mimetype); + $this->error = 'PRINTGCP: '.$ret['errormessage']; + if ($ret['status'] != 1) { + $error++; + } + return $error; + } - /** - * Sends document to the printer - * - * @param string $printerid Printer id returned by Google Cloud Print - * @param string $printjobtitle Job Title - * @param string $filepath File Path to be send to Google Cloud Print - * @param string $contenttype File content type by example application/pdf, image/png - * @return array status array - */ - public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype) - { - // Check if printer id - if (empty($printerid)) { - return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'No provided printer ID'); - } - // Open the file which needs to be print - $handle = fopen($filepath, "rb"); - if (!$handle) { - return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'Could not read the file.'); - } - // Read file content - $contents = fread($handle, filesize($filepath)); - fclose($handle); - // Prepare post fields for sending print - $post_fields = array( - 'printerid' => $printerid, - 'title' => $printjobtitle, - 'contentTransferEncoding' => 'base64', - 'content' => base64_encode($contents), // encode file content as base64 - 'contentType' => $contenttype, - ); - // Dolibarr Token storage - $storage = new DoliStorage($this->db, $this->conf); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google' - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + /** + * Sends document to the printer + * + * @param string $printerid Printer id returned by Google Cloud Print + * @param string $printjobtitle Job Title + * @param string $filepath File Path to be send to Google Cloud Print + * @param string $contenttype File content type by example application/pdf, image/png + * @return array status array + */ + public function sendPrintToPrinter($printerid, $printjobtitle, $filepath, $contenttype) + { + // Check if printer id + if (empty($printerid)) { + return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'No provided printer ID'); + } + // Open the file which needs to be print + $handle = fopen($filepath, "rb"); + if (!$handle) { + return array('status' =>0, 'errorcode' =>'', 'errormessage'=>'Could not read the file.'); + } + // Read file content + $contents = fread($handle, filesize($filepath)); + fclose($handle); + // Prepare post fields for sending print + $post_fields = array( + 'printerid' => $printerid, + 'title' => $printjobtitle, + 'contentTransferEncoding' => 'base64', + 'content' => base64_encode($contents), // encode file content as base64 + 'contentType' => $contenttype, + ); + // Dolibarr Token storage + $storage = new DoliStorage($this->db, $this->conf); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php?service=google' + ); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - // Check if we have auth token and refresh it - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - } - if ($token_ok) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - } - } + // Check if we have auth token and refresh it + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + } + if ($token_ok) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + } + } - // Send a request with api - $response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true); - //print '
'.print_r($response, true).'
'; - return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']); - } + // Send a request with api + $response = json_decode($apiService->request(self::PRINT_URL, 'POST', $post_fields), true); + //print '
'.print_r($response, true).'
'; + return array('status' => $response['success'], 'errorcode' => $response['errorCode'], 'errormessage' => $response['message']); + } - /** - * List jobs print - * - * @return int 0 if OK, >0 if KO - */ - public function listJobs() - { - global $conf, $langs; + /** + * List jobs print + * + * @return int 0 if OK, >0 if KO + */ + public function listJobs() + { + global $conf, $langs; - $error = 0; - $html = ''; - // Token storage - $storage = new DoliStorage($this->db, $this->conf); - // Setup the credentials for the requests - $credentials = new Credentials( - $this->google_id, - $this->google_secret, - DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' - ); - $serviceFactory = new \OAuth\ServiceFactory(); - $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); - // Check if we have auth token - $token_ok = true; - try { - $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $token_ok = false; - $error++; - } - $expire = false; - // Is token expired or will token expire in the next 30 seconds - if ($token_ok) { - $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); - } + $error = 0; + $html = ''; + // Token storage + $storage = new DoliStorage($this->db, $this->conf); + // Setup the credentials for the requests + $credentials = new Credentials( + $this->google_id, + $this->google_secret, + DOL_MAIN_URL_ROOT.'/core/modules/oauth/google_oauthcallback.php' + ); + $serviceFactory = new \OAuth\ServiceFactory(); + $apiService = $serviceFactory->createService($this->OAUTH_SERVICENAME_GOOGLE, $credentials, $storage, array()); + // Check if we have auth token + $token_ok = true; + try { + $token = $storage->retrieveAccessToken($this->OAUTH_SERVICENAME_GOOGLE); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $token_ok = false; + $error++; + } + $expire = false; + // Is token expired or will token expire in the next 30 seconds + if ($token_ok) { + $expire = ($token->getEndOfLife() !== -9002 && $token->getEndOfLife() !== -9001 && time() > ($token->getEndOfLife() - 30)); + } - // Token expired so we refresh it - if ($token_ok && $expire) { - try { - // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois - $refreshtoken = $token->getRefreshToken(); - $token = $apiService->refreshAccessToken($token); - $token->setRefreshToken($refreshtoken); - $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - } - // Getting Jobs - // Send a request with api - try { - $response = $apiService->request(self::PRINTERS_GET_JOBS); - } catch (Exception $e) { - $this->errors[] = $e->getMessage(); - $error++; - } - $responsedata = json_decode($response, true); - //$html .= '
'.print_r($responsedata,true).'
'; - $html .= '
'; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''."\n"; + // Token expired so we refresh it + if ($token_ok && $expire) { + try { + // il faut sauvegarder le refresh token car google ne le donne qu'une seule fois + $refreshtoken = $token->getRefreshToken(); + $token = $apiService->refreshAccessToken($token); + $token->setRefreshToken($refreshtoken); + $storage->storeAccessToken($this->OAUTH_SERVICENAME_GOOGLE, $token); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + } + // Getting Jobs + // Send a request with api + try { + $response = $apiService->request(self::PRINTERS_GET_JOBS); + } catch (Exception $e) { + $this->errors[] = $e->getMessage(); + $error++; + } + $responsedata = json_decode($response, true); + //$html .= '
'.print_r($responsedata,true).'
'; + $html .= '
'; + $html .= '
'.$langs->trans("Id").''.$langs->trans("Date").''.$langs->trans("Owner").''.$langs->trans("Printer").''.$langs->trans("Filename").''.$langs->trans("Status").''.$langs->trans("Cancel").'
'; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''; + $html .= ''."\n"; - $jobs = $responsedata['jobs']; - //$html .= '
'.print_r($jobs['0'],true).'
'; - if (is_array($jobs)) { - foreach ($jobs as $value) { - $html .= ''; - $html .= ''; - $dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour'); - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - $html .= ''; - } - } else { - $html .= ''; - $html .= ''; - $html .= ''; - } - $html .= '
'.$langs->trans("Id").''.$langs->trans("Date").''.$langs->trans("Owner").''.$langs->trans("Printer").''.$langs->trans("Filename").''.$langs->trans("Status").''.$langs->trans("Cancel").'
'.$value['id'].''.$dates.''.$value['ownerId'].''.$value['printerName'].''.$value['title'].''.$value['status'].' 
'.$langs->trans("None").'
'; - $html .= '
'; + $jobs = $responsedata['jobs']; + //$html .= '
'.print_r($jobs['0'],true).'
'; + if (is_array($jobs)) { + foreach ($jobs as $value) { + $html .= ''; + $html .= ''.$value['id'].''; + $dates = dol_print_date((int) substr($value['createTime'], 0, 10), 'dayhour'); + $html .= ''.$dates.''; + $html .= ''.$value['ownerId'].''; + $html .= ''.$value['printerName'].''; + $html .= ''.$value['title'].''; + $html .= ''.$value['status'].''; + $html .= ' '; + $html .= ''; + } + } else { + $html .= ''; + $html .= ''.$langs->trans("None").''; + $html .= ''; + } + $html .= ''; + $html .= '
'; - $this->resprint = $html; + $this->resprint = $html; - return $error; - } + return $error; + } } diff --git a/htdocs/core/tpl/bloc_comment.tpl.php b/htdocs/core/tpl/bloc_comment.tpl.php index edb675e45d6..e78a5a7734e 100644 --- a/htdocs/core/tpl/bloc_comment.tpl.php +++ b/htdocs/core/tpl/bloc_comment.tpl.php @@ -38,21 +38,21 @@ print "\n"; if ($action !== 'editcomment') { - print ''; + print ''; - // Description - print ''; + // Description + print ''; - $desc = GETPOST('comment_description'); + $desc = GETPOST('comment_description'); - $doleditor = new DolEditor('comment_description', $desc, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%'); - print $doleditor->Create(1); + $doleditor = new DolEditor('comment_description', $desc, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%'); + print $doleditor->Create(1); - print ''; + print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; } print ''; @@ -96,47 +96,47 @@ if (!empty($object->comments)) print '
'; print '
'; - if ($action === 'editcomment' && $comment->id == $idcomment) - { - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - } + if ($action === 'editcomment' && $comment->id == $idcomment) + { + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + } - print '
'; - if ($action === 'editcomment' && $comment->id == $idcomment) - { - $doleditor = new DolEditor('comment_description', $comment->description, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%'); - print $doleditor->Create(1); - } else { - print $comment->description; - } + print '
'; + if ($action === 'editcomment' && $comment->id == $idcomment) + { + $doleditor = new DolEditor('comment_description', $comment->description, '', 80, 'dolibarr_notes', 'In', 0, true, true, ROWS_3, '100%'); + print $doleditor->Create(1); + } else { + print $comment->description; + } print '
'; // End comment-description - if ($action === 'editcomment' && $comment->id == $idcomment) - { - print ''; - print ''; + if ($action === 'editcomment' && $comment->id == $idcomment) + { + print ''; + print ''; - print ''; - } else { - if ($fk_user == $user->id || $user->admin == 1) - { - print ''; - print img_picto('', 'edit.png'); - print ''; - } - if (($first && $fk_user == $user->id) || $user->admin == 1) { - print ''; - print img_picto('', 'delete.png'); - print ''; - } - } + print ''; + } else { + if ($fk_user == $user->id || $user->admin == 1) + { + print ''; + print img_picto('', 'edit.png'); + print ''; + } + if (($first && $fk_user == $user->id) || $user->admin == 1) { + print ''; + print img_picto('', 'delete.png'); + print ''; + } + } - print '
'; // End comment-table + print '
'; // End comment-table print '
'; // End comment-right print ''; // End comment diff --git a/htdocs/ecm/class/ecmdirectory.class.php b/htdocs/ecm/class/ecmdirectory.class.php index 25673c65c6c..dc39550c0cf 100644 --- a/htdocs/ecm/class/ecmdirectory.class.php +++ b/htdocs/ecm/class/ecmdirectory.class.php @@ -35,7 +35,7 @@ class EcmDirectory extends CommonObject /** * @var string Name of table without prefix where object is stored */ - public $table_element='ecm_directories'; + public $table_element = 'ecm_directories'; /** * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png diff --git a/htdocs/ecm/file_card.php b/htdocs/ecm/file_card.php index 483335093e9..d5a66ca4134 100644 --- a/htdocs/ecm/file_card.php +++ b/htdocs/ecm/file_card.php @@ -44,8 +44,8 @@ $socid = GETPOST("socid", "int"); // Security check if ($user->socid > 0) { - $action = ''; - $socid = $user->socid; + $action = ''; + $socid = $user->socid; } $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; @@ -62,14 +62,14 @@ if (!$sortfield) $sortfield = "label"; $section = GETPOST("section", 'alpha'); if (!$section) { - dol_print_error('', 'Error, section parameter missing'); - exit; + dol_print_error('', 'Error, section parameter missing'); + exit; } $urlfile = GETPOST("urlfile"); if (!$urlfile) { - dol_print_error('', "ErrorParamNotDefined"); - exit; + dol_print_error('', "ErrorParamNotDefined"); + exit; } // Load ecm object @@ -77,8 +77,8 @@ $ecmdir = new EcmDirectory($db); $result = $ecmdir->fetch(GETPOST("section", 'alpha')); if (!$result > 0) { - dol_print_error($db, $ecmdir->error); - exit; + dol_print_error($db, $ecmdir->error); + exit; } $relativepath = $ecmdir->getRelativePath(); $upload_dir = $conf->ecm->dir_output.'/'.$relativepath; @@ -114,67 +114,67 @@ if ($result < 0) if ($cancel) { - $action = ''; - if ($backtopage) - { - header("Location: ".$backtopage); - exit; - } else { - header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section).($module ? '&module='.urlencode($module) : '')); - exit; - } + $action = ''; + if ($backtopage) + { + header("Location: ".$backtopage); + exit; + } else { + header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section).($module ? '&module='.urlencode($module) : '')); + exit; + } } // Rename file if ($action == 'update') { - $error = 0; + $error = 0; - $oldlabel = GETPOST('urlfile', 'alpha'); - $newlabel = dol_sanitizeFileName(GETPOST('label', 'alpha')); + $oldlabel = GETPOST('urlfile', 'alpha'); + $newlabel = dol_sanitizeFileName(GETPOST('label', 'alpha')); $shareenabled = GETPOST('shareenabled', 'alpha'); - //$db->begin(); + //$db->begin(); - $olddir = $ecmdir->getRelativePath(0); // Relative to ecm - $olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document - $newdirrelativetodocument = 'ecm/'.$olddir; - $olddir = $conf->ecm->dir_output.'/'.$olddir; - $newdir = $olddir; + $olddir = $ecmdir->getRelativePath(0); // Relative to ecm + $olddirrelativetodocument = 'ecm/'.$olddir; // Relative to document + $newdirrelativetodocument = 'ecm/'.$olddir; + $olddir = $conf->ecm->dir_output.'/'.$olddir; + $newdir = $olddir; - $oldfile = $olddir.$oldlabel; - $newfile = $newdir.$newlabel; - $newfileformove = $newfile; - // If old file end with .noexe, new file must also end with .noexe - if (preg_match('/\.noexe$/', $oldfile) && ! preg_match('/\.noexe$/', $newfileformove)) { - $newfileformove .= '.noexe'; - } - //var_dump($oldfile);var_dump($newfile);exit; + $oldfile = $olddir.$oldlabel; + $newfile = $newdir.$newlabel; + $newfileformove = $newfile; + // If old file end with .noexe, new file must also end with .noexe + if (preg_match('/\.noexe$/', $oldfile) && ! preg_match('/\.noexe$/', $newfileformove)) { + $newfileformove .= '.noexe'; + } + //var_dump($oldfile);var_dump($newfile);exit; - // Now we update index of file - $db->begin(); - //print $oldfile.' - '.$newfile; - if ($newlabel != $oldlabel) - { - $result = dol_move($oldfile, $newfileformove); // This include update of database - if (!$result) - { - $langs->load('errors'); - setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors'); - $error++; - } + // Now we update index of file + $db->begin(); + //print $oldfile.' - '.$newfile; + if ($newlabel != $oldlabel) + { + $result = dol_move($oldfile, $newfileformove); // This include update of database + if (!$result) + { + $langs->load('errors'); + setEventMessages($langs->trans('ErrorFailToRenameFile', $oldfile, $newfile), null, 'errors'); + $error++; + } - // Reload object after the move - $result = $object->fetch(0, '', $newdirrelativetodocument.$newlabel); - if ($result < 0) - { - dol_print_error($db, $object->error, $object->errors); - exit; - } - } + // Reload object after the move + $result = $object->fetch(0, '', $newdirrelativetodocument.$newlabel); + if ($result < 0) + { + dol_print_error($db, $object->error, $object->errors); + exit; + } + } - if (!$error) - { + if (!$error) + { if ($shareenabled) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; @@ -217,23 +217,23 @@ if ($action == 'update') setEventMessages($object->error, $object->errors, 'warnings'); } } - } + } - if (!$error) - { - $db->commit(); + if (!$error) + { + $db->commit(); - $urlfile = $newlabel; - // If old file end with .noexe, new file must also end with .noexe - if (preg_match('/\.noexe$/', $newfileformove)) { - $urlfile .= '.noexe'; - } + $urlfile = $newlabel; + // If old file end with .noexe, new file must also end with .noexe + if (preg_match('/\.noexe$/', $newfileformove)) { + $urlfile .= '.noexe'; + } - header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section)); - exit; - } else { - $db->rollback(); - } + header('Location: '.$_SERVER["PHP_SELF"].'?urlfile='.urlencode($urlfile).'§ion='.urlencode($section)); + exit; + } else { + $db->rollback(); + } } @@ -381,7 +381,7 @@ if (!empty($object->share)) } print ''; print ''; -print $object->showOptionals($extrafields, ($action == 'edit'?'edit':'view')); +print $object->showOptionals($extrafields, ($action == 'edit' ? 'edit' : 'view')); print ''; print ''; @@ -392,20 +392,20 @@ dol_fiche_end(); if ($action == 'edit') { - print '
'; - print ''; - print '     '; - print ''; - print '
'; + print '
'; + print ''; + print '     '; + print ''; + print '
'; - print ''; + print ''; } // Confirmation de la suppression d'une ligne categorie if ($action == 'delete_file') { - print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1); + print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.urlencode($section), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile', $urlfile), 'confirm_deletefile', '', 1, 1); } if ($action != 'edit') @@ -413,11 +413,11 @@ if ($action != 'edit') // Actions buttons print '
'; - if ($user->rights->ecm->setup) - { - print ''.$langs->trans('Edit').''; - } - /* + if ($user->rights->ecm->setup) + { + print ''.$langs->trans('Edit').''; + } + /* if ($user->rights->ecm->setup) { print ''.$langs->trans('Delete').''; diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index b32e95597e8..3f7caca5890 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -405,7 +405,7 @@ class ExpenseReport extends CommonObject $this->id = 0; $this->ref = ''; $this->status = 0; - $this->fk_statut = 0; // deprecated + $this->fk_statut = 0; // deprecated // Clear fields $this->fk_user_author = $fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. @@ -1353,7 +1353,7 @@ class ExpenseReport extends CommonObject $sql .= ' WHERE rowid = '.$this->id; if ($this->db->query($sql)) { - $this->fk_statut = 99; // deprecated + $this->fk_statut = 99; // deprecated $this->status = 99; $this->fk_user_refuse = $fuser->id; $this->detail_refuse = $details; diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index 97dc2626280..e4afe4b0452 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -202,16 +202,16 @@ if (empty($reshook)) } } elseif ($action == 'add' && $user->rights->ficheinter->creer) { - $object->socid = $socid; - $object->duration = GETPOST('duration', 'int'); - $object->fk_project = GETPOST('projectid', 'int'); - $object->fk_contrat = GETPOST('contratid', 'int'); - $object->author = $user->id; - $object->description = GETPOST('description', 'restricthtml'); - $object->ref = $ref; - $object->model_pdf = GETPOST('model', 'alpha'); - $object->note_private = GETPOST('note_private', 'restricthtml'); - $object->note_public = GETPOST('note_public', 'restricthtml'); + $object->socid = $socid; + $object->duration = GETPOST('duration', 'int'); + $object->fk_project = GETPOST('projectid', 'int'); + $object->fk_contrat = GETPOST('contratid', 'int'); + $object->author = $user->id; + $object->description = GETPOST('description', 'restricthtml'); + $object->ref = $ref; + $object->model_pdf = GETPOST('model', 'alpha'); + $object->note_private = GETPOST('note_private', 'restricthtml'); + $object->note_public = GETPOST('note_public', 'restricthtml'); if ($object->socid > 0) { @@ -251,7 +251,7 @@ if (empty($reshook)) $extrafields = new ExtraFields($db); $array_options = $extrafields->getOptionalsFromPost($object->table_element); - $object->array_options = $array_options; + $object->array_options = $array_options; $id = $object->create($user); @@ -356,12 +356,12 @@ if (empty($reshook)) $result = $object->addline( $user, - $id, - $desc, - $date_intervention, - $duration, - $array_options - ); + $id, + $desc, + $date_intervention, + $duration, + $array_options + ); if ($result < 0) { @@ -371,44 +371,44 @@ if (empty($reshook)) } } } - } else { + } else { $mesg = $srcobject->error; - $error++; - } - } else { + $error++; + } + } else { $mesg = $object->error; - $error++; - } - } else { - // Fill array 'array_options' with data from add form - $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) { - $error++; - $action = 'create'; - } + $error++; + } + } else { + // Fill array 'array_options' with data from add form + $ret = $extrafields->setOptionalsFromPost(null, $object); + if ($ret < 0) { + $error++; + $action = 'create'; + } - if (!$error) - { - // Extrafields - $array_options = $extrafields->getOptionalsFromPost($object->table_element); + if (!$error) + { + // Extrafields + $array_options = $extrafields->getOptionalsFromPost($object->table_element); - $object->array_options = $array_options; + $object->array_options = $array_options; - $result = $object->create($user); - if ($result > 0) - { - $id = $result; // Force raffraichissement sur fiche venant d'etre cree - } else { - $langs->load("errors"); - setEventMessages($object->error, $object->errors, 'errors'); - $action = 'create'; - } - } - } - } else { + $result = $object->create($user); + if ($result > 0) + { + $id = $result; // Force raffraichissement sur fiche venant d'etre cree + } else { + $langs->load("errors"); + setEventMessages($object->error, $object->errors, 'errors'); + $action = 'create'; + } + } + } + } else { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")); - $action = 'create'; - } + $action = 'create'; + } } elseif ($action == 'update' && $user->rights->ficheinter->creer) { $object->socid = $socid; @@ -482,14 +482,14 @@ if (empty($reshook)) $extrafields->fetch_name_optionals_label($object->table_element_line); $array_options = $extrafields->getOptionalsFromPost($object->table_element_line); - $result = $object->addline( + $result = $object->addline( $user, - $id, - $desc, - $date_intervention, - $duration, - $array_options - ); + $id, + $desc, + $date_intervention, + $duration, + $array_options + ); // Define output language $outputlangs = $langs; @@ -545,14 +545,14 @@ if (empty($reshook)) // Classify Done elseif ($action == 'classifydone' && $user->rights->ficheinter->creer) { - $result = $object->setStatut(3); - if ($result > 0) - { - header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } + $result = $object->setStatut(3); + if ($result > 0) + { + header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); + exit; + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Reopen @@ -591,9 +591,9 @@ if (empty($reshook)) $date_inter = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); $duration = convertTime2Seconds(GETPOST('durationhour', 'int'), GETPOST('durationmin', 'int')); - $objectline->datei = $date_inter; - $objectline->desc = $desc; - $objectline->duration = $duration; + $objectline->datei = $date_inter; + $objectline->desc = $desc; + $objectline->duration = $duration; // Extrafields $extrafields->fetch_name_optionals_label($object->table_element_line); @@ -601,11 +601,11 @@ if (empty($reshook)) $objectline->array_options = $array_options; $result = $objectline->update($user); - if ($result < 0) - { - dol_print_error($db); - exit; - } + if ($result < 0) + { + dol_print_error($db); + exit; + } // Define output language $outputlangs = $langs; @@ -817,11 +817,11 @@ if ($action == 'create') $subelement = $regs[2]; } - if ($element == 'project') - { - $projectid = GETPOST('originid', 'int'); - } else { - // For compatibility + if ($element == 'project') + { + $projectid = GETPOST('originid', 'int'); + } else { + // For compatibility if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } @@ -904,20 +904,20 @@ if ($action == 'create') $langs->load("project"); - print ''.$langs->trans("Project").''; - /* Fix: If a project must be linked to any companies (suppliers or not), project must be not be set as limited to customer but must be not linked to any particular thirdparty + print ''.$langs->trans("Project").''; + /* Fix: If a project must be linked to any companies (suppliers or not), project must be not be set as limited to customer but must be not linked to any particular thirdparty if ($societe->fournisseur==1) $numprojet=select_projects(-1,$_POST["projectid"],'projectid'); else $numprojet=select_projects($societe->id,$_POST["projectid"],'projectid'); */ - $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid'); - if ($numprojet == 0) - { - print '   '; - } - print ''; - } + $numprojet = $formproject->select_projects($soc->id, $projectid, 'projectid'); + if ($numprojet == 0) + { + print '   '; + } + print ''; + } // Contract if ($conf->contrat->enabled) @@ -932,53 +932,53 @@ if ($action == 'create') print ''; } - // Model - print ''; - print ''.$langs->trans("DefaultModel").''; - print ''; - $liste = ModelePDFFicheinter::liste_modeles($db); - print $form->selectarray('model', $liste, $conf->global->FICHEINTER_ADDON_PDF); - print ""; + // Model + print ''; + print ''.$langs->trans("DefaultModel").''; + print ''; + $liste = ModelePDFFicheinter::liste_modeles($db); + print $form->selectarray('model', $liste, $conf->global->FICHEINTER_ADDON_PDF); + print ""; - // Public note - print ''; - print ''.$langs->trans('NotePublic').''; - print ''; - $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - //print ''; - print ''; + // Public note + print ''; + print ''.$langs->trans('NotePublic').''; + print ''; + $doleditor = new DolEditor('note_public', $note_public, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + //print ''; + print ''; - // Private note - if (empty($user->socid)) - { - print ''; - print ''.$langs->trans('NotePrivate').''; - print ''; - $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); - print $doleditor->Create(1); - //print ''; - print ''; - } + // Private note + if (empty($user->socid)) + { + print ''; + print ''.$langs->trans('NotePrivate').''; + print ''; + $doleditor = new DolEditor('note_private', $note_private, '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); + print $doleditor->Create(1); + //print ''; + print ''; + } - // Other attributes - $parameters = array(); - $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; - if (empty($reshook)) + // Other attributes + $parameters = array(); + $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } - // Show link to origin object - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { - $newclassname = $classname; - if ($newclassname == 'Propal') $newclassname = 'CommercialProposal'; - print ''.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).''; + // Show link to origin object + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) + { + $newclassname = $classname; + if ($newclassname == 'Propal') $newclassname = 'CommercialProposal'; + print ''.$langs->trans($newclassname).''.$objectsrc->getNomUrl(1).''; - // Amount - /* Hide amount because we only copy services so amount may differ than source + // Amount + /* Hide amount because we only copy services so amount may differ than source print '' . $langs->trans('AmountHT') . '' . price($objectsrc->total_ht) . ''; print '' . $langs->trans('AmountVAT') . '' . price($objectsrc->total_tva) . ""; if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE @@ -1000,14 +1000,14 @@ if ($action == 'create') print '' . $langs->trans('MulticurrencyAmountTTC') . '' . price($objectsrc->multicurrency_total_ttc) . ""; } */ - } + } - print ''; + print ''; - if (is_object($objectsrc)) - { - print ''; - print ''; + if (is_object($objectsrc)) + { + print ''; + print ''; } elseif ($origin == 'project' && !empty($projectid)) { print ''; } @@ -1016,8 +1016,8 @@ if ($action == 'create') print '
'; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
'; print ''; @@ -1058,8 +1058,8 @@ if ($action == 'create') print '
'; print ''; print ''; - print '     '; - print ''; + print '     '; + print ''; print '
'; print ''; @@ -1172,46 +1172,46 @@ if ($action == 'create') // Project if (!empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->ficheinter->creer) - { - if ($action != 'classify') { - $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; - } - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '
'; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; - $morehtmlref .= '
'; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= ''; - $morehtmlref .= $proj->ref; - $morehtmlref .= ''; - } else { - $morehtmlref .= ''; - } - } + $langs->load("projects"); + $morehtmlref .= '
'.$langs->trans('Project').' '; + if ($user->rights->ficheinter->creer) + { + if ($action != 'classify') { + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + } + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
'; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
'; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; + } else { + $morehtmlref .= ''; + } + } } $morehtmlref .= '
'; - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print ''; + print '
'; if (!empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES)) { @@ -1269,47 +1269,47 @@ if ($action == 'create') $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1, 1); } else { if ($object->fk_contrat) - { - $contratstatic = new Contrat($db); - $contratstatic->fetch($object->fk_contrat); - //print ''.$projet->title.''; - print $contratstatic->getNomUrl(0, '', 1); - } else { - print " "; - } + { + $contratstatic = new Contrat($db); + $contratstatic->fetch($object->fk_contrat); + //print ''.$projet->title.''; + print $contratstatic->getNomUrl(0, '', 1); + } else { + print " "; + } } print ''; print ''; } - // Other attributes - $cols = 2; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; + // Other attributes + $cols = 2; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; - print '
'; + print ''; - print '
'; - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; + print '
'; - print ''; + print '
'; - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) - { - // Duration - print ''; - print ''; - print ''; - } + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) + { + // Duration + print ''; + print ''; + print ''; + } print "
'.$langs->trans("TotalDuration").''.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'
'.$langs->trans("TotalDuration").''.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'
"; print '
'; - print '
'; - print '
'; + print '
'; + print '
'; - print '

'; + print '

'; if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) @@ -1464,25 +1464,25 @@ if ($action == 'create') // Date d'intervention print ''; - if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { - print $form->selectDate($db->jdate($objp->date_intervention), 'di', 0, 0, 0, "date_intervention"); - } else { - print $form->selectDate($db->jdate($objp->date_intervention), 'di', 1, 1, 0, "date_intervention"); - } + if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { + print $form->selectDate($db->jdate($objp->date_intervention), 'di', 0, 0, 0, "date_intervention"); + } else { + print $form->selectDate($db->jdate($objp->date_intervention), 'di', 1, 1, 0, "date_intervention"); + } print ''; - // Duration - print ''; - if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { - $selectmode = 'select'; - if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) - $selectmode = 'text'; - $form->select_duration('duration', $objp->duree, 0, $selectmode); - } - print ''; + // Duration + print ''; + if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { + $selectmode = 'select'; + if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) + $selectmode = 'text'; + $form->select_duration('duration', $objp->duree, 0, $selectmode); + } + print ''; - print ''; - print ''; + print ''; + print ''; print ''; print ''."\n"; @@ -1514,13 +1514,13 @@ if ($action == 'create') print ''; } - print ''; - print ''; // ancre - print $langs->trans('Description').''; - print ''.$langs->trans('Date').''; - print ''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').''; - print ' '; - print "\n"; + print ''; + print ''; // ancre + print $langs->trans('Description').''; + print ''.$langs->trans('Date').''; + print ''.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').''; + print ' '; + print "\n"; } print ''."\n"; @@ -1530,43 +1530,43 @@ if ($action == 'create') print ''.($i + 1).''; } - print ''; - // editeur wysiwyg - if (empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('np_desc', GETPOST('np_desc', 'restricthtml'), '', 100, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); - $doleditor->Create(); - } - print ''; + print ''; + // editeur wysiwyg + if (empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor('np_desc', GETPOST('np_desc', 'restricthtml'), '', 100, 'dolibarr_details', '', false, true, $conf->global->FCKEDITOR_ENABLE_DETAILS, ROWS_2, '90%'); + $doleditor->Create(); + } + print ''; - // Date intervention - print ''; + // Date intervention + print ''; $now = dol_now(); $timearray = dol_getdate($now); if (!GETPOST('diday', 'int')) { - $timewithnohour = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); - } else { - $timewithnohour = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); - } - if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { - print $form->selectDate($timewithnohour, 'di', 0, 0, 0, "addinter"); - } else { - print $form->selectDate($timewithnohour, 'di', 1, 1, 0, "addinter"); - } + $timewithnohour = dol_mktime(0, 0, 0, $timearray['mon'], $timearray['mday'], $timearray['year']); + } else { + $timewithnohour = dol_mktime(GETPOST('dihour', 'int'), GETPOST('dimin', 'int'), 0, GETPOST('dimonth', 'int'), GETPOST('diday', 'int'), GETPOST('diyear', 'int')); + } + if (!empty($conf->global->FICHINTER_DATE_WITHOUT_HOUR)) { + print $form->selectDate($timewithnohour, 'di', 0, 0, 0, "addinter"); + } else { + print $form->selectDate($timewithnohour, 'di', 1, 1, 0, "addinter"); + } print ''; - // Duration - print ''; - if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { - $selectmode = 'select'; - if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) { - $selectmode = 'text'; - } - $form->select_duration('duration', (!GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) ? 3600 : (60 * 60 * GETPOST('durationhour', 'int') + 60 * GETPOST('durationmin', 'int')), 0, $selectmode); - } - print ''; + // Duration + print ''; + if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { + $selectmode = 'select'; + if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) { + $selectmode = 'text'; + } + $form->select_duration('duration', (!GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) ? 3600 : (60 * 60 * GETPOST('durationhour', 'int') + 60 * GETPOST('durationmin', 'int')), 0, $selectmode); + } + print ''; - print ''; + print ''; print ''; //Line extrafield @@ -1601,22 +1601,22 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been - // modified by hook + // modified by hook if (empty($reshook)) { if ($user->socid == 0) { - if ($action != 'editdescription' && ($action != 'presend')) { - // Validate - if ($object->statut == Fichinter::STATUS_DRAFT && (count($object->lines) > 0 || !empty($conf->global->FICHINTER_DISABLE_DETAILS))) { - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->validate)) { - print ''; - } - } + if ($action != 'editdescription' && ($action != 'presend')) { + // Validate + if ($object->statut == Fichinter::STATUS_DRAFT && (count($object->lines) > 0 || !empty($conf->global->FICHINTER_DISABLE_DETAILS))) { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->validate)) { + print ''; + } + } - // Modify - if ($object->statut == Fichinter::STATUS_VALIDATED && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->unvalidate))) + // Modify + if ($object->statut == Fichinter::STATUS_VALIDATED && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->creer) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $user->rights->ficheinter->ficheinter_advance->unvalidate))) { print '
'; if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) print $langs->trans("Modify"); @@ -1684,7 +1684,7 @@ if ($action == 'create') } // Done - if (empty($conf->global->FICHINTER_CLASSIFY_BILLED) && $object->statut > Fichinter::STATUS_DRAFT && $object->statut < Fichinter::STATUS_CLOSED) + if (empty($conf->global->FICHINTER_CLASSIFY_BILLED) && $object->statut > Fichinter::STATUS_DRAFT && $object->statut < Fichinter::STATUS_CLOSED) { print ''; } diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 289eaf2d05b..264832cadc2 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -702,7 +702,7 @@ class FactureFournisseur extends CommonInvoice $this->note_private = $obj->note_private; $this->note_public = $obj->note_public; $this->model_pdf = $obj->model_pdf; - $this->modelpdf = $obj->model_pdf; // deprecated + $this->modelpdf = $obj->model_pdf; // deprecated $this->import_key = $obj->import_key; //Incoterms @@ -827,7 +827,7 @@ class FactureFournisseur extends CommonInvoice // Accountancy $line->code_ventilation = $obj->fk_code_ventilation; - $line->fk_accounting_account = $obj->fk_code_ventilation; + $line->fk_accounting_account = $obj->fk_code_ventilation; // Multicurrency $line->fk_multicurrency = $obj->fk_multicurrency; diff --git a/htdocs/fourn/commande/list.php b/htdocs/fourn/commande/list.php index 8bbd73ad016..fb2e18a0de2 100644 --- a/htdocs/fourn/commande/list.php +++ b/htdocs/fourn/commande/list.php @@ -364,30 +364,30 @@ if (empty($reshook)) { $fk_parent_line = 0; } - $result = $objecttmp->addline( + $result = $objecttmp->addline( $desc, $lines[$i]->subprice, $lines[$i]->tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, - $lines[$i]->qty, - $lines[$i]->fk_product, + $lines[$i]->qty, + $lines[$i]->fk_product, $lines[$i]->remise_percent, $date_start, $date_end, 0, $lines[$i]->info_bits, - 'HT', - $product_type, - $lines[$i]->rang, - false, - $lines[$i]->array_options, - $lines[$i]->fk_unit, - $objecttmp->origin_id, - $lines[$i]->pa_ht, - $lines[$i]->ref_supplier, - $lines[$i]->special_code, - $fk_parent_line + 'HT', + $product_type, + $lines[$i]->rang, + false, + $lines[$i]->array_options, + $lines[$i]->fk_unit, + $objecttmp->origin_id, + $lines[$i]->pa_ht, + $lines[$i]->ref_supplier, + $lines[$i]->special_code, + $fk_parent_line ); if ($result > 0) { @@ -686,7 +686,7 @@ if ($resql) $arrayofmassactions = array( 'generate_doc'=>$langs->trans("ReGeneratePDF"), 'builddoc'=>$langs->trans("PDFMerge"), - 'presend'=>$langs->trans("SendByMail"), + 'presend'=>$langs->trans("SendByMail"), ); if ($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); if ($user->rights->fournisseur->commande->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); @@ -1293,14 +1293,14 @@ if ($resql) $db->free($resql); - $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); - $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook - print $hookmanager->resPrint; + $parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql); + $reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; - print ''."\n"; - print '
'; + print ''."\n"; + print '
'; - print ''."\n"; + print ''."\n"; $hidegeneratedfilelistifempty = 1; if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index b0f178c6fc4..029abf36058 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -153,21 +153,21 @@ if (empty($reshook)) // Action clone object if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) { - $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. + $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone. We use native clone to keep this->db valid. - if (GETPOST('newsupplierref', 'alphanohtml')) $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml'); - $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); + if (GETPOST('newsupplierref', 'alphanohtml')) $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml'); + $objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); - $result = $objectutil->createFromClone($user, $id); - if ($result > 0) - { - header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); - exit; - } else { - $langs->load("errors"); - setEventMessages($objectutil->error, $objectutil->errors, 'errors'); - $action = ''; - } + $result = $objectutil->createFromClone($user, $id); + if ($result > 0) + { + header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); + exit; + } else { + $langs->load("errors"); + setEventMessages($objectutil->error, $objectutil->errors, 'errors'); + $action = ''; + } } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { $idwarehouse = GETPOST('idwarehouse'); @@ -1041,7 +1041,7 @@ if (empty($reshook)) $object->fetch($id); $object->fetch_thirdparty(); - $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); + $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); if (GETPOST('price_ht') != '') { @@ -1077,17 +1077,17 @@ if (empty($reshook)) $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), GETPOST('date_startsec'), GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), GETPOST('date_endsec'), GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); - // Define info_bits - $info_bits = 0; - if (preg_match('/\*/', $tva_tx)) - $info_bits |= 0x01; + // Define info_bits + $info_bits = 0; + if (preg_match('/\*/', $tva_tx)) + $info_bits |= 0x01; - // Define vat_rate - $tva_tx = str_replace('*', '', $tva_tx); - $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); - $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); + // Define vat_rate + $tva_tx = str_replace('*', '', $tva_tx); + $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); + $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - $remise_percent = GETPOST('remise_percent'); + $remise_percent = GETPOST('remise_percent'); $pu_ht_devise = GETPOST('multicurrency_subprice'); // Extrafields Lines @@ -1100,12 +1100,12 @@ if (empty($reshook)) } } - $result = $object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); - if ($result >= 0) - { - unset($_POST['label']); - unset($_POST['fourn_ref']); - unset($_POST['date_starthour']); + $result = $object->updateline(GETPOST('lineid'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, GETPOST('qty'), GETPOST('productid'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, $_POST['units'], $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); + if ($result >= 0) + { + unset($_POST['label']); + unset($_POST['fourn_ref']); + unset($_POST['date_starthour']); unset($_POST['date_startmin']); unset($_POST['date_startsec']); unset($_POST['date_startday']); @@ -1250,7 +1250,7 @@ if (empty($reshook)) // if we use supplier description of the products if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { - $desc = $productsupplier->desc_supplier; + $desc = $productsupplier->desc_supplier; } else $desc = $productsupplier->description; if (trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); @@ -1301,8 +1301,8 @@ if (empty($reshook)) $array_options, $productsupplier->fk_unit, 0, - $pu_ht_devise, - $ref_supplier, + $pu_ht_devise, + $ref_supplier, '' ); } @@ -1430,34 +1430,34 @@ if (empty($reshook)) if (!$ventilExportCompta) { - // On verifie si aucun paiement n'a ete effectue + // On verifie si aucun paiement n'a ete effectue if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) - { - $idwarehouse = GETPOST('idwarehouse'); + { + $idwarehouse = GETPOST('idwarehouse'); - $object->fetch_thirdparty(); + $object->fetch_thirdparty(); - $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); - } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); - } + $qualified_for_stock_change = 0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change = $object->hasProductsOrServices(2); + } else { + $qualified_for_stock_change = $object->hasProductsOrServices(1); + } - // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { - $langs->load("stocks"); - if (!$idwarehouse || $idwarehouse == -1) - { - $error++; - setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); - $action = ''; - } - } + // Check parameters + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + if (!$idwarehouse || $idwarehouse == -1) + { + $error++; + setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); + $action = ''; + } + } - $object->setDraft($user, $idwarehouse); + $object->setDraft($user, $idwarehouse); // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) @@ -1771,9 +1771,9 @@ if ($action == 'create') print ''; // Ref supplier - print ''.$langs->trans('RefSupplier').'id > 0) print ' autofocus'; - print '>'; + print ''.$langs->trans('RefSupplier').'id > 0) print ' autofocus'; + print '>'; print ''; print ''.$langs->trans('Type').''; @@ -2059,7 +2059,7 @@ if ($action == 'create') $doleditor = new DolEditor('note_public', (GETPOSTISSET('note_public') ?GETPOST('note_public', 'restricthtml') : $note_public), '', 80, 'dolibarr_notes', 'In', 0, false, true, ROWS_3, '90%'); print $doleditor->Create(1); print ''; - // print ''; + // print ''; print ''; // Private note @@ -2241,8 +2241,8 @@ if ($action == 'create') { // Create an array for form $formquestion = array( - array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier), - array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now()) + array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier), + array('type' => 'date', 'name' => 'newdate', 'label' => $langs->trans("Date"), 'value' => dol_now()) ); // Ask confirmation to clone $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneInvoice', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 250); @@ -2279,59 +2279,59 @@ if ($action == 'create') $qualified_for_stock_change = $object->hasProductsOrServices(1); } - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { - $langs->load("stocks"); - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct = new FormProduct($db); - $warehouse = new Entrepot($db); - $warehouse_array = $warehouse->list_array(); - if (count($warehouse_array) == 1) { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array)); - $value = ''; - } else { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease"); - $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); - } - $formquestion = array( - array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) - ); - } + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct = new FormProduct($db); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockDecrease", current($warehouse_array)) : $langs->trans("WarehouseForStockIncrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockDecrease") : $langs->trans("SelectWarehouseForStockIncrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) + ); + } $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $text, 'confirm_valid', $formquestion, 1, 1); - } + } - // Confirmation edit (back to draft) - if ($action == 'edit') - { - $formquestion = array(); + // Confirmation edit (back to draft) + if ($action == 'edit') + { + $formquestion = array(); - $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); - } else { - $qualified_for_stock_change = $object->hasProductsOrServices(1); - } - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) - { - $langs->load("stocks"); - require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; - $formproduct = new FormProduct($db); - $warehouse = new Entrepot($db); - $warehouse_array = $warehouse->list_array(); - if (count($warehouse_array) == 1) { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array)); - $value = ''; - } else { - $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease"); - $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); - } - $formquestion = array( - array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) - ); - } - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1); + $qualified_for_stock_change = 0; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + { + $qualified_for_stock_change = $object->hasProductsOrServices(2); + } else { + $qualified_for_stock_change = $object->hasProductsOrServices(1); + } + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) + { + $langs->load("stocks"); + require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; + $formproduct = new FormProduct($db); + $warehouse = new Entrepot($db); + $warehouse_array = $warehouse->list_array(); + if (count($warehouse_array) == 1) { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("WarehouseForStockIncrease", current($warehouse_array)) : $langs->trans("WarehouseForStockDecrease", current($warehouse_array)); + $value = ''; + } else { + $label = $object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("SelectWarehouseForStockIncrease") : $langs->trans("SelectWarehouseForStockDecrease"); + $value = $formproduct->selectWarehouses(GETPOST('idwarehouse') ?GETPOST('idwarehouse') : 'ifone', 'idwarehouse', '', 1); + } + $formquestion = array( + array('type' => 'other', 'name' => 'idwarehouse', 'label' => $label, 'value' => $value) + ); + } + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('UnvalidateBill'), $langs->trans('ConfirmUnvalidateBill', $object->ref), 'confirm_edit', $formquestion, 1, 1); } // Confirmation set paid @@ -2369,109 +2369,109 @@ if ($action == 'create') print $formconfirm; - // Supplier invoice card - $linkback = ''.$langs->trans("BackToList").''; + // Supplier invoice card + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
'; - // Ref supplier - $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1); - $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; - // Project - if (!empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($usercancreate) - { - if ($action != 'classify') { - $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; - } - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '
'; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; - $morehtmlref .= '
'; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= ''; - $morehtmlref .= $proj->ref; - $morehtmlref .= ''; - } else { - $morehtmlref .= ''; - } - } - } - $morehtmlref .= '
'; + $morehtmlref = '
'; + // Ref supplier + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; + // Project + if (!empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref .= '
'.$langs->trans('Project').' '; + if ($usercancreate) + { + if ($action != 'classify') { + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + } + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
'; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects((empty($conf->global->PROJECT_CAN_ALWAYS_LINK_TO_ALL_SUPPLIERS) ? $object->socid : -1), $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
'; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; + } else { + $morehtmlref .= ''; + } + } + } + $morehtmlref .= '
'; - $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); - print '
'; - print '
'; - print '
'; + print '
'; + print '
'; + print '
'; - print ''; + print '
'; - // Type - print ''; + $facidavoir = $object->getListIdAvoirFromInvoice(); + if (count($facidavoir) > 0) + { + print ' ('.$langs->transnoentities("InvoiceHasAvoir"); + $i = 0; + foreach ($facidavoir as $id) + { + if ($i == 0) print ' '; + else print ','; + $facavoir = new FactureFournisseur($db); + $facavoir->fetch($id); + print $facavoir->getNomUrl(1); + } + print ')'; + } + if (isset($facidnext) && $facidnext > 0) + { + $facthatreplace = new FactureFournisseur($db); + $facthatreplace->fetch($facidnext); + print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; + } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + $discount = new DiscountAbsolute($db); + $result = $discount->fetch(0, 0, $object->id); + if ($result > 0) { + print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).'
'; + } + } + print ''; - // Relative and absolute discounts + // Relative and absolute discounts print ''; - // Label - print ''; - print ''; - print ''; - print ''; + // Label + print ''; + print ''; + print ''; + print ''; - $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0); + $form_permission = ($object->statut < FactureFournisseur::STATUS_CLOSED) && $usercancreate && ($object->getSommePaiement() <= 0); - // Date - print ''; + // Date + print ''; // Default terms of the settlement $langs->load('bills'); @@ -3033,7 +3033,7 @@ if ($action == 'create') // modified by hook if (empty($reshook)) { - // Modify a validated invoice with no payments + // Modify a validated invoice with no payments if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate) { // We check if lines of invoice are not already transfered into accountancy @@ -3078,17 +3078,17 @@ if ($action == 'create') } } - // Make payments - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { - print ''; // must use facid because id is for payment id not invoice - } + // Make payments + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) + { + print ''; // must use facid because id is for payment id not invoice + } - // Classify paid - if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { - print ''; + // Classify paid + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) + { + print ''; //print ''.$langs->trans('ClassifyPaid').''; } @@ -3124,21 +3124,21 @@ if ($action == 'create') } } - // Validate - if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) - { - if (count($object->lines)) - { + // Validate + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) + { + if (count($object->lines)) + { if ($usercanvalidate) - { - print ''; - } else { - print ''; - } - } - } + { + print ''; + } else { + print ''; + } + } + } // Create event /*if ($conf->agenda->enabled && ! empty($conf->global->MAIN_ADD_EVENT_ON_ELEMENT_CARD)) // Add hidden condition because this is not a "workflow" action so should appears somewhere else on page. @@ -3161,30 +3161,30 @@ if ($action == 'create') } } - // Delete + // Delete $isErasable = $object->is_erasable(); if ($action != 'confirm_edit' && ($user->rights->fournisseur->facture->supprimer || ($usercancreate && $isErasable == 1))) // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions) - { - //var_dump($isErasable); - if ($isErasable == -4) { - print ''; - } elseif ($isErasable == -3) { // Should never happen with supplier invoice - print ''; - } elseif ($isErasable == -2) { // Should never happen with supplier invoice - print ''; - } elseif ($isErasable == -1) { - print ''; - } elseif ($isErasable <= 0) // Any other cases - { - print ''; - } else { - print ''; - } - } - print ''; + { + //var_dump($isErasable); + if ($isErasable == -4) { + print ''; + } elseif ($isErasable == -3) { // Should never happen with supplier invoice + print ''; + } elseif ($isErasable == -2) { // Should never happen with supplier invoice + print ''; + } elseif ($isErasable == -1) { + print ''; + } elseif ($isErasable <= 0) // Any other cases + { + print ''; + } else { + print ''; + } + } + print ''; - if ($action != 'confirm_edit') - { + if ($action != 'confirm_edit') + { print '
'; /* diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 2887298cae7..f43ef300b01 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -94,56 +94,56 @@ if ($object->id > 0) $totalpaye = $object->getSommePaiement(); - $linkback = ''.$langs->trans("BackToList").''; + $linkback = ''.$langs->trans("BackToList").''; - $morehtmlref = '
'; - // Ref supplier - $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); - $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); - // Thirdparty - $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; - // Project - if (!empty($conf->projet->enabled)) - { - $langs->load("projects"); - $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') - //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; - $morehtmlref .= ' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= '
'; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; - $morehtmlref .= ''; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= ''; - $morehtmlref .= $proj->ref; - $morehtmlref .= ''; - } else { - $morehtmlref .= ''; - } - } - } - $morehtmlref .= '
'; + $morehtmlref = '
'; + // Ref supplier + $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; + // Project + if (!empty($conf->projet->enabled)) + { + $langs->load("projects"); + $morehtmlref .= '
'.$langs->trans('Project').' '; + if ($user->rights->facture->creer) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref .= ' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
'; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= ''; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ''; + $morehtmlref .= $proj->ref; + $morehtmlref .= ''; + } else { + $morehtmlref .= ''; + } + } + } + $morehtmlref .= '
'; - $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status + $object->totalpaye = $totalpaye; // To give a chance to dol_banner_tab to use already paid amount to show correct status - dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0); + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0); - print '
'; - print '
'; + print '
'; + print '
'; // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); @@ -271,7 +271,7 @@ if ($object->id > 0) if ($res) break; } } else { - print $langs->trans('ErrorUnknown'); + print $langs->trans('ErrorUnknown'); } // End of page diff --git a/htdocs/hrm/index.php b/htdocs/hrm/index.php index 88141debfad..3955e3f849a 100644 --- a/htdocs/hrm/index.php +++ b/htdocs/hrm/index.php @@ -96,42 +96,42 @@ print '
'; if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo { - if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) - { - $langs->load("holiday"); - $listofsearchfields['search_holiday'] = array('text'=>'TitreRequestCP'); - } - if (!empty($conf->deplacement->enabled) && $user->rights->deplacement->lire) - { - $langs->load("trips"); - $listofsearchfields['search_deplacement'] = array('text'=>'ExpenseReport'); - } - if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) - { - $langs->load("trips"); - $listofsearchfields['search_expensereport'] = array('text'=>'ExpenseReport'); - } - if (count($listofsearchfields)) - { - print '
'; - print ''; - print '
'; - print '
'.$langs->trans('Type').''; - print $object->getLibType(); - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { - $facreplaced = new FactureFournisseur($db); - $facreplaced->fetch($object->fk_facture_source); - print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; - } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { - $facusing = new FactureFournisseur($db); - $facusing->fetch($object->fk_facture_source); - print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; - } + // Type + print '
'.$langs->trans('Type').''; + print $object->getLibType(); + if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) + { + $facreplaced = new FactureFournisseur($db); + $facreplaced->fetch($object->fk_facture_source); + print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; + } + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) + { + $facusing = new FactureFournisseur($db); + $facusing->fetch($object->fk_facture_source); + print ' ('.$langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)).')'; + } - $facidavoir = $object->getListIdAvoirFromInvoice(); - if (count($facidavoir) > 0) - { - print ' ('.$langs->transnoentities("InvoiceHasAvoir"); - $i = 0; - foreach ($facidavoir as $id) - { - if ($i == 0) print ' '; - else print ','; - $facavoir = new FactureFournisseur($db); - $facavoir->fetch($id); - print $facavoir->getNomUrl(1); - } - print ')'; - } - if (isset($facidnext) && $facidnext > 0) - { - $facthatreplace = new FactureFournisseur($db); - $facthatreplace->fetch($facidnext); - print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; - } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { - $discount = new DiscountAbsolute($db); - $result = $discount->fetch(0, 0, $object->id); - if ($result > 0) { - print '. '.$langs->trans("CreditNoteConvertedIntoDiscount", $object->getLibType(1), $discount->getNomUrl(1, 'discount')).'
'; - } - } - print '
'.$langs->trans('Discounts'); print ''; @@ -2482,18 +2482,18 @@ if ($action == 'create') print '
'.$form->editfieldkey("Label", 'label', $object->label, $object, ($usercancreate)).''.$form->editfieldval("Label", 'label', $object->label, $object, ($usercancreate)).'
'.$form->editfieldkey("Label", 'label', $object->label, $object, ($usercancreate)).''.$form->editfieldval("Label", 'label', $object->label, $object, ($usercancreate)).'
'.$form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker').''; - print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker'); - print '
'.$form->editfieldkey("DateInvoice", 'datef', $object->datep, $object, $form_permission, 'datepicker').''; + print $form->editfieldval("Date", 'datef', $object->datep, $object, $form_permission, 'datepicker'); + print '
'; - $i = 0; - foreach ($listofsearchfields as $key => $value) - { - if ($i == 0) print ''; - print ''; - print ''; - if ($i == 0) print ''; - print ''; - $i++; - } - print '
'.$langs->trans("Search").'
'; - print '
'; - print ''; - print '
'; - } + if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) + { + $langs->load("holiday"); + $listofsearchfields['search_holiday'] = array('text'=>'TitreRequestCP'); + } + if (!empty($conf->deplacement->enabled) && $user->rights->deplacement->lire) + { + $langs->load("trips"); + $listofsearchfields['search_deplacement'] = array('text'=>'ExpenseReport'); + } + if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) + { + $langs->load("trips"); + $listofsearchfields['search_expensereport'] = array('text'=>'ExpenseReport'); + } + if (count($listofsearchfields)) + { + print '
'; + print ''; + print '
'; + print ''; + $i = 0; + foreach ($listofsearchfields as $key => $value) + { + if ($i == 0) print ''; + print ''; + print ''; + if ($i == 0) print ''; + print ''; + $i++; + } + print '
'.$langs->trans("Search").'
'; + print '
'; + print '
'; + print '
'; + } } @@ -141,26 +141,26 @@ if (!empty($conf->holiday->enabled)) { $user_id = $user->id; - print '
'; - print ''; - print ''; - print ''; - print ''; + print ''; + print '
'.$langs->trans("Holidays").'
'; + print '
'; + print ''; + print ''; + print ''; + print ''; - print ''; - print '
'.$langs->trans("Holidays").'
'; - $out = ''; - $typeleaves = $holiday->getTypes(1, 1); - foreach ($typeleaves as $key => $val) - { - $nb_type = $holiday->getCPforUser($user->id, $val['rowid']); - $nb_holiday += $nb_type; - $out .= ' - '.$val['label'].': '.($nb_type ?price2num($nb_type) : 0).'
'; - } - print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'
'; - print $out; + $out = ''; + $typeleaves = $holiday->getTypes(1, 1); + foreach ($typeleaves as $key => $val) + { + $nb_type = $holiday->getCPforUser($user->id, $val['rowid']); + $nb_holiday += $nb_type; + $out .= ' - '.$val['label'].': '.($nb_type ?price2num($nb_type) : 0).'
'; + } + print $langs->trans('SoldeCPUser', round($nb_holiday, 5)).'
'; + print $out; - print '

'; + print '

'; } elseif (!is_numeric($conf->global->HOLIDAY_HIDE_BALANCE)) { print $langs->trans($conf->global->HOLIDAY_HIDE_BALANCE).'
'; @@ -175,80 +175,80 @@ print '
'; // Latest leave requests if (!empty($conf->holiday->enabled) && $user->rights->holiday->read) { - $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.photo, u.statut as user_status,"; - $sql .= " x.rowid, x.rowid as ref, x.fk_type, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.tms as dm, x.statut as status"; - $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; - $sql .= " WHERE u.rowid = x.fk_user"; - $sql .= " AND x.entity = ".$conf->entity; - if (empty($user->rights->holiday->read_all)) $sql .= ' AND x.fk_user IN ('.join(',', $childids).')'; - //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND x.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; - //if (!empty($socid)) $sql.= " AND x.fk_soc = ".$socid; - $sql .= $db->order("x.tms", "DESC"); - $sql .= $db->plimit($max, 0); + $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.email, u.photo, u.statut as user_status,"; + $sql .= " x.rowid, x.rowid as ref, x.fk_type, x.date_debut as date_start, x.date_fin as date_end, x.halfday, x.tms as dm, x.statut as status"; + $sql .= " FROM ".MAIN_DB_PREFIX."holiday as x, ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE u.rowid = x.fk_user"; + $sql .= " AND x.entity = ".$conf->entity; + if (empty($user->rights->holiday->read_all)) $sql .= ' AND x.fk_user IN ('.join(',', $childids).')'; + //if (!$user->rights->societe->client->voir && !$user->socid) $sql.= " AND x.fk_soc = s. rowid AND s.rowid = sc.fk_soc AND sc.fk_user = " .$user->id; + //if (!empty($socid)) $sql.= " AND x.fk_soc = ".$socid; + $sql .= $db->order("x.tms", "DESC"); + $sql .= $db->plimit($max, 0); - $result = $db->query($sql); - if ($result) - { - $var = false; - $num = $db->num_rows($result); + $result = $db->query($sql); + if ($result) + { + $var = false; + $num = $db->num_rows($result); - $holidaystatic = new Holiday($db); - $userstatic = new User($db); + $holidaystatic = new Holiday($db); + $userstatic = new User($db); - $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->trans("Afternoon")); - $typeleaves = $holidaystatic->getTypes(1, -1); + $listhalfday = array('morning'=>$langs->trans("Morning"), "afternoon"=>$langs->trans("Afternoon")); + $typeleaves = $holidaystatic->getTypes(1, -1); - $i = 0; + $i = 0; - print '
'; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - if ($num) - { - while ($i < $num && $i < $max) - { - $obj = $db->fetch_object($result); + print '
'; + print '
'.$langs->trans("BoxTitleLastLeaveRequests", min($max, $num)).''.$langs->trans("from").''.$langs->trans("to").''.$langs->trans("FullList").'
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + if ($num) + { + while ($i < $num && $i < $max) + { + $obj = $db->fetch_object($result); - $holidaystatic->id = $obj->rowid; - $holidaystatic->ref = $obj->ref; - $holidaystatic->statut = $obj->status; + $holidaystatic->id = $obj->rowid; + $holidaystatic->ref = $obj->ref; + $holidaystatic->statut = $obj->status; - $userstatic->id = $obj->uid; - $userstatic->lastname = $obj->lastname; - $userstatic->firstname = $obj->firstname; - $userstatic->login = $obj->login; - $userstatic->photo = $obj->photo; - $userstatic->email = $obj->email; - $userstatic->statut = $obj->user_status; + $userstatic->id = $obj->uid; + $userstatic->lastname = $obj->lastname; + $userstatic->firstname = $obj->firstname; + $userstatic->login = $obj->login; + $userstatic->photo = $obj->photo; + $userstatic->email = $obj->email; + $userstatic->statut = $obj->user_status; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning'; - $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon'; + $starthalfday = ($obj->halfday == -1 || $obj->halfday == 2) ? 'afternoon' : 'morning'; + $endhalfday = ($obj->halfday == 1 || $obj->halfday == 2) ? 'morning' : 'afternoon'; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - $i++; - } - } else { - print ''; - } - print '
'.$langs->trans("BoxTitleLastLeaveRequests", min($max, $num)).''.$langs->trans("from").''.$langs->trans("to").''.$langs->trans("FullList").'
'.$holidaystatic->getNomUrl(1).''.$userstatic->getNomUrl(-1, 'leave').''.$typeleaves[$obj->fk_type]['label'].'
'.$holidaystatic->getNomUrl(1).''.$userstatic->getNomUrl(-1, 'leave').''.$typeleaves[$obj->fk_type]['label'].''.dol_print_date($db->jdate($obj->date_start), 'day').' '.$langs->trans($listhalfday[$starthalfday]).''; - print ''.dol_print_date($db->jdate($obj->date_end), 'day').' '.$langs->trans($listhalfday[$endhalfday]).''; - print ''.dol_print_date($db->jdate($obj->dm), 'day').''.$holidaystatic->LibStatut($obj->status, 3).'
'.dol_print_date($db->jdate($obj->date_start), 'day').' '.$langs->trans($listhalfday[$starthalfday]).''; + print ''.dol_print_date($db->jdate($obj->date_end), 'day').' '.$langs->trans($listhalfday[$endhalfday]).''; + print ''.dol_print_date($db->jdate($obj->dm), 'day').''.$holidaystatic->LibStatut($obj->status, 3).'
'.$langs->trans("None").'
'; - print '
'; - print '
'; - } else dol_print_error($db); + $i++; + } + } else { + print ''.$langs->trans("None").''; + } + print ''; + print '
'; + print '
'; + } else dol_print_error($db); } @@ -298,7 +298,7 @@ if (!empty($conf->expensereport->enabled) && $user->rights->expensereport->lire) $userstatic->id = $obj->uid; $userstatic->lastname = $obj->lastname; $userstatic->firstname = $obj->firstname; - $userstatic->email = $obj->email; + $userstatic->email = $obj->email; $userstatic->login = $obj->login; $userstatic->statut = $obj->user_status; $userstatic->photo = $obj->photo; diff --git a/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php b/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php index 694263e2ec5..ea9eeed797d 100644 --- a/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php +++ b/htdocs/modulebuilder/template/core/modules/mymodule/doc/pdf_standard_myobject.modules.php @@ -43,82 +43,82 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php'; */ class pdf_standard_myobject extends ModelePDFMyObject { - /** - * @var DoliDb Database handler - */ - public $db; + /** + * @var DoliDb Database handler + */ + public $db; /** - * @var string model name - */ - public $name; + * @var string model name + */ + public $name; /** - * @var string model description (short text) - */ - public $description; - - /** - * @var int Save the name of generated file as the main doc when generating a doc with this template - */ - public $update_main_doc_field; + * @var string model description (short text) + */ + public $description; /** - * @var string document type - */ - public $type; + * @var int Save the name of generated file as the main doc when generating a doc with this template + */ + public $update_main_doc_field; /** - * @var array Minimum version of PHP required by module. - * e.g.: PHP ≥ 5.6 = array(5, 6) - */ + * @var string document type + */ + public $type; + + /** + * @var array Minimum version of PHP required by module. + * e.g.: PHP ≥ 5.6 = array(5, 6) + */ public $phpmin = array(5, 6); /** - * Dolibarr version of the loaded document - * @var string - */ + * Dolibarr version of the loaded document + * @var string + */ public $version = 'dolibarr'; - /** - * @var int page_largeur - */ - public $page_largeur; + /** + * @var int page_largeur + */ + public $page_largeur; /** - * @var int page_hauteur - */ - public $page_hauteur; + * @var int page_hauteur + */ + public $page_hauteur; /** - * @var array format - */ - public $format; + * @var array format + */ + public $format; /** - * @var int marge_gauche - */ + * @var int marge_gauche + */ public $marge_gauche; /** - * @var int marge_droite - */ + * @var int marge_droite + */ public $marge_droite; /** - * @var int marge_haute - */ + * @var int marge_haute + */ public $marge_haute; /** - * @var int marge_basse - */ + * @var int marge_basse + */ public $marge_basse; - /** - * Issuer - * @var Societe Object that emits - */ + /** + * Issuer + * @var Societe Object that emits + */ public $emetteur; /** @@ -182,50 +182,50 @@ class pdf_standard_myobject extends ModelePDFMyObject } - // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Function to build pdf onto disk - * - * @param Object $object Object to generate - * @param Translate $outputlangs Lang output object - * @param string $srctemplatepath Full path of source filename for generator using a template file - * @param int $hidedetails Do not show line details - * @param int $hidedesc Do not show desc - * @param int $hideref Do not show ref - * @return int 1=OK, 0=KO + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps + /** + * Function to build pdf onto disk + * + * @param Object $object Object to generate + * @param Translate $outputlangs Lang output object + * @param string $srctemplatepath Full path of source filename for generator using a template file + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return int 1=OK, 0=KO */ public function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) { - // phpcs:enable - global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; + // phpcs:enable + global $user, $langs, $conf, $mysoc, $db, $hookmanager, $nblines; - dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); + dol_syslog("write_file outputlangs->defaultlang=".(is_object($outputlangs) ? $outputlangs->defaultlang : 'null')); - if (!is_object($outputlangs)) $outputlangs = $langs; - // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO - if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; + if (!is_object($outputlangs)) $outputlangs = $langs; + // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO + if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1'; - // Load translation files required by the page - $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies")); + // Load translation files required by the page + $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies")); - if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { - global $outputlangsbis; - $outputlangsbis = new Translate('', $conf); - $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); - $outputlangsbis->loadLangs(array("main", "bills", "products", "dict", "companies")); - } + if (!empty($conf->global->PDF_USE_ALSO_LANGUAGE_CODE) && $outputlangs->defaultlang != $conf->global->PDF_USE_ALSO_LANGUAGE_CODE) { + global $outputlangsbis; + $outputlangsbis = new Translate('', $conf); + $outputlangsbis->setDefaultLang($conf->global->PDF_USE_ALSO_LANGUAGE_CODE); + $outputlangsbis->loadLangs(array("main", "bills", "products", "dict", "companies")); + } - $nblines = (is_array($object->lines) ? count($object->lines) : 0); + $nblines = (is_array($object->lines) ? count($object->lines) : 0); - $hidetop = 0; - if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) { - $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; - } + $hidetop = 0; + if (!empty($conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE)) { + $hidetop = $conf->global->MAIN_PDF_DISABLE_COL_HEAD_TITLE; + } - // Loop on each lines to detect if there is at least one image to show - $realpatharray = array(); - $this->atleastonephoto = false; - /* + // Loop on each lines to detect if there is at least one image to show + $realpatharray = array(); + $this->atleastonephoto = false; + /* if (!empty($conf->global->MAIN_GENERATE_MYOBJECT_WITH_PICTURE)) { $objphoto = new Product($this->db); @@ -278,528 +278,528 @@ class pdf_standard_myobject extends ModelePDFMyObject } */ - //if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; + //if (count($realpatharray) == 0) $this->posxpicture=$this->posxtva; - if ($conf->mymodule->dir_output.'/myobject') - { - $object->fetch_thirdparty(); + if ($conf->mymodule->dir_output.'/myobject') + { + $object->fetch_thirdparty(); - // Definition of $dir and $file - if ($object->specimen) - { - $dir = $conf->mymodule->dir_output.'/myobject'; - $file = $dir."/SPECIMEN.pdf"; - } else { - $objectref = dol_sanitizeFileName($object->ref); - $dir = $conf->mymodule->dir_output.'/myobject/'.$objectref; - $file = $dir."/".$objectref.".pdf"; - } - if (!file_exists($dir)) - { - if (dol_mkdir($dir) < 0) - { - $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); - return 0; - } - } + // Definition of $dir and $file + if ($object->specimen) + { + $dir = $conf->mymodule->dir_output.'/myobject'; + $file = $dir."/SPECIMEN.pdf"; + } else { + $objectref = dol_sanitizeFileName($object->ref); + $dir = $conf->mymodule->dir_output.'/myobject/'.$objectref; + $file = $dir."/".$objectref.".pdf"; + } + if (!file_exists($dir)) + { + if (dol_mkdir($dir) < 0) + { + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); + return 0; + } + } - if (file_exists($dir)) - { - // Add pdfgeneration hook - if (!is_object($hookmanager)) - { - include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; - $hookmanager = new HookManager($this->db); - } - $hookmanager->initHooks(array('pdfgeneration')); - $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); - global $action; - $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + if (file_exists($dir)) + { + // Add pdfgeneration hook + if (!is_object($hookmanager)) + { + include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php'; + $hookmanager = new HookManager($this->db); + } + $hookmanager->initHooks(array('pdfgeneration')); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + global $action; + $reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - // Set nblines with the new facture lines content after hook - $nblines = (is_array($object->lines) ? count($object->lines) : 0); + // Set nblines with the new facture lines content after hook + $nblines = (is_array($object->lines) ? count($object->lines) : 0); - // Create pdf instance - $pdf = pdf_getInstance($this->format); - $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance - $pdf->SetAutoPageBreak(1, 0); + // Create pdf instance + $pdf = pdf_getInstance($this->format); + $default_font_size = pdf_getPDFFontSize($outputlangs); // Must be after pdf_getInstance + $pdf->SetAutoPageBreak(1, 0); - $heightforinfotot = 50; // Height reserved to output the info and total part and payment part - $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page - $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) + $heightforinfotot = 50; // Height reserved to output the info and total part and payment part + $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page + $heightforfooter = $this->marge_basse + (empty($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS) ? 12 : 22); // Height reserved to output the footer (value include bottom margin) - if (class_exists('TCPDF')) - { - $pdf->setPrintHeader(false); - $pdf->setPrintFooter(false); - } - $pdf->SetFont(pdf_getPDFFont($outputlangs)); + if (class_exists('TCPDF')) + { + $pdf->setPrintHeader(false); + $pdf->setPrintFooter(false); + } + $pdf->SetFont(pdf_getPDFFont($outputlangs)); - // Set path to the background PDF File - if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) - { - $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); - $tplidx = $pdf->importPage(1); - } + // Set path to the background PDF File + if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND)) + { + $pagecount = $pdf->setSourceFile($conf->mycompany->multidir_output[$object->entity].'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND); + $tplidx = $pdf->importPage(1); + } - $pdf->Open(); - $pagenb = 0; - $pdf->SetDrawColor(128, 128, 128); + $pdf->Open(); + $pagenb = 0; + $pdf->SetDrawColor(128, 128, 128); - $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); - $pdf->SetSubject($outputlangs->transnoentities("PdfTitle")); - $pdf->SetCreator("Dolibarr ".DOL_VERSION); - $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); - $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); - if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref)); + $pdf->SetSubject($outputlangs->transnoentities("PdfTitle")); + $pdf->SetCreator("Dolibarr ".DOL_VERSION); + $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs))); + $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("PdfTitle")." ".$outputlangs->convToOutputCharset($object->thirdparty->name)); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); - // Set certificate - $cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT; - // If user has no certificate, we try to take the company one - if (!$cert) { - $cert = empty($conf->global->CERTIFICATE_CRT) ? '' : $conf->global->CERTIFICATE_CRT; - } - // If a certificate is found - if ($cert) { - $info = array( - 'Name' => $this->emetteur->name, - 'Location' => getCountry($this->emetteur->country_code, 0), - 'Reason' => 'MYOBJECT', - 'ContactInfo' => $this->emetteur->email - ); - $pdf->setSignature($cert, $cert, $this->emetteur->name, '', 2, $info); - } + // Set certificate + $cert = empty($user->conf->CERTIFICATE_CRT) ? '' : $user->conf->CERTIFICATE_CRT; + // If user has no certificate, we try to take the company one + if (!$cert) { + $cert = empty($conf->global->CERTIFICATE_CRT) ? '' : $conf->global->CERTIFICATE_CRT; + } + // If a certificate is found + if ($cert) { + $info = array( + 'Name' => $this->emetteur->name, + 'Location' => getCountry($this->emetteur->country_code, 0), + 'Reason' => 'MYOBJECT', + 'ContactInfo' => $this->emetteur->email + ); + $pdf->setSignature($cert, $cert, $this->emetteur->name, '', 2, $info); + } - $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right + $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right - // New page - $pdf->AddPage(); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - $pagenb++; + // New page + $pdf->AddPage(); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pagenb++; - $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); - $pdf->SetFont('', '', $default_font_size - 1); - $pdf->MultiCell(0, 3, ''); // Set interline to 3 - $pdf->SetTextColor(0, 0, 0); + $top_shift = $this->_pagehead($pdf, $object, 1, $outputlangs, $outputlangsbis); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->MultiCell(0, 3, ''); // Set interline to 3 + $pdf->SetTextColor(0, 0, 0); - $tab_top = 90 + $top_shift; - $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); - $tab_height = 130 - $top_shift; - $tab_height_newpage = 150; - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $tab_height_newpage -= $top_shift; + $tab_top = 90 + $top_shift; + $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 + $top_shift : 10); + $tab_height = 130 - $top_shift; + $tab_height_newpage = 150; + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $tab_height_newpage -= $top_shift; - $nexY = $tab_top - 1; + $nexY = $tab_top - 1; - // Display notes - $notetoshow = empty($object->note_public) ? '' : $object->note_public; - // Extrafields in note - $extranote = $this->getExtrafieldsInHtml($object, $outputlangs); - if (!empty($extranote)) - { - $notetoshow = dol_concatdesc($notetoshow, $extranote); - } + // Display notes + $notetoshow = empty($object->note_public) ? '' : $object->note_public; + // Extrafields in note + $extranote = $this->getExtrafieldsInHtml($object, $outputlangs); + if (!empty($extranote)) + { + $notetoshow = dol_concatdesc($notetoshow, $extranote); + } - $pagenb = $pdf->getPage(); - if ($notetoshow) - { + $pagenb = $pdf->getPage(); + if ($notetoshow) + { $tab_top -= 2; - $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; - $pageposbeforenote = $pagenb; + $tab_width = $this->page_largeur - $this->marge_gauche - $this->marge_droite; + $pageposbeforenote = $pagenb; - $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); - complete_substitutions_array($substitutionarray, $outputlangs, $object); - $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); - $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); + $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); + complete_substitutions_array($substitutionarray, $outputlangs, $object); + $notetoshow = make_substitutions($notetoshow, $substitutionarray, $outputlangs); + $notetoshow = convertBackOfficeMediasLinksToPublicLinks($notetoshow); - $pdf->startTransaction(); + $pdf->startTransaction(); - $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); - // Description - $pageposafternote = $pdf->getPage(); - $posyafter = $pdf->GetY(); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); + // Description + $pageposafternote = $pdf->getPage(); + $posyafter = $pdf->GetY(); - if ($pageposafternote > $pageposbeforenote) - { - $pdf->rollbackTransaction(true); + if ($pageposafternote > $pageposbeforenote) + { + $pdf->rollbackTransaction(true); - // prepare pages to receive notes - while ($pagenb < $pageposafternote) { - $pdf->AddPage(); - $pagenb++; - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - // $this->_pagefoot($pdf,$object,$outputlangs,1); - $pdf->setTopMargin($tab_top_newpage); - // The only function to edit the bottom margin of current page to set it. - $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); - } + // prepare pages to receive notes + while ($pagenb < $pageposafternote) { + $pdf->AddPage(); + $pagenb++; + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + // $this->_pagefoot($pdf,$object,$outputlangs,1); + $pdf->setTopMargin($tab_top_newpage); + // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); + } - // back to start - $pdf->setPage($pageposbeforenote); - $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); - $pdf->SetFont('', '', $default_font_size - 1); - $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); - $pageposafternote = $pdf->getPage(); + // back to start + $pdf->setPage($pageposbeforenote); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); + $pdf->SetFont('', '', $default_font_size - 1); + $pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top, dol_htmlentitiesbr($notetoshow), 0, 1); + $pageposafternote = $pdf->getPage(); - $posyafter = $pdf->GetY(); + $posyafter = $pdf->GetY(); - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) // There is no space left for total+free text - { - $pdf->AddPage('', '', true); - $pagenb++; - $pageposafternote++; - $pdf->setPage($pageposafternote); - $pdf->setTopMargin($tab_top_newpage); - // The only function to edit the bottom margin of current page to set it. - $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); - //$posyafter = $tab_top_newpage; - } + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) // There is no space left for total+free text + { + $pdf->AddPage('', '', true); + $pagenb++; + $pageposafternote++; + $pdf->setPage($pageposafternote); + $pdf->setTopMargin($tab_top_newpage); + // The only function to edit the bottom margin of current page to set it. + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext); + //$posyafter = $tab_top_newpage; + } - // apply note frame to previous pages - $i = $pageposbeforenote; - while ($i < $pageposafternote) { - $pdf->setPage($i); + // apply note frame to previous pages + $i = $pageposbeforenote; + while ($i < $pageposafternote) { + $pdf->setPage($i); - $pdf->SetDrawColor(128, 128, 128); - // Draw note frame - if ($i > $pageposbeforenote) { - $height_note = $this->page_hauteur - ($tab_top_newpage + $heightforfooter); - $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); - } else { - $height_note = $this->page_hauteur - ($tab_top + $heightforfooter); - $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); - } + $pdf->SetDrawColor(128, 128, 128); + // Draw note frame + if ($i > $pageposbeforenote) { + $height_note = $this->page_hauteur - ($tab_top_newpage + $heightforfooter); + $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); + } else { + $height_note = $this->page_hauteur - ($tab_top + $heightforfooter); + $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); + } - // Add footer - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. - $this->_pagefoot($pdf, $object, $outputlangs, 1); + // Add footer + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $this->_pagefoot($pdf, $object, $outputlangs, 1); - $i++; - } + $i++; + } - // apply note frame to last page - $pdf->setPage($pageposafternote); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $height_note = $posyafter - $tab_top_newpage; - $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); - } else // No pagebreak - { - $pdf->commitTransaction(); - $posyafter = $pdf->GetY(); - $height_note = $posyafter - $tab_top; - $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); + // apply note frame to last page + $pdf->setPage($pageposafternote); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + $height_note = $posyafter - $tab_top_newpage; + $pdf->Rect($this->marge_gauche, $tab_top_newpage - 1, $tab_width, $height_note + 1); + } else // No pagebreak + { + $pdf->commitTransaction(); + $posyafter = $pdf->GetY(); + $height_note = $posyafter - $tab_top; + $pdf->Rect($this->marge_gauche, $tab_top - 1, $tab_width, $height_note + 1); - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) - { - // not enough space, need to add page - $pdf->AddPage('', '', true); - $pagenb++; - $pageposafternote++; - $pdf->setPage($pageposafternote); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + 20))) + { + // not enough space, need to add page + $pdf->AddPage('', '', true); + $pagenb++; + $pageposafternote++; + $pdf->setPage($pageposafternote); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - $posyafter = $tab_top_newpage; - } - } + $posyafter = $tab_top_newpage; + } + } - $tab_height = $tab_height - $height_note; - $tab_top = $posyafter + 6; - } else { - $height_note = 0; - } + $tab_height = $tab_height - $height_note; + $tab_top = $posyafter + 6; + } else { + $height_note = 0; + } - // Use new auto column system - $this->prepareArrayColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); + // Use new auto column system + $this->prepareArrayColumnField($object, $outputlangs, $hidedetails, $hidedesc, $hideref); - // Table simulation to know the height of the title line - $pdf->startTransaction(); - $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); - $pdf->rollbackTransaction(true); + // Table simulation to know the height of the title line + $pdf->startTransaction(); + $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); + $pdf->rollbackTransaction(true); - $nexY = $tab_top + $this->tabTitleHeight; + $nexY = $tab_top + $this->tabTitleHeight; - // Loop on each lines - $pageposbeforeprintlines = $pdf->getPage(); - $pagenb = $pageposbeforeprintlines; - for ($i = 0; $i < $nblines; $i++) - { - $curY = $nexY; - $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage - $pdf->SetTextColor(0, 0, 0); + // Loop on each lines + $pageposbeforeprintlines = $pdf->getPage(); + $pagenb = $pageposbeforeprintlines; + for ($i = 0; $i < $nblines; $i++) + { + $curY = $nexY; + $pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage + $pdf->SetTextColor(0, 0, 0); - // Define size of image if we need it - $imglinesize = array(); - if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); + // Define size of image if we need it + $imglinesize = array(); + if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]); - $pdf->setTopMargin($tab_top_newpage); - $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. - $pageposbefore = $pdf->getPage(); + $pdf->setTopMargin($tab_top_newpage); + $pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it. + $pageposbefore = $pdf->getPage(); - $showpricebeforepagebreak = 1; - $posYAfterImage = 0; + $showpricebeforepagebreak = 1; + $posYAfterImage = 0; - if ($this->getColumnStatus('photo')) - { - // We start with Photo of product line - if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page - { - $pdf->AddPage('', '', true); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - $pdf->setPage($pageposbefore + 1); + if ($this->getColumnStatus('photo')) + { + // We start with Photo of product line + if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // If photo too high, we moved completely on new page + { + $pdf->AddPage('', '', true); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pdf->setPage($pageposbefore + 1); - $curY = $tab_top_newpage; + $curY = $tab_top_newpage; // Allows data in the first page if description is long enough to break in multiples pages if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; - } + } - if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) - { - $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi - // $pdf->Image does not increase value return by getY, so we save it manually - $posYAfterImage = $curY + $imglinesize['height']; - } - } + if (!empty($this->cols['photo']) && isset($imglinesize['width']) && isset($imglinesize['height'])) + { + $pdf->Image($realpatharray[$i], $this->getColumnContentXStart('photo'), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi + // $pdf->Image does not increase value return by getY, so we save it manually + $posYAfterImage = $curY + $imglinesize['height']; + } + } - // Description of product line - if ($this->getColumnStatus('desc')) - { - $pdf->startTransaction(); + // Description of product line + if ($this->getColumnStatus('desc')) + { + $pdf->startTransaction(); - $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); - $pageposafter = $pdf->getPage(); + $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); + $pageposafter = $pdf->getPage(); - if ($pageposafter > $pageposbefore) // There is a pagebreak - { - $pdf->rollbackTransaction(true); - $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. + if ($pageposafter > $pageposbefore) // There is a pagebreak + { + $pdf->rollbackTransaction(true); + $pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it. - $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); + $this->printColDescContent($pdf, $curY, 'desc', $object, $i, $outputlangs, $hideref, $hidedesc); - $pageposafter = $pdf->getPage(); - $posyafter = $pdf->GetY(); - //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; - if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text - { - if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page - { - $pdf->AddPage('', '', true); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - $pdf->setPage($pageposafter + 1); - } - } else { - // We found a page break + $pageposafter = $pdf->getPage(); + $posyafter = $pdf->GetY(); + //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit; + if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot))) // There is no space left for total+free text + { + if ($i == ($nblines - 1)) // No more lines, and no space left to show total, so we create a new page + { + $pdf->AddPage('', '', true); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pdf->setPage($pageposafter + 1); + } + } else { + // We found a page break // Allows data in the first page if description is long enough to break in multiples pages if (!empty($conf->global->MAIN_PDF_DATA_ON_FIRST_PAGE)) $showpricebeforepagebreak = 1; else $showpricebeforepagebreak = 0; - } - } else // No pagebreak - { - $pdf->commitTransaction(); - } - } + } + } else // No pagebreak + { + $pdf->commitTransaction(); + } + } - $nexY = $pdf->GetY(); - $pageposafter = $pdf->getPage(); - $pdf->setPage($pageposbefore); - $pdf->setTopMargin($this->marge_haute); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + $nexY = $pdf->GetY(); + $pageposafter = $pdf->getPage(); + $pdf->setPage($pageposbefore); + $pdf->setTopMargin($this->marge_haute); + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. - // We suppose that a too long description or photo were moved completely on next page - if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { - $pdf->setPage($pageposafter); $curY = $tab_top_newpage; - } + // We suppose that a too long description or photo were moved completely on next page + if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) { + $pdf->setPage($pageposafter); $curY = $tab_top_newpage; + } - $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut + $pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut - // Quantity - // Enough for 6 chars - if ($this->getColumnStatus('qty')) - { - $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); - $this->printStdColumnContent($pdf, $curY, 'qty', $qty); - $nexY = max($pdf->GetY(), $nexY); - } + // Quantity + // Enough for 6 chars + if ($this->getColumnStatus('qty')) + { + $qty = pdf_getlineqty($object, $i, $outputlangs, $hidedetails); + $this->printStdColumnContent($pdf, $curY, 'qty', $qty); + $nexY = max($pdf->GetY(), $nexY); + } - // Extrafields - if (!empty($object->lines[$i]->array_options)) { - foreach ($object->lines[$i]->array_options as $extrafieldColKey => $extrafieldValue) { - if ($this->getColumnStatus($extrafieldColKey)) - { - $extrafieldValue = $this->getExtrafieldContent($object->lines[$i], $extrafieldColKey); - $this->printStdColumnContent($pdf, $curY, $extrafieldColKey, $extrafieldValue); - $nexY = max($pdf->GetY(), $nexY); - } - } - } + // Extrafields + if (!empty($object->lines[$i]->array_options)) { + foreach ($object->lines[$i]->array_options as $extrafieldColKey => $extrafieldValue) { + if ($this->getColumnStatus($extrafieldColKey)) + { + $extrafieldValue = $this->getExtrafieldContent($object->lines[$i], $extrafieldColKey); + $this->printStdColumnContent($pdf, $curY, $extrafieldColKey, $extrafieldValue); + $nexY = max($pdf->GetY(), $nexY); + } + } + } - $parameters = array( - 'object' => $object, - 'i' => $i, - 'pdf' =>& $pdf, - 'curY' =>& $curY, - 'nexY' =>& $nexY, - 'outputlangs' => $outputlangs, - 'hidedetails' => $hidedetails - ); - $reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook + $parameters = array( + 'object' => $object, + 'i' => $i, + 'pdf' =>& $pdf, + 'curY' =>& $curY, + 'nexY' =>& $nexY, + 'outputlangs' => $outputlangs, + 'hidedetails' => $hidedetails + ); + $reshook = $hookmanager->executeHooks('printPDFline', $parameters, $this); // Note that $object may have been modified by hook - $sign = 1; - // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva - $prev_progress = $object->lines[$i]->get_prev_progress($object->id); - if ($prev_progress > 0 && !empty($object->lines[$i]->situation_percent)) // Compute progress from previous situation - { - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; - else $tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; - } else { - if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva; - else $tvaligne = $sign * $object->lines[$i]->total_tva; - } + $sign = 1; + // Collecte des totaux par valeur de tva dans $this->tva["taux"]=total_tva + $prev_progress = $object->lines[$i]->get_prev_progress($object->id); + if ($prev_progress > 0 && !empty($object->lines[$i]->situation_percent)) // Compute progress from previous situation + { + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; + else $tvaligne = $sign * $object->lines[$i]->total_tva * ($object->lines[$i]->situation_percent - $prev_progress) / $object->lines[$i]->situation_percent; + } else { + if ($conf->multicurrency->enabled && $object->multicurrency_tx != 1) $tvaligne = $sign * $object->lines[$i]->multicurrency_total_tva; + else $tvaligne = $sign * $object->lines[$i]->total_tva; + } - $localtax1ligne = $object->lines[$i]->total_localtax1; - $localtax2ligne = $object->lines[$i]->total_localtax2; - $localtax1_rate = $object->lines[$i]->localtax1_tx; - $localtax2_rate = $object->lines[$i]->localtax2_tx; - $localtax1_type = $object->lines[$i]->localtax1_type; - $localtax2_type = $object->lines[$i]->localtax2_type; + $localtax1ligne = $object->lines[$i]->total_localtax1; + $localtax2ligne = $object->lines[$i]->total_localtax2; + $localtax1_rate = $object->lines[$i]->localtax1_tx; + $localtax2_rate = $object->lines[$i]->localtax2_tx; + $localtax1_type = $object->lines[$i]->localtax1_type; + $localtax2_type = $object->lines[$i]->localtax2_type; - if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; - if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; - if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $tvaligne -= ($tvaligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax1ligne -= ($localtax1ligne * $object->remise_percent) / 100; + if ($object->remise_percent) $localtax2ligne -= ($localtax2ligne * $object->remise_percent) / 100; - $vatrate = (string) $object->lines[$i]->tva_tx; + $vatrate = (string) $object->lines[$i]->tva_tx; - // Retrieve type from database for backward compatibility with old records - if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined - && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax - { - $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); - $localtax1_type = $localtaxtmp_array[0]; - $localtax2_type = $localtaxtmp_array[2]; - } + // Retrieve type from database for backward compatibility with old records + if ((!isset($localtax1_type) || $localtax1_type == '' || !isset($localtax2_type) || $localtax2_type == '') // if tax type not defined + && (!empty($localtax1_rate) || !empty($localtax2_rate))) // and there is local tax + { + $localtaxtmp_array = getLocalTaxesFromRate($vatrate, 0, $object->thirdparty, $mysoc); + $localtax1_type = $localtaxtmp_array[0]; + $localtax2_type = $localtaxtmp_array[2]; + } - // retrieve global local tax - if ($localtax1_type && $localtax1ligne != 0) { - $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; - } - if ($localtax2_type && $localtax2ligne != 0) { - $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; - } + // retrieve global local tax + if ($localtax1_type && $localtax1ligne != 0) { + $this->localtax1[$localtax1_type][$localtax1_rate] += $localtax1ligne; + } + if ($localtax2_type && $localtax2ligne != 0) { + $this->localtax2[$localtax2_type][$localtax2_rate] += $localtax2ligne; + } - if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; - if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; - $this->tva[$vatrate] += $tvaligne; + if (($object->lines[$i]->info_bits & 0x01) == 0x01) $vatrate .= '*'; + if (!isset($this->tva[$vatrate])) $this->tva[$vatrate] = 0; + $this->tva[$vatrate] += $tvaligne; - $nexY = max($nexY, $posYAfterImage); + $nexY = max($nexY, $posYAfterImage); - // Add line - if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { - $pdf->setPage($pageposafter); - $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); - //$pdf->SetDrawColor(190,190,200); - $pdf->line($this->marge_gauche, $nexY, $this->page_largeur - $this->marge_droite, $nexY); - $pdf->SetLineStyle(array('dash'=>0)); - } + // Add line + if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblines - 1)) { + $pdf->setPage($pageposafter); + $pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80))); + //$pdf->SetDrawColor(190,190,200); + $pdf->line($this->marge_gauche, $nexY, $this->page_largeur - $this->marge_droite, $nexY); + $pdf->SetLineStyle(array('dash'=>0)); + } - // Detect if some page were added automatically and output _tableau for past pages - while ($pagenb < $pageposafter) { - $pdf->setPage($pagenb); - if ($pagenb == $pageposbeforeprintlines) { - $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code, $outputlangsbis); - } else { - $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); - } - $this->_pagefoot($pdf, $object, $outputlangs, 1); - $pagenb++; - $pdf->setPage($pagenb); - $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - } + // Detect if some page were added automatically and output _tableau for past pages + while ($pagenb < $pageposafter) { + $pdf->setPage($pagenb); + if ($pagenb == $pageposbeforeprintlines) { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code, $outputlangsbis); + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); + } + $this->_pagefoot($pdf, $object, $outputlangs, 1); + $pagenb++; + $pdf->setPage($pagenb); + $pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it. + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + } - if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { - if ($pagenb == $pageposafter) { - $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code, $outputlangsbis); - } else { - $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); - } - $this->_pagefoot($pdf, $object, $outputlangs, 1); - // New page - $pdf->AddPage(); - if (!empty($tplidx)) $pdf->useTemplate($tplidx); - $pagenb++; - if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); - } - } + if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak) { + if ($pagenb == $pageposafter) { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, $hidetop, 1, $object->multicurrency_code, $outputlangsbis); + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1, $object->multicurrency_code, $outputlangsbis); + } + $this->_pagefoot($pdf, $object, $outputlangs, 1); + // New page + $pdf->AddPage(); + if (!empty($tplidx)) $pdf->useTemplate($tplidx); + $pagenb++; + if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs); + } + } - // Show square - if ($pagenb == $pageposbeforeprintlines) - { - $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis); - $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; - } else { - $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code, $outputlangsbis); - $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; - } + // Show square + if ($pagenb == $pageposbeforeprintlines) + { + $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, $hidetop, 0, $object->multicurrency_code, $outputlangsbis); + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + } else { + $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0, $object->multicurrency_code, $outputlangsbis); + $bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1; + } - // Display infos area - //$posy = $this->drawInfoTable($pdf, $object, $bottomlasttab, $outputlangs); + // Display infos area + //$posy = $this->drawInfoTable($pdf, $object, $bottomlasttab, $outputlangs); - // Display total zone - //$posy = $this->drawTotalTable($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); + // Display total zone + //$posy = $this->drawTotalTable($pdf, $object, $deja_regle, $bottomlasttab, $outputlangs); - // Display payment area - /* + // Display payment area + /* if (($deja_regle || $amount_credit_notes_included || $amount_deposits_included) && empty($conf->global->INVOICE_NO_PAYMENT_DETAILS)) { $posy = $this->drawPaymentsTable($pdf, $object, $posy, $outputlangs); } */ - // Pagefoot - $this->_pagefoot($pdf, $object, $outputlangs); - if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); + // Pagefoot + $this->_pagefoot($pdf, $object, $outputlangs); + if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages(); - $pdf->Close(); + $pdf->Close(); - $pdf->Output($file, 'F'); + $pdf->Output($file, 'F'); - // Add pdfgeneration hook - $hookmanager->initHooks(array('pdfgeneration')); - $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); - global $action; - $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) - { - $this->error = $hookmanager->error; - $this->errors = $hookmanager->errors; - } + // Add pdfgeneration hook + $hookmanager->initHooks(array('pdfgeneration')); + $parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs); + global $action; + $reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks + if ($reshook < 0) + { + $this->error = $hookmanager->error; + $this->errors = $hookmanager->errors; + } - if (!empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); + if (!empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); - $this->result = array('fullpath'=>$file); + $this->result = array('fullpath'=>$file); - return 1; // No error - } else { - $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); - return 0; - } - } else { - $this->error = $langs->transnoentities("ErrorConstantNotDefined", "FAC_OUTPUTDIR"); - return 0; - } + return 1; // No error + } else { + $this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir); + return 0; + } + } else { + $this->error = $langs->transnoentities("ErrorConstantNotDefined", "FAC_OUTPUTDIR"); + return 0; + } } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -872,7 +872,7 @@ class pdf_standard_myobject extends ModelePDFMyObject $this->pdfTabTitles($pdf, $tab_top, $tab_height, $outputlangs, $hidetop); if (empty($hidetop)) { - $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter + $pdf->line($this->marge_gauche, $tab_top + $this->tabTitleHeight, $this->page_largeur - $this->marge_droite, $tab_top + $this->tabTitleHeight); // line takes a position y in 2nd parameter and 4th parameter } } @@ -900,9 +900,9 @@ class pdf_standard_myobject extends ModelePDFMyObject // Show Draft Watermark if ($object->statut == $object::STATUS_DRAFT && (!empty($conf->global->FACTURE_DRAFT_WATERMARK))) - { - pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); - } + { + pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->FACTURE_DRAFT_WATERMARK); + } $pdf->SetTextColor(0, 0, 60); $pdf->SetFont('', 'B', $default_font_size + 3); @@ -910,7 +910,7 @@ class pdf_standard_myobject extends ModelePDFMyObject $w = 110; $posy = $this->marge_haute; - $posx = $this->page_largeur - $this->marge_droite - $w; + $posx = $this->page_largeur - $this->marge_droite - $w; $pdf->SetXY($this->marge_gauche, $posy); @@ -929,7 +929,7 @@ class pdf_standard_myobject extends ModelePDFMyObject } if (is_readable($logo)) { - $height = pdf_getHeightForLogo($logo); + $height = pdf_getHeightForLogo($logo); $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto) } else { $pdf->SetTextColor(200, 0, 0); @@ -1022,16 +1022,16 @@ class pdf_standard_myobject extends ModelePDFMyObject // Get contact if (!empty($conf->global->DOC_SHOW_FIRST_SALES_REP)) { - $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); - if (count($arrayidcontact) > 0) - { - $usertmp = new User($this->db); - $usertmp->fetch($arrayidcontact[0]); - $posy += 4; - $pdf->SetXY($posx, $posy); - $pdf->SetTextColor(0, 0, 60); - $pdf->MultiCell($w, 3, $langs->transnoentities("SalesRepresentative")." : ".$usertmp->getFullName($langs), '', 'R'); - } + $arrayidcontact = $object->getIdContact('internal', 'SALESREPFOLL'); + if (count($arrayidcontact) > 0) + { + $usertmp = new User($this->db); + $usertmp->fetch($arrayidcontact[0]); + $posy += 4; + $pdf->SetXY($posx, $posy); + $pdf->SetTextColor(0, 0, 60); + $pdf->MultiCell($w, 3, $langs->transnoentities("SalesRepresentative")." : ".$usertmp->getFullName($langs), '', 'R'); + } } $posy += 1; @@ -1138,7 +1138,7 @@ class pdf_standard_myobject extends ModelePDFMyObject // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** * Show footer of page. Need this->emetteur object - * + * * @param TCPDF $pdf PDF * @param Object $object Object to show * @param Translate $outputlangs Object lang for output @@ -1157,28 +1157,28 @@ class pdf_standard_myobject extends ModelePDFMyObject * * @param object $object common object * @param Translate $outputlangs langs - * @param int $hidedetails Do not show line details - * @param int $hidedesc Do not show desc - * @param int $hideref Do not show ref - * @return null - */ - public function defineColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) - { - global $conf, $hookmanager; + * @param int $hidedetails Do not show line details + * @param int $hidedesc Do not show desc + * @param int $hideref Do not show ref + * @return null + */ + public function defineColumnField($object, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0) + { + global $conf, $hookmanager; - // Default field style for content - $this->defaultContentsFieldsStyle = array( - 'align' => 'R', // R,C,L - 'padding' => array(1, 0.5, 1, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ); + // Default field style for content + $this->defaultContentsFieldsStyle = array( + 'align' => 'R', // R,C,L + 'padding' => array(1, 0.5, 1, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ); - // Default field style for content - $this->defaultTitlesFieldsStyle = array( - 'align' => 'C', // R,C,L - 'padding' => array(0.5, 0, 0.5, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ); + // Default field style for content + $this->defaultTitlesFieldsStyle = array( + 'align' => 'C', // R,C,L + 'padding' => array(0.5, 0, 0.5, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ); - /* + /* * For exemple $this->cols['theColKey'] = array( 'rank' => $rank, // int : use for ordering columns @@ -1196,162 +1196,162 @@ class pdf_standard_myobject extends ModelePDFMyObject ); */ - $rank = 0; // do not use negative rank - $this->cols['desc'] = array( - 'rank' => $rank, - 'width' => false, // only for desc - 'status' => true, - 'title' => array( - 'textkey' => 'Designation', // use lang key is usefull in somme case with module - 'align' => 'L', - // 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label - // 'label' => ' ', // the final label - 'padding' => array(0.5, 0.5, 0.5, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - 'content' => array( - 'align' => 'L', - 'padding' => array(1, 0.5, 1, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - ); + $rank = 0; // do not use negative rank + $this->cols['desc'] = array( + 'rank' => $rank, + 'width' => false, // only for desc + 'status' => true, + 'title' => array( + 'textkey' => 'Designation', // use lang key is usefull in somme case with module + 'align' => 'L', + // 'textkey' => 'yourLangKey', // if there is no label, yourLangKey will be translated to replace label + // 'label' => ' ', // the final label + 'padding' => array(0.5, 0.5, 0.5, 0.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'content' => array( + 'align' => 'L', + 'padding' => array(1, 0.5, 1, 1.5), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + ); - // PHOTO - $rank = $rank + 10; - $this->cols['photo'] = array( - 'rank' => $rank, - 'width' => (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH), // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Photo', - 'label' => ' ' - ), - 'content' => array( - 'padding' => array(0, 0, 0, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left - ), - 'border-left' => false, // remove left line separator - ); + // PHOTO + $rank = $rank + 10; + $this->cols['photo'] = array( + 'rank' => $rank, + 'width' => (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH), // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Photo', + 'label' => ' ' + ), + 'content' => array( + 'padding' => array(0, 0, 0, 0), // Like css 0 => top , 1 => right, 2 => bottom, 3 => left + ), + 'border-left' => false, // remove left line separator + ); - if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) - { - $this->cols['photo']['status'] = true; - } + if (!empty($conf->global->MAIN_GENERATE_INVOICES_WITH_PICTURE) && !empty($this->atleastonephoto)) + { + $this->cols['photo']['status'] = true; + } - $rank = $rank + 10; - $this->cols['vat'] = array( - 'rank' => $rank, - 'status' => false, - 'width' => 16, // in mm - 'title' => array( - 'textkey' => 'VAT' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['vat'] = array( + 'rank' => $rank, + 'status' => false, + 'width' => 16, // in mm + 'title' => array( + 'textkey' => 'VAT' + ), + 'border-left' => true, // add left line separator + ); - if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) - { - $this->cols['vat']['status'] = true; - } + if (empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT) && empty($conf->global->MAIN_GENERATE_DOCUMENTS_WITHOUT_VAT_COLUMN)) + { + $this->cols['vat']['status'] = true; + } - $rank = $rank + 10; - $this->cols['subprice'] = array( - 'rank' => $rank, - 'width' => 19, // in mm - 'status' => true, - 'title' => array( - 'textkey' => 'PriceUHT' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['subprice'] = array( + 'rank' => $rank, + 'width' => 19, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'PriceUHT' + ), + 'border-left' => true, // add left line separator + ); - $rank = $rank + 10; - $this->cols['qty'] = array( - 'rank' => $rank, - 'width' => 16, // in mm - 'status' => true, - 'title' => array( - 'textkey' => 'Qty' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['qty'] = array( + 'rank' => $rank, + 'width' => 16, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'Qty' + ), + 'border-left' => true, // add left line separator + ); - $rank = $rank + 10; - $this->cols['progress'] = array( - 'rank' => $rank, - 'width' => 19, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Progress' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 10; + $this->cols['progress'] = array( + 'rank' => $rank, + 'width' => 19, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Progress' + ), + 'border-left' => true, // add left line separator + ); - if ($this->situationinvoice) - { - $this->cols['progress']['status'] = true; - } + if ($this->situationinvoice) + { + $this->cols['progress']['status'] = true; + } - $rank = $rank + 10; - $this->cols['unit'] = array( - 'rank' => $rank, - 'width' => 11, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'Unit' - ), - 'border-left' => true, // add left line separator - ); - if ($conf->global->PRODUCT_USE_UNITS) { - $this->cols['unit']['status'] = true; - } + $rank = $rank + 10; + $this->cols['unit'] = array( + 'rank' => $rank, + 'width' => 11, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'Unit' + ), + 'border-left' => true, // add left line separator + ); + if ($conf->global->PRODUCT_USE_UNITS) { + $this->cols['unit']['status'] = true; + } - $rank = $rank + 10; - $this->cols['discount'] = array( - 'rank' => $rank, - 'width' => 13, // in mm - 'status' => false, - 'title' => array( - 'textkey' => 'ReductionShort' - ), - 'border-left' => true, // add left line separator - ); - if ($this->atleastonediscount) { - $this->cols['discount']['status'] = true; - } + $rank = $rank + 10; + $this->cols['discount'] = array( + 'rank' => $rank, + 'width' => 13, // in mm + 'status' => false, + 'title' => array( + 'textkey' => 'ReductionShort' + ), + 'border-left' => true, // add left line separator + ); + if ($this->atleastonediscount) { + $this->cols['discount']['status'] = true; + } - $rank = $rank + 1000; // add a big offset to be sure is the last col because default extrafield rank is 100 - $this->cols['totalexcltax'] = array( - 'rank' => $rank, - 'width' => 26, // in mm - 'status' => true, - 'title' => array( - 'textkey' => 'TotalHT' - ), - 'border-left' => true, // add left line separator - ); + $rank = $rank + 1000; // add a big offset to be sure is the last col because default extrafield rank is 100 + $this->cols['totalexcltax'] = array( + 'rank' => $rank, + 'width' => 26, // in mm + 'status' => true, + 'title' => array( + 'textkey' => 'TotalHT' + ), + 'border-left' => true, // add left line separator + ); - // Add extrafields cols - if (!empty($object->lines)) { - $line = reset($object->lines); - $this->defineColumnExtrafield($line, $outputlangs, $hidedetails); - } + // Add extrafields cols + if (!empty($object->lines)) { + $line = reset($object->lines); + $this->defineColumnExtrafield($line, $outputlangs, $hidedetails); + } - $parameters = array( - 'object' => $object, - 'outputlangs' => $outputlangs, - 'hidedetails' => $hidedetails, - 'hidedesc' => $hidedesc, - 'hideref' => $hideref - ); + $parameters = array( + 'object' => $object, + 'outputlangs' => $outputlangs, + 'hidedetails' => $hidedetails, + 'hidedesc' => $hidedesc, + 'hideref' => $hideref + ); - $reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook - if ($reshook < 0) - { - setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - } elseif (empty($reshook)) - { - $this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys - } else { - $this->cols = $hookmanager->resArray; - } + $reshook = $hookmanager->executeHooks('defineColumnField', $parameters, $this); // Note that $object may have been modified by hook + if ($reshook < 0) + { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } elseif (empty($reshook)) + { + $this->cols = array_replace($this->cols, $hookmanager->resArray); // array_replace is used to preserve keys + } else { + $this->cols = $hookmanager->resArray; + } } } diff --git a/htdocs/mrp/mo_card.php b/htdocs/mrp/mo_card.php index add7de31b56..e20a57a6e4d 100644 --- a/htdocs/mrp/mo_card.php +++ b/htdocs/mrp/mo_card.php @@ -107,75 +107,75 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - $error = 0; + $error = 0; - $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); + $backurlforlist = dol_buildpath('/mrp/mo_list.php', 1); - if (empty($backtopage) || ($cancel && empty($id))) { - if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { - if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; - else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); - } - } - if ($cancel && !empty($backtopageforcancel)) { - $backtopage = $backtopageforcancel; - } + if (empty($backtopage) || ($cancel && empty($id))) { + if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) $backtopage = $backurlforlist; + else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); + } + } + if ($cancel && !empty($backtopageforcancel)) { + $backtopage = $backtopageforcancel; + } - $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record + $triggermodname = 'MRP_MO_MODIFY'; // Name of trigger action code to execute when we modify record - // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen - include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; + // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen + include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; - // Actions when linking object each other - include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; + // Actions when linking object each other + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; - // Actions when printing a doc from card - include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; - // Actions to send emails - $triggersendname = 'MO_SENTBYMAIL'; - $autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO'; - $trackid = 'mo'.$object->id; - include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; + // Actions to send emails + $triggersendname = 'MO_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_MO_TO'; + $trackid = 'mo'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - // Action to move up and down lines of object - //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once + // Action to move up and down lines of object + //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - if ($action == 'set_thirdparty' && $permissiontoadd) - { - $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); - } - if ($action == 'classin' && $permissiontoadd) - { - $object->setProject(GETPOST('projectid', 'int')); - } + if ($action == 'set_thirdparty' && $permissiontoadd) + { + $object->setValueFrom('fk_soc', GETPOST('fk_soc', 'int'), '', '', 'date', '', $user, 'MO_MODIFY'); + } + if ($action == 'classin' && $permissiontoadd) + { + $object->setProject(GETPOST('projectid', 'int')); + } - // Action close produced - if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) - { - $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED'); - if ($result >= 0) - { - // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { - $outputlangs = $langs; - $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) { - $outputlangs = new Translate("", $conf); - $outputlangs->setDefaultLang($newlang); - } - $model = $object->model_pdf; - $ret = $object->fetch($id); // Reload to get new records + // Action close produced + if ($action == 'confirm_produced' && $confirm == 'yes' && $permissiontoadd) + { + $result = $object->setStatut($object::STATUS_PRODUCED, 0, '', 'MRP_MO_PRODUCED'); + if ($result >= 0) + { + // Define output language + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + { + $outputlangs = $langs; + $newlang = ''; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $object->thirdparty->default_lang; + if (!empty($newlang)) { + $outputlangs = new Translate("", $conf); + $outputlangs->setDefaultLang($newlang); + } + $model = $object->model_pdf; + $ret = $object->fetch($id); // Reload to get new records - $object->generateDocument($model, $outputlangs, 0, 0, 0); - } - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } + $object->generateDocument($model, $outputlangs, 0, 0, 0); + } + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } } @@ -317,7 +317,7 @@ if (($id || $ref) && $action == 'edit') print load_fiche_titre($langs->trans("MO"), '', 'mrp'); print '
'; - print ''; + print ''; print ''; print ''; if ($backtopage) print ''; @@ -360,7 +360,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Confirmation to delete if ($action == 'delete') { - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteMo'), $langs->trans('ConfirmDeleteMo'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line if ($action == 'deleteline') @@ -439,32 +439,32 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Project if (!empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($permissiontoadd) - { - if ($action != 'classify') - $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= ''; - $morehtmlref .= $formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= ''; - $morehtmlref .= '
'; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= ' : '.$proj->getNomUrl(); - } else { - $morehtmlref .= ''; - } - } + $langs->load("projects"); + $morehtmlref .= '
'.$langs->trans('Project').' '; + if ($permissiontoadd) + { + if ($action != 'classify') + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref .= '
'; + $morehtmlref .= ''; + $morehtmlref .= ''; + $morehtmlref .= $formproject->select_projects($object->fk_soc, $object->fk_project, 'projectid', 0, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= ''; + $morehtmlref .= '
'; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_soc, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ' : '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } } $morehtmlref .= '
'; @@ -501,167 +501,167 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if (!empty($object->table_element_line)) { - // Show object lines + // Show object lines //$result = $object->getLinesArray(); $object->fetchLines(); - print '
+ print ' '; - /*if (!empty($conf->use_javascript_ajax) && $object->status == 0) { + /*if (!empty($conf->use_javascript_ajax) && $object->status == 0) { include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; }*/ - if (!empty($object->lines)) - { - print '
'; - print ''; + if (!empty($object->lines)) + { + print '
'; + print '
'; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print ''; - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; + print ''; - print '
'.$langs->trans("Summary").'
'.$langs->trans("Summary").'
'.$langs->trans("ProductsToConsume").''; - if (!empty($object->lines)) - { - $i = 0; - foreach ($object->lines as $line) { - if ($line->role == 'toconsume') { - if ($i) print ', '; - $tmpproduct = new Product($db); - $tmpproduct->fetch($line->fk_product); - print $tmpproduct->getNomUrl(1); - $i++; - } - } - } - print '
'.$langs->trans("ProductsToConsume").''; + if (!empty($object->lines)) + { + $i = 0; + foreach ($object->lines as $line) { + if ($line->role == 'toconsume') { + if ($i) print ', '; + $tmpproduct = new Product($db); + $tmpproduct->fetch($line->fk_product); + print $tmpproduct->getNomUrl(1); + $i++; + } + } + } + print '
'.$langs->trans("ProductsToProduce").''; - if (!empty($object->lines)) - { - $i = 0; - foreach ($object->lines as $line) { - if ($line->role == 'toproduce') { - if ($i) print ', '; - $tmpproduct = new Product($db); - $tmpproduct->fetch($line->fk_product); - print $tmpproduct->getNomUrl(1); - $i++; - } - } - } - print '
'.$langs->trans("ProductsToProduce").''; + if (!empty($object->lines)) + { + $i = 0; + foreach ($object->lines as $line) { + if ($line->role == 'toproduce') { + if ($i) print ', '; + $tmpproduct = new Product($db); + $tmpproduct->fetch($line->fk_product); + print $tmpproduct->getNomUrl(1); + $i++; + } + } + } + print '
'; - print '
'; - } + print ''; + print '
'; + } - print "\n"; + print "\n"; } // Buttons for actions if ($action != 'presend' && $action != 'editline') { - print '
'."\n"; - $parameters = array(); - $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + print '
'."\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); - if (empty($reshook)) - { - // Send - //if (empty($user->socid)) { - // print '' . $langs->trans('SendMail') . ''."\n"; - //} + if (empty($reshook)) + { + // Send + //if (empty($user->socid)) { + // print '' . $langs->trans('SendMail') . ''."\n"; + //} - // Back to draft - if ($object->status == $object::STATUS_VALIDATED) - { - if ($permissiontoadd) - { - // TODO Add test that production has not started - print ''.$langs->trans("SetToDraft").''; - } - } + // Back to draft + if ($object->status == $object::STATUS_VALIDATED) + { + if ($permissiontoadd) + { + // TODO Add test that production has not started + print ''.$langs->trans("SetToDraft").''; + } + } - // Modify - if ($object->status == $object::STATUS_DRAFT) { - if ($permissiontoadd) - { - print ''.$langs->trans("Modify").''."\n"; - } else { - print ''.$langs->trans('Modify').''."\n"; - } - } + // Modify + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) + { + print ''.$langs->trans("Modify").''."\n"; + } else { + print ''.$langs->trans('Modify').''."\n"; + } + } - // Validate - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { - if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) - { - print ''.$langs->trans("Validate").''; - } else { - $langs->load("errors"); - print ''.$langs->trans("Validate").''; - } - } - } + // Validate + if ($object->status == $object::STATUS_DRAFT) + { + if ($permissiontoadd) + { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) + { + print ''.$langs->trans("Validate").''; + } else { + $langs->load("errors"); + print ''.$langs->trans("Validate").''; + } + } + } - // Clone - if ($permissiontoadd) - { - print ''.$langs->trans("ToClone").''; - } + // Clone + if ($permissiontoadd) + { + print ''.$langs->trans("ToClone").''; + } - // Cancel - Reopen - if ($permissiontoadd) - { - if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) - { - $arrayproduced = $object->fetchLinesLinked('produced', 0); - $nbProduced = 0; - foreach ($arrayproduced as $lineproduced) { - $nbProduced += $lineproduced['qty']; - } - if ($nbProduced > 0) { // If production has started, we can close it - print ''.$langs->trans("Close").''."\n"; - } else { - print 'transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").''."\n"; - } + // Cancel - Reopen + if ($permissiontoadd) + { + if ($object->status == $object::STATUS_VALIDATED || $object->status == $object::STATUS_INPROGRESS) + { + $arrayproduced = $object->fetchLinesLinked('produced', 0); + $nbProduced = 0; + foreach ($arrayproduced as $lineproduced) { + $nbProduced += $lineproduced['qty']; + } + if ($nbProduced > 0) { // If production has started, we can close it + print ''.$langs->trans("Close").''."\n"; + } else { + print 'transnoentitiesnoconv("Production")).'">'.$langs->trans("Close").''."\n"; + } - print ''.$langs->trans("Cancel").''."\n"; - } + print ''.$langs->trans("Cancel").''."\n"; + } - if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED) - { - print ''.$langs->trans("ReOpen").''."\n"; - } - } + if ($object->status == $object::STATUS_PRODUCED || $object->status == $object::STATUS_CANCELED) + { + print ''.$langs->trans("ReOpen").''."\n"; + } + } - // Delete (need delete permission, or if draft, just need create/modify permission) - if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) - { - print ''.$langs->trans('Delete').''."\n"; - } else { - print ''.$langs->trans('Delete').''."\n"; - } - } - print '
'."\n"; + // Delete (need delete permission, or if draft, just need create/modify permission) + if ($permissiontodelete || ($object->status == $object::STATUS_DRAFT && $permissiontoadd)) + { + print ''.$langs->trans('Delete').''."\n"; + } else { + print ''.$langs->trans('Delete').''."\n"; + } + } + print '
'."\n"; } @@ -672,37 +672,37 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea if ($action != 'presend') { - print '
'; - print ''; // ancre + print '
'; + print ''; // ancre - // Documents - $objref = dol_sanitizeFileName($object->ref); - $relativepath = $objref.'/'.$objref.'.pdf'; - $filedir = $conf->mrp->dir_output.'/'.$objref; - $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed = $user->rights->mrp->read; // If you can read, you can build the PDF to read content - $delallowed = $user->rights->mrp->create; // If you can create/edit, you can remove a file on card - print $formfile->showdocuments('mrp:mo', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang); + // Documents + $objref = dol_sanitizeFileName($object->ref); + $relativepath = $objref.'/'.$objref.'.pdf'; + $filedir = $conf->mrp->dir_output.'/'.$objref; + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $user->rights->mrp->read; // If you can read, you can build the PDF to read content + $delallowed = $user->rights->mrp->create; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('mrp:mo', $objref, $filedir, $urlsource, $genallowed, $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', $mysoc->default_lang); - // Show links to link elements - $linktoelem = $form->showLinkToObjectBlock($object, null, array('mo')); - $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + // Show links to link elements + $linktoelem = $form->showLinkToObjectBlock($object, null, array('mo')); + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); - print '
'; + print '
'; - $MAXEVENT = 10; + $MAXEVENT = 10; - $morehtmlright = ''; - $morehtmlright .= $langs->trans("SeeAll"); - $morehtmlright .= ''; + $morehtmlright = ''; + $morehtmlright .= $langs->trans("SeeAll"); + $morehtmlright .= ''; - // List of actions on element - include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'mo', $socid, 1, '', $MAXEVENT, '', $morehtmlright); + // List of actions on element + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'mo', $socid, 1, '', $MAXEVENT, '', $morehtmlright); - print '
'; + print '
'; } //Select mail models is same action as presend diff --git a/htdocs/product/admin/dynamic_prices.php b/htdocs/product/admin/dynamic_prices.php index aafc36ca256..bdd86169466 100644 --- a/htdocs/product/admin/dynamic_prices.php +++ b/htdocs/product/admin/dynamic_prices.php @@ -42,17 +42,17 @@ if (!$user->admin) accessforbidden(); //Objects $price_globals = new PriceGlobalVariable($db); if ($action == 'edit_variable') { - $res = $price_globals->fetch($selection); - if ($res < 1) { - setEventMessages($price_globals->error, $price_globals->errors, 'errors'); - } + $res = $price_globals->fetch($selection); + if ($res < 1) { + setEventMessages($price_globals->error, $price_globals->errors, 'errors'); + } } $price_updaters = new PriceGlobalVariableUpdater($db); if ($action == 'edit_updater') { - $res = $price_updaters->fetch($selection); - if ($res < 1) { - setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); - } + $res = $price_updaters->fetch($selection); + if ($res < 1) { + setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); + } } @@ -61,84 +61,84 @@ if ($action == 'edit_updater') { */ if (!empty($action) && empty($cancel)) { - //Global variable actions - if ($action == 'create_variable' || $action == 'edit_variable') { - $price_globals->code = GETPOSTISSET('code') ?GETPOST('code', 'alpha') : $price_globals->code; - $price_globals->description = GETPOSTISSET('description') ?GETPOST('description', 'restricthtml') : $price_globals->description; - $price_globals->value = GETPOSTISSET('value') ?GETPOST('value', 'int') : $price_globals->value; - //Check if record already exists only when saving - if (!empty($save)) { - foreach ($price_globals->listGlobalVariables() as $entry) { - if ($price_globals->id != $entry->id && dol_strtolower($price_globals->code) == dol_strtolower($entry->code)) { - setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors'); - $save = null; - } - } - } - } - if ($action == 'create_variable' && !empty($save)) { - $res = $price_globals->create($user); - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_globals->error, $price_globals->errors, 'errors'); - } - } elseif ($action == 'edit_variable' && !empty($save)) { - $res = $price_globals->update($user); - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_globals->error, $price_globals->errors, 'errors'); - } - } elseif ($action == 'delete_variable') { - $res = $price_globals->delete($selection, $user); - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_globals->error, $price_globals->errors, 'errors'); - } - } + //Global variable actions + if ($action == 'create_variable' || $action == 'edit_variable') { + $price_globals->code = GETPOSTISSET('code') ?GETPOST('code', 'alpha') : $price_globals->code; + $price_globals->description = GETPOSTISSET('description') ?GETPOST('description', 'restricthtml') : $price_globals->description; + $price_globals->value = GETPOSTISSET('value') ?GETPOST('value', 'int') : $price_globals->value; + //Check if record already exists only when saving + if (!empty($save)) { + foreach ($price_globals->listGlobalVariables() as $entry) { + if ($price_globals->id != $entry->id && dol_strtolower($price_globals->code) == dol_strtolower($entry->code)) { + setEventMessages($langs->trans("ErrorRecordAlreadyExists"), null, 'errors'); + $save = null; + } + } + } + } + if ($action == 'create_variable' && !empty($save)) { + $res = $price_globals->create($user); + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_globals->error, $price_globals->errors, 'errors'); + } + } elseif ($action == 'edit_variable' && !empty($save)) { + $res = $price_globals->update($user); + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_globals->error, $price_globals->errors, 'errors'); + } + } elseif ($action == 'delete_variable') { + $res = $price_globals->delete($selection, $user); + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_globals->error, $price_globals->errors, 'errors'); + } + } - //Updaters actions - if ($action == 'create_updater' || $action == 'edit_updater') { - $price_updaters->type = GETPOSTISSET('type') ? GETPOST('type', 'int') : $price_updaters->type; - $price_updaters->description = GETPOSTISSET('description') ? GETPOST('description', 'restricthtml') : $price_updaters->description; - $price_updaters->parameters = GETPOSTISSET('parameters') ? GETPOST('parameters', 'alphanohtml') : $price_updaters->parameters; - $price_updaters->fk_variable = GETPOSTISSET('fk_variable') ? GETPOST('fk_variable', 'int') : $price_updaters->fk_variable; - $price_updaters->update_interval = GETPOSTISSET('update_interval') ? GETPOST('update_interval', 'int') : $price_updaters->update_interval; - } - if ($action == 'create_updater' && !empty($save)) { - //Verify if process() works - $res = $price_updaters->process(); - if ($res > 0) { - $res = $price_updaters->create($user); - } - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); - } - } elseif ($action == 'edit_updater' && !empty($save)) { - //Verify if process() works - $res = $price_updaters->process(); - if ($res > 0) { - $res = $price_updaters->update($user); - } - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); - } - } elseif ($action == 'delete_updater') { - $res = $price_updaters->delete($selection, $user); - if ($res > 0) { - $action = ''; - } else { - setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); - } - } + //Updaters actions + if ($action == 'create_updater' || $action == 'edit_updater') { + $price_updaters->type = GETPOSTISSET('type') ? GETPOST('type', 'int') : $price_updaters->type; + $price_updaters->description = GETPOSTISSET('description') ? GETPOST('description', 'restricthtml') : $price_updaters->description; + $price_updaters->parameters = GETPOSTISSET('parameters') ? GETPOST('parameters', 'alphanohtml') : $price_updaters->parameters; + $price_updaters->fk_variable = GETPOSTISSET('fk_variable') ? GETPOST('fk_variable', 'int') : $price_updaters->fk_variable; + $price_updaters->update_interval = GETPOSTISSET('update_interval') ? GETPOST('update_interval', 'int') : $price_updaters->update_interval; + } + if ($action == 'create_updater' && !empty($save)) { + //Verify if process() works + $res = $price_updaters->process(); + if ($res > 0) { + $res = $price_updaters->create($user); + } + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); + } + } elseif ($action == 'edit_updater' && !empty($save)) { + //Verify if process() works + $res = $price_updaters->process(); + if ($res > 0) { + $res = $price_updaters->update($user); + } + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); + } + } elseif ($action == 'delete_updater') { + $res = $price_updaters->delete($selection, $user); + if ($res > 0) { + $action = ''; + } else { + setEventMessages($price_updaters->error, $price_updaters->errors, 'errors'); + } + } } elseif (!empty($cancel)) { - $action = ''; + $action = ''; } @@ -159,171 +159,171 @@ print '
'; //Global variables table if ($action != 'create_updater' && $action != 'edit_updater') { - print load_fiche_titre($langs->trans("GlobalVariables"), '', ''); + print load_fiche_titre($langs->trans("GlobalVariables"), '', ''); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; //Space for buttons - print ''; + print '
'.$langs->trans("Variable").''.$langs->trans("Description").''.$langs->trans("Value").' 
'; + print ''; + print ''; + print ''; + print ''; + print ''; //Space for buttons + print ''; - $arrayglobalvars = $price_globals->listGlobalVariables(); - if (!empty($arrayglobalvars)) - { - foreach ($arrayglobalvars as $i=>$entry) { - $var = !$var; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - } - } else { - print ''; - } - print '
'.$langs->trans("Variable").''.$langs->trans("Description").''.$langs->trans("Value").' 
'.$entry->code.''.$entry->description.''.price($entry->value).'id.'">'.img_edit().'  '; - print 'id.'">'.img_delete().'
'; - print $langs->trans("None"); - print '
'; + $arrayglobalvars = $price_globals->listGlobalVariables(); + if (!empty($arrayglobalvars)) + { + foreach ($arrayglobalvars as $i=>$entry) { + $var = !$var; + print ''; + print ''.$entry->code.''; + print ''.$entry->description.''; + print ''.price($entry->value).''; + print 'id.'">'.img_edit().'  '; + print 'id.'">'.img_delete().''; + print ''; + } + } else { + print ''; + print $langs->trans("None"); + print ''; + } + print ''; - if (empty($action)) - { - //Action Buttons - print '
'; - print ''.$langs->trans("AddVariable").''; - print '
'; - //Separator is only need for updaters table is showed after buttons - print '

'; - } + if (empty($action)) + { + //Action Buttons + print '
'; + print ''.$langs->trans("AddVariable").''; + print '
'; + //Separator is only need for updaters table is showed after buttons + print '

'; + } } //Global variable editor if ($action == 'create_variable' || $action == 'edit_variable') { - //Form - print '
'; - print ''; - print ''; - print ''; + //Form + print ''; + print ''; + print ''; + print ''; - //Table - print '
'; - //Code - print ''; - print ''; - print ''; - print ''; - //Description - print ''; - print ''; - print ''; - print ''; - //Value - print ''; - print ''; - print ''; - print ''; - print '
'.$langs->trans("Variable").'
'.$langs->trans("Description").'
'.$langs->trans("Value").'
'; + //Table + print '
'; + //Code + print ''; + print ''; + print ''; + print ''; + //Description + print ''; + print ''; + print ''; + print ''; + //Value + print ''; + print ''; + print ''; + print ''; + print '
'.$langs->trans("Variable").'
'.$langs->trans("Description").'
'.$langs->trans("Value").'
'; - //Form Buttons - print '
'; - print '  '; - print ''; - print '
'; - print '
'; + //Form Buttons + print '
'; + print '  '; + print ''; + print '
'; + print ''; } // Updaters table if ($action != 'create_variable' && $action != 'edit_variable') { - print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', ''); + print load_fiche_titre($langs->trans("GlobalVariableUpdaters"), '', ''); - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; //Space for buttons - print ''; + print '
'.$langs->trans("VariableToUpdate").''.$langs->trans("Description").''.$langs->trans("Type").''.$langs->trans("Parameters").''.$langs->trans("UpdateInterval").''.$langs->trans("LastUpdated").' 
'; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; + print ''; //Space for buttons + print ''; - $arraypriceupdaters = $price_updaters->listUpdaters(); - if (!empty($arraypriceupdaters)) - { - foreach ($arraypriceupdaters as $i=>$entry) { - $code = ""; - if ($entry->fk_variable > 0) { - $res = $price_globals->fetch($entry->fk_variable); - if ($res > 0) { - $code = $price_globals->code; - } - } - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - } - } else { - print ''; - } - print '
'.$langs->trans("VariableToUpdate").''.$langs->trans("Description").''.$langs->trans("Type").''.$langs->trans("Parameters").''.$langs->trans("UpdateInterval").''.$langs->trans("LastUpdated").' 
'.$code.''.$entry->description.''.$langs->trans("GlobalVariableUpdaterType".$entry->type).''.$entry->parameters.''.$entry->update_interval.''.$entry->getLastUpdated().'id.'">'.img_edit().'  '; - print 'id.'">'.img_delete().'
'; - print $langs->trans("None"); - print '
'; + $arraypriceupdaters = $price_updaters->listUpdaters(); + if (!empty($arraypriceupdaters)) + { + foreach ($arraypriceupdaters as $i=>$entry) { + $code = ""; + if ($entry->fk_variable > 0) { + $res = $price_globals->fetch($entry->fk_variable); + if ($res > 0) { + $code = $price_globals->code; + } + } + print ''; + print ''.$code.''; + print ''.$entry->description.''; + print ''.$langs->trans("GlobalVariableUpdaterType".$entry->type).''; + print ''.$entry->parameters.''; + print ''.$entry->update_interval.''; + print ''.$entry->getLastUpdated().''; + print 'id.'">'.img_edit().'  '; + print 'id.'">'.img_delete().''; + print ''; + } + } else { + print ''; + print $langs->trans("None"); + print ''; + } + print ''; - if (empty($action)) - { - //Action Buttons - print '
'; - print ''.$langs->trans("AddUpdater").''; - print '
'; - } + if (empty($action)) + { + //Action Buttons + print '
'; + print ''.$langs->trans("AddUpdater").''; + print '
'; + } } //Updater editor if ($action == 'create_updater' || $action == 'edit_updater') { - //Form - print '
'; - print ''; - print ''; - print ''; + //Form + print ''; + print ''; + print ''; + print ''; - //Table - print '
'; - //Code - print ''; - print ''; - //Description - print ''; - print ''; - print ''; - print ''; - //Type - print ''; - print ''; - //Parameters - print ''; - $help = $langs->trans("GlobalVariableUpdaterHelp".$type).'
'.$langs->trans("GlobalVariableUpdaterHelpFormat".$type).''; - print ''; - print ''; - //Interval - print ''; - print ''; - print ''; - print ''; - print '
'.$langs->trans("VariableToUpdate").''; - $globals_list = array(); - foreach ($price_globals->listGlobalVariables() as $entry) { - $globals_list[$entry->id] = $entry->code; - } - print $form->selectarray('fk_variable', $globals_list, (empty($price_updaters->fk_variable) ? 0 : $price_updaters->fk_variable)); - print '
'.$langs->trans("Description").'
'.$langs->trans("Type").''; - $type = empty($price_updaters->type) ? 0 : $price_updaters->type; - $type_list = array(); - foreach ($price_updaters->types as $val) { - $type_list[$val] = $langs->trans("GlobalVariableUpdaterType".$val); - } - print $form->selectarray('type', $type_list, $type); - // This code submits form when type is changed - print ''; - print '
'.$form->textwithpicto($langs->trans("Parameters"), $help, 1).''; - require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; - $doleditor = new DolEditor('parameters', empty($price_updaters->parameters) ? '' : $price_updaters->parameters, '', 300, '', '', false, false, false, ROWS_8, '90%'); - $doleditor->Create(); - print '
'.$langs->trans("UpdateInterval").'
'; + print ''; + //Parameters + print ''; + $help = $langs->trans("GlobalVariableUpdaterHelp".$type).'
'.$langs->trans("GlobalVariableUpdaterHelpFormat".$type).''; + print ''.$form->textwithpicto($langs->trans("Parameters"), $help, 1).''; + require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; + $doleditor = new DolEditor('parameters', empty($price_updaters->parameters) ? '' : $price_updaters->parameters, '', 300, '', '', false, false, false, ROWS_8, '90%'); + $doleditor->Create(); + print ''; + print ''; + //Interval + print ''; + print ''.$langs->trans("UpdateInterval").''; + print ''; + print ''; + print ''; - //Form Buttons - print '
'; - print '  '; - print ''; - print '
'; - print '
'; + //Form Buttons + print '
'; + print '  '; + print ''; + print '
'; + print ''; } // End of page diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 4970679eb87..e3467e871c8 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -301,8 +301,8 @@ if (empty($reshook)) $object->note_private = dol_htmlcleanlastbr(GETPOST('note_private', 'restricthtml')); $object->note = $object->note_private; // deprecated $object->customcode = GETPOST('customcode', 'alphanohtml'); - $object->country_id = GETPOST('country_id', 'int'); - $object->state_id = GETPOST('state_id', 'int'); + $object->country_id = GETPOST('country_id', 'int'); + $object->state_id = GETPOST('state_id', 'int'); $object->duration_value = $duration_value; $object->duration_unit = $duration_unit; $object->fk_default_warehouse = GETPOST('fk_default_warehouse'); @@ -965,14 +965,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $linkback = ""; print load_fiche_titre($title, $linkback, $picto); - // We set country_id, country_code and country for the selected country - $object->country_id = GETPOSTISSET('country_id') ? GETPOST('country_id', 'int') : null; - if ($object->country_id > 0) - { - $tmparray = getCountry($object->country_id, 'all'); - $object->country_code = $tmparray['code']; - $object->country = $tmparray['label']; - } + // We set country_id, country_code and country for the selected country + $object->country_id = GETPOSTISSET('country_id') ? GETPOST('country_id', 'int') : null; + if ($object->country_id > 0) + { + $tmparray = getCountry($object->country_id, 'all'); + $object->country_code = $tmparray['code']; + $object->country = $tmparray['label']; + } dol_fiche_head(''); @@ -1151,26 +1151,26 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Origin country print ''.$langs->trans("CountryOrigin").''; print ''; - 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 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 ''; - // State - if (empty($conf->global->PRODUCT_DISABLE_STATE)) - { - if ($conf->browser->layout == 'phone') print ''; - 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-StateOrigine', 'state_id', '', $object, 0).''; - } else { - print ''.$form->editfieldkey('StateOrigin', 'state_id', '', $object, 0).''; - } + // State + if (empty($conf->global->PRODUCT_DISABLE_STATE)) + { + if ($conf->browser->layout == 'phone') print ''; + 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-StateOrigine', 'state_id', '', $object, 0).''; + } else { + print ''.$form->editfieldkey('StateOrigin', 'state_id', '', $object, 0).''; + } print $formcompany->select_state($object->state_id, $object->country_code); - print ''; - } - print ''; + print ''; + } + print ''; } // Other attributes @@ -1616,7 +1616,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // State if (empty($conf->global->PRODUCT_DISABLE_STATE)) { - if ($conf->browser->layout == 'phone') print ''; + if ($conf->browser->layout == 'phone') print ''; 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-StateOrigine', 'state_id', '', $object, 0).''; @@ -2389,7 +2389,7 @@ if ($action != 'create' && $action != 'edit' && $action != 'delete') $objectref = dol_sanitizeFileName($object->ref); $relativepath = $comref.'/'.$objectref.'.pdf'; if (!empty($conf->product->multidir_output[$object->entity])) { - $filedir = $conf->product->multidir_output[$object->entity].'/'.$objectref; //Check repertories of current entities + $filedir = $conf->product->multidir_output[$object->entity].'/'.$objectref; //Check repertories of current entities } else { $filedir = $conf->product->dir_output.'/'.$objectref; } diff --git a/htdocs/product/class/productcustomerprice.class.php b/htdocs/product/class/productcustomerprice.class.php index 1553869d1f1..25a3c5cd836 100644 --- a/htdocs/product/class/productcustomerprice.class.php +++ b/htdocs/product/class/productcustomerprice.class.php @@ -368,7 +368,7 @@ class Productcustomerprice extends CommonObject } elseif ($key == 'prod.ref' || $key == 'prod.label') { $sql .= ' AND '.$key.' LIKE \'%'.$this->db->escape($value).'%\''; } elseif ($key == 't.price' || $key == 't.price_ttc') { - $sql .= ' AND ' . $key . ' LIKE \'%' . price2num($value) . '%\''; + $sql .= ' AND '.$key.' LIKE \'%'.price2num($value).'%\''; } else { $sql .= ' AND '.$key.' = '.((int) $value); } diff --git a/htdocs/product/price.php b/htdocs/product/price.php index 847292fa367..c97e22b9166 100644 --- a/htdocs/product/price.php +++ b/htdocs/product/price.php @@ -90,94 +90,94 @@ if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'e if (empty($reshook)) { - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { - $search_soc = ''; - } + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers + { + $search_soc = ''; + } - if ($action == 'setlabelsellingprice' && $user->admin) - { - require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; - $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.GETPOST('pricelevel'); - dolibarr_set_const($db, $keyforlabel, GETPOST('labelsellingprice', 'alpha'), 'chaine', 0, '', $conf->entity); - $action = ''; - } + if ($action == 'setlabelsellingprice' && $user->admin) + { + require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; + $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.GETPOST('pricelevel'); + dolibarr_set_const($db, $keyforlabel, GETPOST('labelsellingprice', 'alpha'), 'chaine', 0, '', $conf->entity); + $action = ''; + } if (($action == 'update_vat') && !$cancel && ($user->rights->produit->creer || $user->rights->service->creer)) { - $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' + $tva_tx_txt = GETPOST('tva_tx', 'alpha'); // tva_tx can be '8.5' or '8.5*' or '8.5 (XXX)' or '8.5* (XXX)' - // We must define tva_tx, npr and local taxes - $tva_tx = $tva_tx_txt; - $vatratecode = ''; - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { - $vat_src_code = $reg[1]; - $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. - } + // We must define tva_tx, npr and local taxes + $tva_tx = $tva_tx_txt; + $vatratecode = ''; + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) + { + $vat_src_code = $reg[1]; + $tva_tx = preg_replace('/\s*\(.*\)/', '', $tva_tx_txt); // Remove code into vatrate. + } - $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot - $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; - $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; - // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { - // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in create product. - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; - } - } + $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot + $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; + $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; + // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) + { + // We look into database using code (we can't use get_localtax() because it depends on buyer that is not known). Same in create product. + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; + } + } - $object->default_vat_code = $vatratecode; - $object->tva_tx = $tva_tx; - $object->tva_npr = $npr; - $object->localtax1_tx = $localtax1; - $object->localtax2_tx = $localtax2; - $object->localtax1_type = $localtax1_type; - $object->localtax2_type = $localtax2_type; + $object->default_vat_code = $vatratecode; + $object->tva_tx = $tva_tx; + $object->tva_npr = $npr; + $object->localtax1_tx = $localtax1; + $object->localtax2_tx = $localtax2; + $object->localtax1_type = $localtax1_type; + $object->localtax2_type = $localtax2_type; - $db->begin(); + $db->begin(); - $resql = $object->update($object->id, $user); - if ($resql <= 0) - { - $error++; - setEventMessages($object->error, $object->errors, 'errors'); - } + $resql = $object->update($object->id, $user); + if ($resql <= 0) + { + $error++; + setEventMessages($object->error, $object->errors, 'errors'); + } - if ($error) - { - //$localtaxarray=array('0'=>$localtax1_type,'1'=>$localtax1,'2'=>$localtax2_type,'3'=>$localtax2); - $localtaxarray = array(); // We do not store localtaxes into product, we will use instead the "vat code" to retreive them. - $object->updatePrice(0, $object->price_base_type, $user, $tva_tx, '', 0, $npr, 0, 0, $localtaxarray, $vatratecode); - } + if ($error) + { + //$localtaxarray=array('0'=>$localtax1_type,'1'=>$localtax1,'2'=>$localtax2_type,'3'=>$localtax2); + $localtaxarray = array(); // We do not store localtaxes into product, we will use instead the "vat code" to retreive them. + $object->updatePrice(0, $object->price_base_type, $user, $tva_tx, '', 0, $npr, 0, 0, $localtaxarray, $vatratecode); + } - if (!$error) - { - $db->commit(); - } else { - $db->rollback(); - } + if (!$error) + { + $db->commit(); + } else { + $db->rollback(); + } - $action = ''; + $action = ''; } if (($action == 'update_price') && !$cancel && $object->getRights()->creer) - { + { $error = 0; $pricestoupdate = array(); @@ -231,41 +231,41 @@ if (empty($reshook)) } $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot - $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; + $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; $localtax1 = $newlocaltax1_tx[$i]; $localtax1_type = $newlocaltax1_type[$i]; $localtax2 = $newlocaltax2_tx[$i]; $localtax2_type = $newlocaltax2_type[$i]; - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { - // We look into database using code - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; - } - } + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) + { + // We look into database using code + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".((float) $tva_tx)." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; + } + } $pricestoupdate[$i] = array( 'price' => $newprice[$i], 'price_min' => $newprice_min[$i], 'price_base_type' => $newpricebase[$i], - 'default_vat_code' => $vatratecode, + 'default_vat_code' => $vatratecode, 'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future 'npr' => $npr, // default_vat_code should be used in priority in a future - 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future + 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future ); //If autogeneration is enabled, then we only set the first level @@ -286,45 +286,45 @@ if (empty($reshook)) } $tva_tx = price2num(preg_replace('/\*/', '', $tva_tx)); // keep remove all after the numbers and dot - $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; - $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; - // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes - if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) - { - // We look into database using code - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; + $npr = preg_match('/\*/', $tva_tx_txt) ? 1 : 0; + $localtax1 = 0; $localtax2 = 0; $localtax1_type = '0'; $localtax2_type = '0'; + // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes + if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) + { + // We look into database using code + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; - // If spain, we don't use the localtax found into tax record in database with same code, but using the get_localtax rule - if (in_array($mysoc->country_code, array('ES'))) - { - $localtax1 = get_localtax($tva_tx, 1); - $localtax2 = get_localtax($tva_tx, 2); - } - } - } + // If spain, we don't use the localtax found into tax record in database with same code, but using the get_localtax rule + if (in_array($mysoc->country_code, array('ES'))) + { + $localtax1 = get_localtax($tva_tx, 1); + $localtax2 = get_localtax($tva_tx, 2); + } + } + } $pricestoupdate[0] = array( 'price' => $_POST["price"], 'price_min' => $_POST["price_min"], 'price_base_type' => $_POST["price_base_type"], - 'default_vat_code' => $vatratecode, + 'default_vat_code' => $vatratecode, 'vat_tx' => $tva_tx, // default_vat_code should be used in priority in a future 'npr' => $npr, // default_vat_code should be used in priority in a future - 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future + 'localtaxes_array' => array('0'=>$localtax1_type, '1'=>$localtax1, '2'=>$localtax2_type, '3'=>$localtax2) // default_vat_code should be used in priority in a future ); } @@ -348,7 +348,7 @@ if (empty($reshook)) } if ($object->multiprices[$key] != $newprice || $object->multiprices_min[$key] != $newprice_min || $object->multiprices_base_type[$key] != $val['price_base_type']) - $res = $object->updatePrice($newprice, $val['price_base_type'], $user, $val['vat_tx'], $newprice_min, $key, $val['npr'], $psq, 0, $val['localtaxes_array'], $val['default_vat_code']); + $res = $object->updatePrice($newprice, $val['price_base_type'], $user, $val['vat_tx'], $newprice_min, $key, $val['npr'], $psq, 0, $val['localtaxes_array'], $val['default_vat_code']); else $res = 0; @@ -520,24 +520,24 @@ if (empty($reshook)) // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { - // We look into database using code - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; - } + // We look into database using code + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; + } } $prodcustprice->default_vat_code = $vatratecode; @@ -550,14 +550,14 @@ if (empty($reshook)) if (!($prodcustprice->fk_soc > 0)) { - $langs->load("errors"); - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors'); - $error++; - $action = 'add_customer_price'; + $langs->load("errors"); + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors'); + $error++; + $action = 'add_customer_price'; } if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE) && $prodcustprice->price_min < $maxpricesupplier) { - $langs->load("errors"); + $langs->load("errors"); setEventMessages($langs->trans("MinimumPriceLimit", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')), null, 'errors'); $error++; $action = 'add_customer_price'; @@ -620,24 +620,24 @@ if (empty($reshook)) // If value contains the unique code of vat line (new recommanded method), we use it to find npr and local taxes if (preg_match('/\((.*)\)/', $tva_tx_txt, $reg)) { - // We look into database using code - $vatratecode = $reg[1]; - // Get record from code - $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; - $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; - $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; - $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; - $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - $npr = $obj->recuperableonly; - $localtax1 = $obj->localtax1; - $localtax2 = $obj->localtax2; - $localtax1_type = $obj->localtax1_type; - $localtax2_type = $obj->localtax2_type; - } + // We look into database using code + $vatratecode = $reg[1]; + // Get record from code + $sql = "SELECT t.rowid, t.code, t.recuperableonly, t.localtax1, t.localtax2, t.localtax1_type, t.localtax2_type"; + $sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c"; + $sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$db->escape($mysoc->country_code)."'"; + $sql .= " AND t.taux = ".$tva_tx." AND t.active = 1"; + $sql .= " AND t.code ='".$db->escape($vatratecode)."'"; + $resql = $db->query($sql); + if ($resql) + { + $obj = $db->fetch_object($resql); + $npr = $obj->recuperableonly; + $localtax1 = $obj->localtax1; + $localtax2 = $obj->localtax2; + $localtax1_type = $obj->localtax1_type; + $localtax2_type = $obj->localtax2_type; + } } $prodcustprice->default_vat_code = $vatratecode; @@ -770,22 +770,22 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ //print vatrate($object->multiprices_tva_tx[$soc->price_level], true); print ''; } else { - // TVA - print ''.$langs->trans("DefaultTaxRate").''; + // TVA + print ''.$langs->trans("DefaultTaxRate").''; - $positiverates = ''; - if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; - echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); + $positiverates = ''; + if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); /* if ($object->default_vat_code) { print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; } else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);*/ - print ''; + print ''; } } else { if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility @@ -795,28 +795,28 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ print ''.vatrate($object->multiprices_tva_tx[1], true).''; print ''; } else { - // TVA - print ''.$langs->trans("DefaultTaxRate").''; + // TVA + print ''.$langs->trans("DefaultTaxRate").''; - $positiverates = ''; - if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); - if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); - if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); - if (empty($positiverates)) $positiverates = '0'; - echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); - /* + $positiverates = ''; + if (price2num($object->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx); + if (price2num($object->localtax1_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx); + if (price2num($object->localtax2_type)) $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx); + if (empty($positiverates)) $positiverates = '0'; + echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), '%', $object->tva_npr); + /* if ($object->default_vat_code) { print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')'; } else print vatrate($object->tva_tx . ($object->tva_npr ? '*' : ''), true);*/ - print ''; + print ''; } - print ''; + print ''; - print '
'; + print '
'; - print ''; + print '
'; print ''; @@ -875,7 +875,7 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) // TODO Fix the form included into a tr instead of a td { print ''; + print '   '.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().''; } print ''; print ''; @@ -1282,8 +1282,8 @@ if ($action == 'edit_price' && $object->getRights()->creer) print '
'; } else { - print ''."\n"; - ?> + print ''."\n"; + ?>
'; print $langs->trans("PriceLevel"); if ($user->admin) print ' id.'">'.img_edit($langs->trans('EditSellingPriceLabel'), 0).''; @@ -834,17 +834,17 @@ if (!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_ $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i; if (preg_match('/editlabelsellingprice/', $action)) { - print '
'; - print ''; - print ''; - print ''; - print $langs->trans("SellingPrice").' '.$i.' - '; - print ''; - print ' '; - print '
'; + print '
'; + print ''; + print ''; + print ''; + print $langs->trans("SellingPrice").' '.$i.' - '; + print ''; + print ' '; + print '
'; } else { - print $langs->trans("SellingPrice").' '.$i; - if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); + print $langs->trans("SellingPrice").' '.$i; + if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); } print '
'.$langs->trans("PriceByQuantity").' '.$i; - if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); + if (!empty($conf->global->$keyforlabel)) print ' - '.$langs->trans($conf->global->$keyforlabel); print ''; if ($object->prices_by_qty[$i] == 1) { @@ -1102,7 +1102,7 @@ if (!$action || $action == 'delete' || $action == 'showlog_customer_price' || $a { print "\n".'
'."\n"; - if ($object->isVariant()) { + if ($object->isVariant()) { if ($user->rights->produit->creer || $user->rights->service->creer) { print ''; } @@ -1128,7 +1128,7 @@ if (!$action || $action == 'delete' || $action == 'showlog_customer_price' || $a print ''; } } - } + } print "\n
\n"; } @@ -1176,7 +1176,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) if (empty($conf->global->PRODUIT_MULTIPRICES) && empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { - print ''."\n"; + print ''."\n"; print '
'; print ''; print ''; @@ -1262,7 +1262,7 @@ if ($action == 'edit_price' && $object->getRights()->creer) } if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) { - print '   '.$langs->trans("MinimumRecommendedPrice", price($maxpricesupplier, 0, '', 1, -1, -1, 'auto')).' '.img_warning().'