From 8c1902be1bc667b85898d48c817ea6300aac22e6 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Mon, 22 Feb 2021 18:40:15 +0100 Subject: [PATCH 01/64] Missing space --- htdocs/compta/facture/card.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index 44097c84f49..c871304905f 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -3596,7 +3596,7 @@ if ($action == 'create') if (is_array($objectsrc->linkedObjects['facture']) && count($objectsrc->linkedObjects['facture']) >= 1) { setEventMessages('WarningBillExist', null, 'warnings'); - echo ' ('.$langs->trans('LatestRelatedBill').end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')'; + echo ' ('.$langs->trans('LatestRelatedBill').' '.end($objectsrc->linkedObjects['facture'])->getNomUrl(1).')'; } echo ''; print ''.$langs->trans('AmountHT').''.price($objectsrc->total_ht).''; From 34dcebea78186b91d2d57d50b0bf90f523a829fe Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 Feb 2021 11:03:34 +0100 Subject: [PATCH 02/64] Code comment --- htdocs/core/js/lib_head.js.php | 7 ++++--- htdocs/core/lib/ajax.lib.php | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/htdocs/core/js/lib_head.js.php b/htdocs/core/js/lib_head.js.php index 391a5359846..f03be3711f9 100644 --- a/htdocs/core/js/lib_head.js.php +++ b/htdocs/core/js/lib_head.js.php @@ -536,7 +536,7 @@ function setConstant(url, code, input, entity, strict, forcereload, userid, toke entity: entity, token: token }, - function() { + function() { /* handler for success of post */ console.log("url request success forcereload="+forcereload); $("#set_" + code).hide(); $("#del_" + code).show(); @@ -659,12 +659,13 @@ function delConstant(url, code, input, entity, strict, forcereload, userid, toke } /* - * Used by button to set on/off + * Call the setConstant or delConstant but with a confirmation before. + * Used by button to set on/off. * * @param string action Action * @param string url Url * @param string code Code - * @param string intput Input + * @param string intput Array of complementary actions to do if success * @param string box Box * @param int entity Entity * @param int yesButton yesButton diff --git a/htdocs/core/lib/ajax.lib.php b/htdocs/core/lib/ajax.lib.php index 8a364359e9d..c9f64129e65 100644 --- a/htdocs/core/lib/ajax.lib.php +++ b/htdocs/core/lib/ajax.lib.php @@ -491,13 +491,13 @@ function ajax_combobox($htmlname, $events = array(), $minLengthToAutocomplete = * On/off button for constant * * @param string $code Name of constant - * @param array $input Array of options. ("disabled"|"enabled'|'set'|'del') => CSS element to switch, 'alert' => message to show, ... Example: array('disabled'=>array(0=>'cssid')) - * @param int $entity Entity to set. Use current entity if null. + * @param array $input Array of complementary actions to do if success ("disabled"|"enabled'|'set'|'del') => CSS element to switch, 'alert' => message to show, ... Example: array('disabled'=>array(0=>'cssid')) + * @param int $entity Entity. Current entity is used if null. * @param int $revertonoff Revert on/off * @param int $strict Use only "disabled" with delConstant and "enabled" with setConstant * @param int $forcereload Force to reload page if we click/change value (this is supported only when there is no 'alert' option in input) * @param string $marginleftonlyshort 1 = Add a short left margin on picto, 2 = Add a larger left margin on picto, 0 = No left margin. Works for fontawesome picto only. - * @param int $forcenoajax 1=Force to use a ahref link instead of ajax code. + * @param int $forcenoajax 1 = Force to use a ahref link instead of ajax code. * @return string */ function ajax_constantonoff($code, $input = array(), $entity = null, $revertonoff = 0, $strict = 0, $forcereload = 0, $marginleftonlyshort = 2, $forcenoajax = 0) From d2e1f9fce9d2245d42f21e21a1056645d490c658 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 Feb 2021 11:13:57 +0100 Subject: [PATCH 03/64] FIX #16096 #16085 Any call of ajax pages must provide the token --- htdocs/core/js/lib_head.js.php | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/htdocs/core/js/lib_head.js.php b/htdocs/core/js/lib_head.js.php index f03be3711f9..f40f84c7b2c 100644 --- a/htdocs/core/js/lib_head.js.php +++ b/htdocs/core/js/lib_head.js.php @@ -520,9 +520,9 @@ function hideMessage(fieldId,message) { * Used by button to set on/off. * Call url then make complementary action (like show/hide, enable/disable or set another option). * - * @param string url Url + * @param string url Url (warning: as any url called in ajax mode, the url called here must not renew the token) * @param string code Code - * @param string intput Input + * @param string intput Array of complementary actions to do if success * @param int entity Entity * @param int strict Strict * @param int forcereload Force reload @@ -574,11 +574,12 @@ function setConstant(url, code, input, entity, strict, forcereload, userid, toke $.each(data, function(key, value) { $("#set_" + key).hide(); $("#del_" + key).show(); - $.get( url, { + $.post( url, { action: "set", name: key, value: value, - entity: entity + entity: entity, + token: token }); }); } @@ -593,9 +594,9 @@ function setConstant(url, code, input, entity, strict, forcereload, userid, toke * Used by button to set on/off * Call url then make complementary action (like show/hide, enable/disable or set another option). * - * @param string url Url + * @param string url Url (warning: as any url called in ajax mode, the url called here must not renew the token) * @param string code Code - * @param string intput Input + * @param string intput Array of complementary actions to do if success * @param int entity Entity * @param int strict Strict * @param int forcereload Force reload @@ -644,10 +645,11 @@ function delConstant(url, code, input, entity, strict, forcereload, userid, toke $.each(data, function(key, value) { $("#del_" + value).hide(); $("#set_" + value).show(); - $.get( url, { + $.post( url, { action: "del", name: value, - entity: entity + entity: entity, + token: token }); }); } From f50ce6f91f3885103a6efbc1ca2ef27c95eead76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 12:19:49 +0100 Subject: [PATCH 04/64] add cache on project head --- htdocs/core/lib/project.lib.php | 243 +++++++++++++++++++++++--------- 1 file changed, 177 insertions(+), 66 deletions(-) diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index 9bbfe1322e9..d710f69b2d4 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -2,7 +2,7 @@ /* Copyright (C) 2006-2015 Laurent Destailleur * Copyright (C) 2010 Regis Houssin * Copyright (C) 2011 Juanjo Menent - * Copyright (C) 2018 Frédéric France + * Copyright (C) 2018-2021 Frédéric France * * 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 @@ -44,44 +44,80 @@ function project_prepare_head(Project $project) $head[$h][1] = $langs->trans("Project"); $head[$h][2] = 'project'; $h++; + $nbContacts = 0; + // Enable caching of project count Contacts + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $cachekey = 'count_contacts_project_'.$object->id; + $dataretrieved = dol_getcache($cachekey); - $nbContact = count($project->liste_contact(-1, 'internal')) + count($project->liste_contact(-1, 'external')); + if (!is_null($dataretrieved)) { + $nbContacts = $dataretrieved; + } else { + $nbContacts = count($project->liste_contact(-1, 'internal')) + count($project->liste_contact(-1, 'external')); + dol_setcache($cachekey, $nbContact, 120); // If setting cache fails, this is not a problem, so we do not test result. + } $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.''; + if ($nbContacts > 0) { + $head[$h][1] .= ''.$nbContacts.''; + } $head[$h][2] = 'contact'; $h++; - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { // Then tab for sub level of projet, i mean tasks + $nbTasks = 0; + // Enable caching of project count Tasks + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $cachekey = 'count_tasks_project_'.$object->id; + $dataretrieved = dol_getcache($cachekey); + + if (!is_null($dataretrieved)) { + $nbTasks = $dataretrieved; + } else { + require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; + $taskstatic = new Task($db); + $nbTasks = count($taskstatic->getTasksArray(0, 0, $project->id, 0, 0)); + dol_setcache($cachekey, $nbTasks, 120); // If setting cache fails, this is not a problem, so we do not test result. + } $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, $project->id, 0, 0)); - if ($nbTasks > 0) $head[$h][1] .= ''.($nbTasks).''; + if ($nbTasks > 0) { + $head[$h][1] .= ''.($nbTasks).''; + } $head[$h][2] = 'tasks'; $h++; $nbTimeSpent = 0; - $sql = "SELECT t.rowid"; - //$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."user as u"; - //$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 =".$project->id; - $resql = $db->query($sql); - if ($resql) - { - $obj = $db->fetch_object($resql); - if ($obj) $nbTimeSpent = 1; - } else dol_print_error($db); + // Enable caching of project count Timespent + $cachekey = 'count_timespent_project_'.$object->id; + $dataretrieved = dol_getcache($cachekey); + if (!is_null($dataretrieved)) { + $nbTimeSpent = $dataretrieved; + } else { + $sql = "SELECT t.rowid"; + //$sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t, ".MAIN_DB_PREFIX."projet_task as pt, ".MAIN_DB_PREFIX."user as u"; + //$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 =".$project->id; + $resql = $db->query($sql); + if ($resql) { + $obj = $db->fetch_object($resql); + if ($obj) { + $nbTimeSpent = 1; + dol_setcache($cachekey, $nbTimeSpent, 120); // If setting cache fails, this is not a problem, so we do not test result. + } + } else { + dol_print_error($db); + } + } $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] .= '...'; + if ($nbTimeSpent > 0) { + $head[$h][1] .= '...'; + } $head[$h][2] = 'timespent'; $h++; } @@ -89,34 +125,80 @@ function project_prepare_head(Project $project) if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) || !empty($conf->propal->enabled) || !empty($conf->commande->enabled) || !empty($conf->facture->enabled) || !empty($conf->contrat->enabled) - || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) - { - $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'); - + || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) { + $nbElements = 0; + // Enable caching of thirdrparty count Contacts + $cachekey = 'count_elements_project_'.$object->id; + $dataretrieved = dol_getcache($cachekey); + if (!is_null($dataretrieved)) { + $nbElements = $dataretrieved; + } else { + 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.''; + if ($nbElements > 0) { + $head[$h][1] .= ''.$nbElements.''; + } $head[$h][2] = 'element'; $h++; } @@ -128,44 +210,73 @@ function project_prepare_head(Project $project) complete_head_from_modules($conf, $langs, $project, $head, $h, 'project'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($project->note_private)) $nbNote++; - if (!empty($project->note_public)) $nbNote++; + 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.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'notes'; $h++; } - 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($project->ref); - $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); - $nbLinks = Link::count($db, $project->element, $project->id); + // Attached files and Links + $totalAttached = 0; + // Enable caching of thirdrparty count attached files and links + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $cachekey = 'count_attached_project_'.$object->id; + $dataretrieved = dol_getcache($cachekey); + if (!is_null($dataretrieved)) { + $totalAttached = $dataretrieved; + } else { + 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($project->ref); + $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); + $nbLinks = Link::count($db, $project->element, $project->id); + $totalAttached = $nbFiles + $nbLinks; + dol_setcache($cachekey, $totalAttached, 120); // If setting cache fails, this is not a problem, so we do not test result. + } $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).''; + if (($totalAttached) > 0) { + $head[$h][1] .= ''.($totalAttached).''; + } $head[$h][2] = 'document'; $h++; // Manage discussion - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) - { - $nbComments = $project->getNbComments(); + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) { + $nbComments = 0; + // Enable caching of thirdrparty count attached files and links + require_once DOL_DOCUMENT_ROOT.'/core/lib/memory.lib.php'; + $cachekey = 'count_attached_project_'.$object->id; + $dataretrieved = dol_getcache($cachekey); + if (!is_null($dataretrieved)) { + $nbComments = $dataretrieved; + } else { + $nbComments = $project->getNbComments(); + dol_setcache($cachekey, $nbComments, 120); // If setting cache fails, this is not a problem, so we do not test result. + } $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.''; + if ($nbComments > 0) { + $head[$h][1] .= ''.$nbComments.''; + } $head[$h][2] = 'project_comment'; $h++; } $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))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } From b7e2c7d87a2a33fbe18cde005951931484ca121b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur Date: Tue, 23 Feb 2021 12:58:43 +0100 Subject: [PATCH 05/64] FIX #16393 Do not sanitize --- htdocs/core/lib/functions.lib.php | 4 ++++ test/phpunit/SecurityTest.php | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/htdocs/core/lib/functions.lib.php b/htdocs/core/lib/functions.lib.php index 92c519c5a66..e2889c4d6d3 100644 --- a/htdocs/core/lib/functions.lib.php +++ b/htdocs/core/lib/functions.lib.php @@ -5833,6 +5833,8 @@ function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $allowed_tags_string = join("><", $allowed_tags); $allowed_tags_string = '<'.$allowed_tags_string.'>'; + $stringtoclean = str_replace('', '__!DOCTYPE_HTML__', $stringtoclean); // Replace DOCTYPE to avoid to have it removed by the strip_tags + $stringtoclean = dol_string_nounprintableascii($stringtoclean, 0); $stringtoclean = preg_replace('/:/i', ':', $stringtoclean); @@ -5855,6 +5857,8 @@ function dol_string_onlythesehtmltags($stringtoclean, $cleanalsosomestyles = 1, $temp = preg_replace('/javascript\s*:/i', '', $temp); } + $temp = str_replace('__!DOCTYPE_HTML__', '', $temp); // Restore the DOCTYPE + return $temp; } diff --git a/test/phpunit/SecurityTest.php b/test/phpunit/SecurityTest.php index 78fdb0b1419..bca1aace56a 100644 --- a/test/phpunit/SecurityTest.php +++ b/test/phpunit/SecurityTest.php @@ -300,6 +300,7 @@ class SecurityTest extends PHPUnit\Framework\TestCase $_POST["param9"]='is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : \'objnotdefined\''; $_POST["param10"]='is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : \'objnotdefined\''; $_POST["param11"]=' Name '; + $_POST["param12"]='aaa'; $result=GETPOST('id', 'int'); // Must return nothing print __METHOD__." result=".$result."\n"; @@ -397,6 +398,10 @@ class SecurityTest extends PHPUnit\Framework\TestCase print __METHOD__." result=".$result."\n"; $this->assertEquals(trim($_POST["param11"]), $result, 'Test an email string with alphawithlgt'); + $result=GETPOST("param12", 'restricthtml'); + print __METHOD__." result=".$result."\n"; + $this->assertEquals(trim($_POST["param12"]), $result, 'Test a string with DOCTYPE and restricthtml'); + return $result; } From 00f10d1850fc066c11c46ec343e7492b9b41766f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 13:33:27 +0100 Subject: [PATCH 06/64] fix typo --- htdocs/projet/event.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/htdocs/projet/event.php b/htdocs/projet/event.php index 0f565c7923c..91f763a5e83 100644 --- a/htdocs/projet/event.php +++ b/htdocs/projet/event.php @@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // Load translation files required by the page -$langs->load('projects', 'enevntorganization'); +$langs->load('projects', 'enventorganization'); $action = GETPOST('action', 'aZ09'); $id = GETPOST('id', 'int'); @@ -45,7 +45,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ // Security check $socid = 0; -if ($user->socid > 0) $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. +if ($user->socid > 0) { + $socid = $user->socid; // For external user, no check is done on company because readability is managed by public status of project and assignement. +} $result = restrictedArea($user, 'eventorganization', $id); $permissiontoread = $user->rights->eventorganization->read; From 9b48e1a649cef89f76f826607d50aa838db7738d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 17:44:43 +0100 Subject: [PATCH 07/64] code syntax api directory --- htdocs/api/admin/explorer.php | 115 +++++++-------- htdocs/api/class/api.class.php | 34 +++-- htdocs/api/class/api_access.class.php | 31 ++-- htdocs/api/class/api_documents.class.php | 176 +++++++++-------------- htdocs/api/class/api_login.class.php | 36 +++-- htdocs/api/class/api_setup.class.php | 2 +- htdocs/api/index.php | 144 +++++++++++-------- 7 files changed, 251 insertions(+), 287 deletions(-) diff --git a/htdocs/api/admin/explorer.php b/htdocs/api/admin/explorer.php index 835a5485544..53b9233c130 100644 --- a/htdocs/api/admin/explorer.php +++ b/htdocs/api/admin/explorer.php @@ -41,8 +41,7 @@ $langs->load("admin"); */ // Enable and test if module Api is enabled -if (empty($conf->global->MAIN_MODULE_API)) -{ +if (empty($conf->global->MAIN_MODULE_API)) { dol_syslog("Call Dolibarr API interfaces with module REST disabled"); print $langs->trans("WarningModuleNotActive", 'Api').'.

'; print $langs->trans("ToActivateModule"); @@ -59,20 +58,16 @@ $api->r->addAuthenticationClass('DolibarrApiAccess', ''); $listofapis = array(); $modulesdir = dolGetModulesDirs(); -foreach ($modulesdir as $dir) -{ +foreach ($modulesdir as $dir) { /* - * Search available module - */ + * Search available module + */ //dol_syslog("Scan directory ".$dir." for API modules"); $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) { $modulename = $reg[1]; // Defined if module is enabled @@ -96,60 +91,58 @@ foreach ($modulesdir as $dir) $module = 'fichinter'; } - if (empty($conf->$module->enabled)) $enabled = false; + if (empty($conf->$module->enabled)) { + $enabled = false; + } if ($enabled) { /* - * If exists, load the API class for enable module - * - * Search files named api_.class.php into /htdocs//class directory - * - * @todo : take care of externals module! - * @todo : use getElementProperties() function ? - */ + * If exists, load the API class for enable module + * + * Search files named api_.class.php into /htdocs//class directory + * + * @todo : take care of externals module! + * @todo : use getElementProperties() function ? + */ $dir_part = DOL_DOCUMENT_ROOT.'/'.$part.'/class/'; $handle_part = @opendir(dol_osencode($dir_part)); - if (is_resource($handle_part)) - { - while (($file_searched = readdir($handle_part)) !== false) - { - if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg)) - { + if (is_resource($handle_part)) { + while (($file_searched = readdir($handle_part)) !== false) { + if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $reg)) { $classname = ucwords($reg[1]); require_once $dir_part.$file_searched; - if (class_exists($classname)) - { + if (class_exists($classname)) { dol_syslog("Found API classname=".$classname." into ".$dir); $listofapis[] = $classname; } } /* - if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg)) - { - $classname=$reg[1]; - $classname = str_replace('Api_','',ucwords($reg[1])).'Api'; - //$classname = str_replace('Api_','',ucwords($reg[1])); - $classname = ucfirst($classname); - require_once $dir_part.$file_searched; + if (is_readable($dir_part.$file_searched) && preg_match("/^(api_.*)\.class\.php$/i",$file_searched,$reg)) + { + $classname=$reg[1]; + $classname = str_replace('Api_','',ucwords($reg[1])).'Api'; + //$classname = str_replace('Api_','',ucwords($reg[1])); + $classname = ucfirst($classname); + require_once $dir_part.$file_searched; - // if (class_exists($classname)) - // { - // dol_syslog("Found API classname=".$classname); - // $api->r->addAPIClass($classname,''); + // if (class_exists($classname)) + // { + // dol_syslog("Found API classname=".$classname); + // $api->r->addAPIClass($classname,''); - // require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php'; - // $tmpclass = new ReflectionClass($classname); - // try { - // $classMetadata = CommentParser::parse($tmpclass->getDocComment()); - // } catch (Exception $e) { - // throw new RestException(500, "Error while parsing comments of `$classname` class. " . $e->getMessage()); - // } + // require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/Routes.php'; + // $tmpclass = new ReflectionClass($classname); + // try { + // $classMetadata = CommentParser::parse($tmpclass->getDocComment()); + // } catch (Exception $e) { + // throw new RestException(500, "Error while parsing comments of `$classname` class. " . $e->getMessage()); + // } - // //$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched); - // } - }*/ + // //$listofapis[]=array('classname'=>$classname, 'fullpath'=>$file_searched); + // } + }*/ } } } @@ -186,21 +179,23 @@ print '
'; $oldclass = ''; print $langs->trans("ListOfAvailableAPIs").':
'; -foreach ($listofapis['v1'] as $key => $val) -{ - if ($key == 'login') continue; - if ($key == 'index') continue; +foreach ($listofapis['v1'] as $key => $val) { + if ($key == 'login') { + continue; + } + if ($key == 'index') { + continue; + } - if ($key) - { - foreach ($val as $method => $val2) - { + if ($key) { + foreach ($val as $method => $val2) { $newclass = $val2['className']; - if (preg_match('/restler/i', $newclass)) continue; + if (preg_match('/restler/i', $newclass)) { + continue; + } - if ($oldclass != $newclass) - { + if ($oldclass != $newclass) { print "\n
\n".$langs->trans("Class").': '.$newclass.'
'."\n"; $oldclass = $newclass; } diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index 89d170feb60..8ddcf9f2dc3 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -51,7 +51,9 @@ class DolibarrApi { global $conf, $dolibarr_main_url_root; - if (empty($cachedir)) $cachedir = $conf->api->dir_temp; + if (empty($cachedir)) { + $cachedir = $conf->api->dir_temp; + } Defaults::$cacheDirectory = $cachedir; $this->db = $db; @@ -140,7 +142,7 @@ class DolibarrApi unset($object->labelStatusShort); unset($object->stats_propale); - unset($object->stats_commande); + unset($object->stats_commande); unset($object->stats_contrat); unset($object->stats_facture); unset($object->stats_commande_fournisseur); @@ -191,8 +193,7 @@ class DolibarrApi // If object has lines, remove $db property if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) { $nboflines = count($object->lines); - for ($i = 0; $i < $nboflines; $i++) - { + for ($i = 0; $i < $nboflines; $i++) { $this->_cleanObjectDatas($object->lines[$i]); unset($object->lines[$i]->contact); @@ -284,12 +285,14 @@ class DolibarrApi $ok = 0; $i = 0; $nb = strlen($tmp); $counter = 0; - while ($i < $nb) - { - if ($tmp[$i] == '(') $counter++; - if ($tmp[$i] == ')') $counter--; - if ($counter < 0) - { + while ($i < $nb) { + if ($tmp[$i] == '(') { + $counter++; + } + if ($tmp[$i] == ')') { + $counter--; + } + if ($counter < 0) { $error = "Bad sqlfilters=".$sqlfilters; dol_syslog($error, LOG_WARNING); return false; @@ -313,14 +316,17 @@ class DolibarrApi global $db; //dol_syslog("Convert matches ".$matches[1]); - if (empty($matches[1])) return ''; + if (empty($matches[1])) { + return ''; + } $tmp = explode(':', $matches[1]); - if (count($tmp) < 3) return ''; + if (count($tmp) < 3) { + return ''; + } $tmpescaped = $tmp[2]; $regbis = array(); - if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) - { + if (preg_match('/^\'(.*)\'$/', $tmpescaped, $regbis)) { $tmpescaped = "'".$db->escape($regbis[1])."'"; } else { $tmpescaped = $db->escape($tmpescaped); diff --git a/htdocs/api/class/api_access.class.php b/htdocs/api/class/api_access.class.php index 926a51456c7..99582b62047 100644 --- a/htdocs/api/class/api_access.class.php +++ b/htdocs/api/class/api_access.class.php @@ -35,7 +35,6 @@ use \Luracast\Restler\Resources; use \Luracast\Restler\Defaults; use \Luracast\Restler\RestException; - /** * Dolibarr API access class * @@ -90,28 +89,24 @@ class DolibarrApiAccess implements iAuthenticate /*foreach ($_SERVER as $key => $val) { - dol_syslog($key.' - '.$val); + dol_syslog($key.' - '.$val); }*/ // api key can be provided in url with parameter api_key=xxx or ni header with header DOLAPIKEY:xxx $api_key = ''; - if (isset($_GET['api_key'])) // For backward compatibility - { + if (isset($_GET['api_key'])) { // For backward compatibility // TODO Add option to disable use of api key on url. Return errors if used. $api_key = $_GET['api_key']; } - if (isset($_GET['DOLAPIKEY'])) - { + if (isset($_GET['DOLAPIKEY'])) { // TODO Add option to disable use of api key on url. Return errors if used. $api_key = $_GET['DOLAPIKEY']; // With GET method } - if (isset($_SERVER['HTTP_DOLAPIKEY'])) // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY - { + if (isset($_SERVER['HTTP_DOLAPIKEY'])) { // Param DOLAPIKEY in header can be read with HTTP_DOLAPIKEY $api_key = $_SERVER['HTTP_DOLAPIKEY']; // With header method (recommanded) } - if ($api_key) - { + if ($api_key) { $userentity = 0; $sql = "SELECT u.login, u.datec, u.api_key, "; @@ -121,17 +116,14 @@ class DolibarrApiAccess implements iAuthenticate // TODO Check if 2 users has same API key. $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $login = $obj->login; $stored_key = $obj->api_key; $userentity = $obj->entity; - if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user - { + if (!defined("DOLENTITY") && $conf->entity != ($obj->entity ? $obj->entity : 1)) { // If API was not forced with HTTP_DOLENTITY, and user is on another entity, so we reset entity to entity of user $conf->entity = ($obj->entity ? $obj->entity : 1); // We must also reload global conf to get params from the entity dol_syslog("Entity was not set on http header with HTTP_DOLAPIENTITY (recommanded for performance purpose), so we switch now on entity of user (".$conf->entity.") and we have to reload configuration.", LOG_WARNING); @@ -147,8 +139,7 @@ class DolibarrApiAccess implements iAuthenticate return false; } - if (!$login) - { + if (!$login) { throw new RestException(503, 'Error when searching login user from api key'); } $fuser = new User($this->db); @@ -173,7 +164,9 @@ class DolibarrApiAccess implements iAuthenticate $userClass::setCacheIdentifier(static::$role); Resources::$accessControlFunction = 'DolibarrApiAccess::verifyAccess'; $requirefortest = static::$requires; - if (!is_array($requirefortest)) $requirefortest = explode(',', $requirefortest); + if (!is_array($requirefortest)) { + $requirefortest = explode(',', $requirefortest); + } return in_array(static::$role, (array) $requirefortest) || static::$role == 'admin'; } diff --git a/htdocs/api/class/api_documents.class.php b/htdocs/api/class/api_documents.class.php index ebeeac5c5b9..00fd1a91a8a 100644 --- a/htdocs/api/class/api_documents.class.php +++ b/htdocs/api/class/api_documents.class.php @@ -20,7 +20,6 @@ use Luracast\Restler\RestException; use Luracast\Restler\Format\UploadFormat; - require_once DOL_DOCUMENT_ROOT.'/main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -36,7 +35,7 @@ class Documents extends DolibarrApi /** * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object */ - static $DOCUMENT_FIELDS = array( + public static $DOCUMENT_FIELDS = array( 'modulepart' ); @@ -106,8 +105,7 @@ class Documents extends DolibarrApi $filename = basename($original_file); $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset - if (!file_exists($original_file_osencoded)) - { + if (!file_exists($original_file_osencoded)) { dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); throw new RestException(404, 'File not found'); } @@ -148,8 +146,7 @@ class Documents extends DolibarrApi } $outputlangs = $langs; - if ($langcode && $langs->defaultlang != $langcode) - { + if ($langcode && $langs->defaultlang != $langcode) { $outputlangs = new Translate('', $conf); $outputlangs->setDefaultLang($langcode); } @@ -187,8 +184,7 @@ class Documents extends DolibarrApi $templateused = ''; - if ($modulepart == 'facture' || $modulepart == 'invoice') - { + if ($modulepart == 'facture' || $modulepart == 'invoice') { require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $this->invoice = new Facture($this->db); $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); @@ -201,9 +197,7 @@ class Documents extends DolibarrApi if ($result <= 0) { throw new RestException(500, 'Error generating document'); } - } - elseif ($modulepart == 'commande' || $modulepart == 'order') - { + } elseif ($modulepart == 'commande' || $modulepart == 'order') { require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $this->order = new Commande($this->db); $result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); @@ -215,9 +209,7 @@ class Documents extends DolibarrApi if ($result <= 0) { throw new RestException(500, 'Error generating document'); } - } - elseif ($modulepart == 'propal' || $modulepart == 'proposal') - { + } elseif ($modulepart == 'propal' || $modulepart == 'proposal') { require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $this->propal = new Propal($this->db); $result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file))); @@ -236,8 +228,7 @@ class Documents extends DolibarrApi $filename = basename($original_file); $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset - if (!file_exists($original_file_osencoded)) - { + if (!file_exists($original_file_osencoded)) { throw new RestException(404, 'File not found'); } @@ -278,8 +269,7 @@ class Documents extends DolibarrApi $recursive = 0; $type = 'files'; - if ($modulepart == 'societe' || $modulepart == 'thirdparty') - { + if ($modulepart == 'societe' || $modulepart == 'thirdparty') { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; if (!DolibarrApiAccess::$user->rights->societe->lire) { @@ -293,9 +283,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id; - } - elseif ($modulepart == 'user') - { + } elseif ($modulepart == 'user') { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; // Can get doc if has permission to read all user or if it is user itself @@ -310,9 +298,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id; - } - elseif ($modulepart == 'adherent' || $modulepart == 'member') - { + } elseif ($modulepart == 'adherent' || $modulepart == 'member') { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; if (!DolibarrApiAccess::$user->rights->adherent->lire) { @@ -326,9 +312,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member'); - } - elseif ($modulepart == 'propal' || $modulepart == 'proposal') - { + } elseif ($modulepart == 'propal' || $modulepart == 'proposal') { require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; if (!DolibarrApiAccess::$user->rights->propal->lire) { @@ -342,9 +326,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal'); - } - elseif ($modulepart == 'commande' || $modulepart == 'order') - { + } elseif ($modulepart == 'commande' || $modulepart == 'order') { require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; if (!DolibarrApiAccess::$user->rights->commande->lire) { @@ -358,9 +340,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande'); - } - elseif ($modulepart == 'shipment' || $modulepart == 'expedition') - { + } elseif ($modulepart == 'shipment' || $modulepart == 'expedition') { require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; if (!DolibarrApiAccess::$user->rights->expedition->lire) { @@ -374,9 +354,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment'); - } - elseif ($modulepart == 'facture' || $modulepart == 'invoice') - { + } elseif ($modulepart == 'facture' || $modulepart == 'invoice') { require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; if (!DolibarrApiAccess::$user->rights->facture->lire) { @@ -390,9 +368,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice'); - } - elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') - { + } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') { $modulepart = 'supplier_invoice'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; @@ -408,9 +384,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref); - } - elseif ($modulepart == 'produit' || $modulepart == 'product') - { + } elseif ($modulepart == 'produit' || $modulepart == 'product') { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; if (!DolibarrApiAccess::$user->rights->produit->lire) { @@ -426,9 +400,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product'); - } - elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') - { + } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') { require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) { @@ -442,9 +414,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref); - } - elseif ($modulepart == 'expensereport') - { + } elseif ($modulepart == 'expensereport') { require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) { @@ -458,9 +428,7 @@ class Documents extends DolibarrApi } $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref); - } - elseif ($modulepart == 'categorie' || $modulepart == 'category') - { + } elseif ($modulepart == 'categorie' || $modulepart == 'category') { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; if (!DolibarrApiAccess::$user->rights->categorie->lire) { @@ -523,9 +491,9 @@ class Documents extends DolibarrApi * @throws RestException */ /* - public function get($id) { - return array('note'=>'xxx'); - }*/ + public function get($id) { + return array('note'=>'xxx'); + }*/ /** @@ -557,12 +525,11 @@ class Documents extends DolibarrApi global $db, $conf; /*var_dump($modulepart); - var_dump($filename); - var_dump($filecontent); - exit;*/ + var_dump($filename); + var_dump($filecontent); + exit;*/ - if (empty($modulepart)) - { + if (empty($modulepart)) { throw new RestException(400, 'Modulepart not provided.'); } @@ -571,41 +538,39 @@ class Documents extends DolibarrApi } $newfilecontent = ''; - if (empty($fileencoding)) $newfilecontent = $filecontent; - if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent); + if (empty($fileencoding)) { + $newfilecontent = $filecontent; + } + if ($fileencoding == 'base64') { + $newfilecontent = base64_decode($filecontent); + } $original_file = dol_sanitizeFileName($filename); // Define $uploadir $object = null; $entity = DolibarrApiAccess::$user->entity; - if (empty($entity)) $entity = 1; + if (empty($entity)) { + $entity = 1; + } - if ($ref) - { + if ($ref) { $tmpreldir = ''; - if ($modulepart == 'facture' || $modulepart == 'invoice') - { + if ($modulepart == 'facture' || $modulepart == 'invoice') { $modulepart = 'facture'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $object = new Facture($this->db); - } - elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') - { + } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') { $modulepart = 'supplier_invoice'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $object = new FactureFournisseur($this->db); - } - elseif ($modulepart == 'project') - { + } elseif ($modulepart == 'project') { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $object = new Project($this->db); - } - elseif ($modulepart == 'task' || $modulepart == 'project_task') - { + } elseif ($modulepart == 'task' || $modulepart == 'project_task') { $modulepart = 'project_task'; require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; @@ -614,36 +579,26 @@ class Documents extends DolibarrApi $task_result = $object->fetch('', $ref); // Fetching the tasks project is required because its out_dir might be a sub-directory of the project - if ($task_result > 0) - { + if ($task_result > 0) { $project_result = $object->fetch_projet(); - if ($project_result >= 0) - { + if ($project_result >= 0) { $tmpreldir = dol_sanitizeFileName($object->project->ref).'/'; } } else { throw new RestException(500, 'Error while fetching Task '.$ref); } - } - elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') - { + } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $object = new Product($this->db); - } - elseif ($modulepart == 'expensereport') - { + } elseif ($modulepart == 'expensereport') { require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; $object = new ExpenseReport($this->db); - } - elseif ($modulepart == 'adherent' || $modulepart == 'member') - { + } elseif ($modulepart == 'adherent' || $modulepart == 'member') { $modulepart = 'adherent'; require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $object = new Adherent($this->db); - } - elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') - { + } elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') { $modulepart = 'propale'; require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $object = new Propal($this->db); @@ -652,22 +607,18 @@ class Documents extends DolibarrApi throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.'); } - if (is_object($object)) - { + if (is_object($object)) { $result = $object->fetch('', $ref); - if ($result == 0) - { + if ($result == 0) { throw new RestException(404, "Object with ref '".$ref."' was not found."); - } - elseif ($result < 0) - { + } elseif ($result < 0) { throw new RestException(500, 'Error while fetching object: '.$object->error); } } if (!($object->id > 0)) { - throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found."); + throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found."); } // Special cases that need to use get_exdir to get real dir of object @@ -681,13 +632,16 @@ class Documents extends DolibarrApi $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write'); $upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir - if (empty($upload_dir) || $upload_dir == '/') - { + if (empty($upload_dir) || $upload_dir == '/') { throw new RestException(500, 'This value of modulepart ('.$modulepart.') does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.'); } } else { - if ($modulepart == 'invoice') $modulepart = 'facture'; - if ($modulepart == 'member') $modulepart = 'adherent'; + if ($modulepart == 'invoice') { + $modulepart = 'facture'; + } + if ($modulepart == 'member') { + $modulepart = 'adherent'; + } $relativefile = $subdir; $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write'); @@ -771,12 +725,12 @@ class Documents extends DolibarrApi // Special cases that need to use get_exdir to get real dir of object // If future, all object should use this to define path of documents. /* - $tmpreldir = ''; - if ($modulepart == 'supplier_invoice') { - $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier'); - } + $tmpreldir = ''; + if ($modulepart == 'supplier_invoice') { + $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier'); + } - $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */ + $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */ $relativefile = $original_file; $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read'); @@ -794,8 +748,7 @@ class Documents extends DolibarrApi $filename = basename($original_file); $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset - if (!file_exists($original_file_osencoded)) - { + if (!file_exists($original_file_osencoded)) { dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING); throw new RestException(404, 'File not found'); } @@ -825,8 +778,9 @@ class Documents extends DolibarrApi // phpcs:enable $result = array(); foreach (Documents::$DOCUMENT_FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $result[$field] = $data[$field]; } return $result; diff --git a/htdocs/api/class/api_login.class.php b/htdocs/api/class/api_login.class.php index 17d8916b9aa..b9666269cc1 100644 --- a/htdocs/api/class/api_login.class.php +++ b/htdocs/api/class/api_login.class.php @@ -61,14 +61,16 @@ class Login // TODO Remove the API login. The token must be generated from backoffice only. // Authentication mode - if (empty($dolibarr_main_authentication)) $dolibarr_main_authentication = 'dolibarr'; + if (empty($dolibarr_main_authentication)) { + $dolibarr_main_authentication = 'dolibarr'; + } // Authentication mode: forceuser - if ($dolibarr_main_authentication == 'forceuser') - { - if (empty($dolibarr_auto_user)) $dolibarr_auto_user = 'auto'; - if ($dolibarr_auto_user != $login) - { + if ($dolibarr_main_authentication == 'forceuser') { + if (empty($dolibarr_auto_user)) { + $dolibarr_auto_user = 'auto'; + } + if ($dolibarr_auto_user != $login) { dol_syslog("Warning: your instance is set to use the automatic forced login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); throw new RestException(403, "Your instance is set to use the automatic login '".$dolibarr_auto_user."' that is not the requested login. API usage is forbidden in this mode."); } @@ -77,16 +79,16 @@ class Login // Set authmode $authmode = explode(',', $dolibarr_main_authentication); - if ($entity != '' && !is_numeric($entity)) - { + if ($entity != '' && !is_numeric($entity)) { throw new RestException(403, "Bad value for entity, must be the numeric ID of company."); } - if ($entity == '') $entity = 1; + if ($entity == '') { + $entity = 1; + } include_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $login = checkLoginPassEntity($login, $password, $entity, $authmode, 'api'); - if (empty($login)) - { + if (empty($login)) { throw new RestException(403, 'Access denied'); } @@ -94,17 +96,14 @@ class Login $tmpuser = new User($this->db); $tmpuser->fetch(0, $login, 0, 0, $entity); - if (empty($tmpuser->id)) - { + if (empty($tmpuser->id)) { throw new RestException(500, 'Failed to load user'); } // Renew the hash - if (empty($tmpuser->api_key) || $reset) - { + if (empty($tmpuser->api_key) || $reset) { $tmpuser->getrights(); - if (empty($tmpuser->rights->user->self->creer)) - { + if (empty($tmpuser->rights->user->self->creer)) { throw new RestException(403, 'User need write permission on itself to reset its API token'); } @@ -118,8 +117,7 @@ class Login dol_syslog(get_class($this)."::login", LOG_DEBUG); // No log $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { throw new RestException(500, 'Error when updating api_key for user :'.$this->db->lasterror()); } } else { diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index 4e4996df7e0..674cc53b69f 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -310,7 +310,7 @@ class Setup extends DolibarrApi * Get state by ID. * * @param int $id ID of state - * @return array Array of cleaned object properties + * @return array Array of cleaned object properties * * @url GET dictionary/states/{id} * diff --git a/htdocs/api/index.php b/htdocs/api/index.php index 2c85533fd11..bb74144a40d 100644 --- a/htdocs/api/index.php +++ b/htdocs/api/index.php @@ -26,22 +26,42 @@ use Luracast\Restler\Format\UploadFormat; -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library -if (!defined("NOLOGIN")) define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) -if (!defined("NOSESSION")) define("NOSESSION", '1'); +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +} +if (!defined("NOLOGIN")) { + define("NOLOGIN", '1'); // If this page is public (can be called outside logged session) +} +if (!defined("NOSESSION")) { + define("NOSESSION", '1'); +} // Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used. -if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']); +if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) { + define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']); +} $res = 0; -if (!$res && file_exists("../main.inc.php")) $res = include '../main.inc.php'; -if (!$res) die("Include of main fails"); +if (!$res && file_exists("../main.inc.php")) { + $res = include '../main.inc.php'; +} +if (!$res) { + die("Include of main fails"); +} require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php'; @@ -61,14 +81,12 @@ if (preg_match('/api\/index\.php$/', $url)) { // sometimes $_SERVER['PHP_SELF'] $url = $_SERVER['PHP_SELF'].$_SERVER['PATH_INFO']; } // Fix for some NGINX setups (this should not be required even with NGINX, however setup of NGINX are often mysterious and this may help is such cases) -if (!empty($conf->global->MAIN_NGINX_FIX)) -{ +if (!empty($conf->global->MAIN_NGINX_FIX)) { $url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF']; } // Enable and test if module Api is enabled -if (empty($conf->global->MAIN_MODULE_API)) -{ +if (empty($conf->global->MAIN_MODULE_API)) { $langs->load("admin"); dol_syslog("Call Dolibarr API interfaces with module REST disabled"); print $langs->trans("WarningModuleNotActive", 'Api').'.

'; @@ -78,8 +96,7 @@ if (empty($conf->global->MAIN_MODULE_API)) } // Test if explorer is not disabled -if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) -{ +if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) { $langs->load("admin"); dol_syslog("Call Dolibarr API interfaces with module REST disabled"); print $langs->trans("WarningAPIExplorerDisabled").'.

'; @@ -112,8 +129,7 @@ preg_match('/index\.php\/([^\/]+)(.*)$/', $url, $reg); // using the explorer. And when we make another call for another API, the API is not into the api/temp/routes.php and a 404 is returned. // So we force refresh to each call. $refreshcache = (empty($conf->global->API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE) ? true : false); -if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) -{ +if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) { $refreshcache = true; } @@ -132,12 +148,10 @@ UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain', // Restrict API to some IPs -if (!empty($conf->global->API_RESTRICT_ON_IP)) -{ +if (!empty($conf->global->API_RESTRICT_ON_IP)) { $allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP); $ipremote = getUserRemoteIP(); - if (!in_array($ipremote, $allowedip)) - { + if (!in_array($ipremote, $allowedip)) { dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP); print 'APIs are not allowed from the IP '.$ipremote; header('HTTP/1.1 503 API not allowed from your IP '.$ipremote); @@ -148,65 +162,64 @@ if (!empty($conf->global->API_RESTRICT_ON_IP)) // Call Explorer file for all APIs definitions (this part is slow) -if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) -{ +if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) { // Scan all API files to load them $listofapis = array(); $modulesdir = dolGetModulesDirs(); - foreach ($modulesdir as $dir) - { + foreach ($modulesdir as $dir) { // Search available module dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files"); $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { $regmod = array(); - if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) - { + if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) { $module = strtolower($regmod[1]); $moduledirforclass = getModuleDirForApiClass($module); $modulenameforenabled = $module; - if ($module == 'propale') { $modulenameforenabled = 'propal'; } - if ($module == 'supplierproposal') { $modulenameforenabled = 'supplier_proposal'; } - if ($module == 'ficheinter') { $modulenameforenabled = 'ficheinter'; } + if ($module == 'propale') { + $modulenameforenabled = 'propal'; + } + if ($module == 'supplierproposal') { + $modulenameforenabled = 'supplier_proposal'; + } + if ($module == 'ficheinter') { + $modulenameforenabled = 'ficheinter'; + } dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass); // Defined if module is enabled $enabled = true; - if (empty($conf->$modulenameforenabled->enabled)) $enabled = false; + if (empty($conf->$modulenameforenabled->enabled)) { + $enabled = false; + } - if ($enabled) - { + if ($enabled) { // If exists, load the API class for enable module // Search files named api_.class.php into /htdocs//class directory // @todo : use getElementProperties() function ? $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/'); $handle_part = @opendir(dol_osencode($dir_part)); - if (is_resource($handle_part)) - { - while (($file_searched = readdir($handle_part)) !== false) - { - if ($file_searched == 'api_access.class.php') continue; + if (is_resource($handle_part)) { + while (($file_searched = readdir($handle_part)) !== false) { + if ($file_searched == 'api_access.class.php') { + continue; + } $regapi = array(); - if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) - { + if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) { $classname = ucwords($regapi[1]); $classname = str_replace('_', '', $classname); require_once $dir_part.$file_searched; - if (class_exists($classname.'Api')) - { + if (class_exists($classname.'Api')) { //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched); $listofapis[strtolower($classname.'Api')] = $classname.'Api'; - } elseif (class_exists($classname)) - { + } elseif (class_exists($classname)) { //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched); $listofapis[strtolower($classname)] = $classname; } else { @@ -224,8 +237,7 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $ // Sort the classes before adding them to Restler. // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted. asort($listofapis); - foreach ($listofapis as $apiname => $classname) - { + foreach ($listofapis as $apiname => $classname) { $api->r->addAPIClass($classname, $apiname); } //var_dump($api->r); @@ -233,11 +245,9 @@ if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $ // Call one APIs or one definition of an API $regbis = array(); -if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) -{ +if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) { $moduleobject = $reg[1]; - if ($moduleobject == 'explorer') // If we call page to explore details of a service - { + if ($moduleobject == 'explorer') { // If we call page to explore details of a service $moduleobject = $regbis[2]; } @@ -248,21 +258,27 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass); $tmpmodule = $moduleobject; - if ($tmpmodule != 'api') + if ($tmpmodule != 'api') { $tmpmodule = preg_replace('/api$/i', '', $tmpmodule); + } $classfile = str_replace('_', '', $tmpmodule); // Special cases that does not match name rules conventions - if ($moduleobject == 'supplierproposals') + if ($moduleobject == 'supplierproposals') { $classfile = 'supplier_proposals'; - if ($moduleobject == 'supplierorders') + } + if ($moduleobject == 'supplierorders') { $classfile = 'supplier_orders'; - if ($moduleobject == 'supplierinvoices') + } + if ($moduleobject == 'supplierinvoices') { $classfile = 'supplier_invoices'; - if ($moduleobject == 'ficheinter') + } + if ($moduleobject == 'ficheinter') { $classfile = 'interventions'; - if ($moduleobject == 'interventions') + } + if ($moduleobject == 'interventions') { $classfile = 'interventions'; + } $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2); @@ -271,8 +287,9 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname); $res = false; - if ($dir_part_file) + if ($dir_part_file) { $res = include_once $dir_part_file; + } if (!$res) { dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING); print 'API not found (failed to include API file)'; @@ -281,8 +298,9 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && exit(0); } - if (class_exists($classname)) + if (class_exists($classname)) { $api->r->addAPIClass($classname); + } } From 3c8089af0de8ccb6647285f923facc4f39a4fbf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 17:51:46 +0100 Subject: [PATCH 08/64] code syntax bom directory --- htdocs/bom/bom_agenda.php | 117 +++---- htdocs/bom/bom_card.php | 259 +++++++-------- htdocs/bom/bom_document.php | 22 +- htdocs/bom/bom_list.php | 381 +++++++++++++---------- htdocs/bom/bom_note.php | 67 ++-- htdocs/bom/class/api_boms.class.php | 60 ++-- htdocs/bom/class/bom.class.php | 338 ++++++++++---------- htdocs/bom/lib/bom.lib.php | 21 +- htdocs/bom/tpl/linkedobjectblock.tpl.php | 7 +- htdocs/bom/tpl/objectline_create.tpl.php | 34 +- htdocs/bom/tpl/objectline_edit.tpl.php | 15 +- htdocs/bom/tpl/objectline_title.tpl.php | 13 +- htdocs/bom/tpl/objectline_view.tpl.php | 29 +- 13 files changed, 733 insertions(+), 630 deletions(-) diff --git a/htdocs/bom/bom_agenda.php b/htdocs/bom/bom_agenda.php index a7cc68d5677..2cf66d9c3f5 100644 --- a/htdocs/bom/bom_agenda.php +++ b/htdocs/bom/bom_agenda.php @@ -41,10 +41,11 @@ $action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); -if (GETPOST('actioncode', 'array')) -{ +if (GETPOST('actioncode', 'array')) { $actioncode = GETPOST('actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + if (!count($actioncode)) { + $actioncode = '0'; + } } else { $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); } @@ -59,12 +60,18 @@ $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 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} // Initialize technical objects $object = new BOM($db); @@ -76,7 +83,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; +} @@ -86,20 +95,19 @@ if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object-> $parameters = array('id'=>$socid); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers $actioncode = ''; $search_agenda_label = ''; } @@ -115,14 +123,15 @@ $contactstatic = new Contact($db); $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $title = $langs->trans("Agenda"); //if (! empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/',$conf->global->MAIN_HTML_TITLE) && $object->name) $title=$object->name." - ".$title; $help_url = ''; llxHeader('', $title, $help_url); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = bomPrepareHead($object); @@ -147,31 +156,31 @@ if ($object->id > 0) if ($user->rights->bom->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.='' . 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 .= ''; @@ -196,10 +205,11 @@ if ($object->id > 0) $out = '&origin='.$object->element.'&originid='.$object->id; $permok = $user->rights->agenda->myactions->create; - if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) - { + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { //$out.='trans("AddAnAction"),'filenew'); @@ -209,10 +219,8 @@ if ($object->id > 0) print ''; - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $param = '&id='.$object->id.'&socid='.$socid; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } //print load_fiche_titre($langs->trans("ActionsOnBom"), '', ''); diff --git a/htdocs/bom/bom_card.php b/htdocs/bom/bom_card.php index 47f1d336279..5547c21faab 100644 --- a/htdocs/bom/bom_card.php +++ b/htdocs/bom/bom_card.php @@ -37,10 +37,10 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); -$cancel = GETPOST('cancel', 'aZ09'); +$cancel = GETPOST('cancel', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'bomcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); -$lineid = GETPOST('lineid', 'int'); +$lineid = GETPOST('lineid', 'int'); // PDF $hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); @@ -59,12 +59,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. @@ -88,18 +91,22 @@ $upload_dir = $conf->bom->multidir_output[isset($object->entity) ? $object->enti $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { $error = 0; $backurlforlist = DOL_URL_ROOT.'/bom/bom_list.php'; 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_buildpath('/bom/bom_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/bom/bom_card.php', 1).'?id='.($id > 0 ? $id : '__ID__'); + } } } @@ -127,8 +134,7 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; // Add line - if ($action == 'addline' && $user->rights->bom->write) - { + if ($action == 'addline' && $user->rights->bom->write) { $langs->load('errors'); $error = 0; @@ -153,8 +159,7 @@ if (empty($reshook)) $error++; } - if (!$error) - { + if (!$error) { $bomline = new BOMLine($db); $bomline->fk_bom = $id; $bomline->fk_product = $idprod; @@ -164,10 +169,10 @@ if (empty($reshook)) $bomline->efficiency = $efficiency; // Rang to use - $rangmax = $object->line_max(0); - $ranktouse = $rangmax + 1; + $rangmax = $object->line_max(0); + $ranktouse = $rangmax + 1; - $bomline->position = ($ranktouse + 1); + $bomline->position = ($ranktouse + 1); $result = $bomline->create($user); if ($result <= 0) { @@ -179,16 +184,15 @@ if (empty($reshook)) unset($_POST['qty_frozen']); unset($_POST['disable_stock_change']); - $object->fetchLines(); + $object->fetchLines(); - $object->calculateCosts(); - } + $object->calculateCosts(); + } } } // Add line - if ($action == 'updateline' && $user->rights->bom->write) - { + if ($action == 'updateline' && $user->rights->bom->write) { $langs->load('errors'); $error = 0; @@ -211,8 +215,7 @@ if (empty($reshook)) $bomline->efficiency = $efficiency; $result = $bomline->update($user); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($bomline->error, $bomline->errors, 'errors'); $action = ''; } else { @@ -221,9 +224,9 @@ if (empty($reshook)) unset($_POST['qty_frozen']); unset($_POST['disable_stock_change']); - $object->fetchLines(); + $object->fetchLines(); - $object->calculateCosts(); + $object->calculateCosts(); } } } @@ -255,8 +258,7 @@ jQuery(document).ready(function() { // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewBOM"), '', 'bom'); print '
'; @@ -288,8 +290,7 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("BillOfMaterials"), '', 'cubes'); print ''; @@ -322,8 +323,7 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); $head = bomPrepareHead($object); @@ -332,19 +332,16 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $formconfirm = ''; // Confirmation to delete - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBillOfMaterials'), $langs->trans('ConfirmDeleteBillOfMaterials'), 'confirm_delete', '', 0, 1); } // Confirmation to delete line - if ($action == 'deleteline') - { + if ($action == 'deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } // Confirmation of validation - if ($action == 'validate') - { + if ($action == 'validate') { // We check that object has a temporary ref $ref = substr($object->ref, 1, 4); if ($ref == 'PROV') { @@ -364,13 +361,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }*/ $formquestion = array(); - if (!empty($conf->bom->enabled)) - { + if (!empty($conf->bom->enabled)) { $langs->load("mrp"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -382,8 +380,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of closing - if ($action == 'close') - { + if ($action == 'close') { $text = $langs->trans('ConfirmCloseBom', $object->ref); /*if (! empty($conf->notification->enabled)) { @@ -394,13 +391,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }*/ $formquestion = array(); - if (!empty($conf->bom->enabled)) - { + if (!empty($conf->bom->enabled)) { $langs->load("mrp"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -412,8 +410,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of reopen - if ($action == 'reopen') - { + if ($action == 'reopen') { $text = $langs->trans('ConfirmReopenBom', $object->ref); /*if (! empty($conf->notification->enabled)) { @@ -424,13 +421,14 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea }*/ $formquestion = array(); - if (!empty($conf->bom->enabled)) - { + if (!empty($conf->bom->enabled)) { $langs->load("mrp"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( // 'text' => $langs->trans("ConfirmClone"), // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -449,8 +447,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Confirmation of action xxxx - if ($action == 'setdraft') - { + if ($action == 'setdraft') { $text = $langs->trans('ConfirmSetToDraft', $object->ref); $formquestion = array(); @@ -460,8 +457,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -481,32 +481,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->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=''; - $morehtmlref.=$formproject->select_projects($object->socid, $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->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.=$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->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $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->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.=$proj->getNomUrl(); + } else { + $morehtmlref.=''; + } + } } */ $morehtmlref .= ''; @@ -544,8 +544,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea * Lines */ - if (!empty($object->table_element_line)) - { + if (!empty($object->table_element_line)) { print '
@@ -558,21 +557,17 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } print '
'; - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print ''; } - if (!empty($object->lines)) - { + if (!empty($object->lines)) { $object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1, '/bom/tpl'); } // Form to add new line - if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') - { - if ($action != 'editline') - { + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') { + if ($action != 'editline') { // Add products/services form $object->formAddObjectLine(1, $mysoc, null, '/bom/tpl'); @@ -581,8 +576,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } } - if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) - { + if (!empty($object->lines) || ($object->status == $object::STATUS_DRAFT && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { print '
'; } print '
'; @@ -597,29 +591,26 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea 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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Send //if (empty($user->socid)) { // print '' . $langs->trans('SendMail') . ''."\n"; //} // Back to draft - if ($object->status == $object::STATUS_VALIDATED) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_VALIDATED) { + if ($permissiontoadd) { print ''.$langs->trans("SetToDraft").''; } } // Modify - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { print ''.$langs->trans("Modify").''."\n"; } else { print ''.$langs->trans('Modify').''."\n"; @@ -627,12 +618,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Validate - if ($object->status == $object::STATUS_DRAFT) - { - if ($permissiontoadd) - { - if (is_array($object->lines) && count($object->lines) > 0) - { + if ($object->status == $object::STATUS_DRAFT) { + if ($permissiontoadd) { + if (is_array($object->lines) && count($object->lines) > 0) { print ''.$langs->trans("Validate").''; } else { $langs->load("errors"); @@ -642,48 +630,42 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } // Re-open - if ($permissiontoadd && $object->status == $object::STATUS_CANCELED) - { + if ($permissiontoadd && $object->status == $object::STATUS_CANCELED) { print ''.$langs->trans("ReOpen").''; } // Create MO - if ($conf->mrp->enabled) - { - if ($object->status == $object::STATUS_VALIDATED && !empty($user->rights->mrp->write)) - { + if ($conf->mrp->enabled) { + if ($object->status == $object::STATUS_VALIDATED && !empty($user->rights->mrp->write)) { print ''.$langs->trans("CreateMO").''; } } // Clone - if ($permissiontoadd) - { + if ($permissiontoadd) { print ''.$langs->trans("ToClone").''; } // Close / Cancel - if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) - { + if ($permissiontoadd && $object->status == $object::STATUS_VALIDATED) { print ''.$langs->trans("Disable").''; } /* - if ($user->rights->bom->write) - { - if ($object->status == 1) - { - print ''.$langs->trans("Disable").''."\n"; - } - else - { - print ''.$langs->trans("Enable").''."\n"; - } - } - */ - - if ($permissiontodelete) + if ($user->rights->bom->write) { + if ($object->status == 1) + { + print ''.$langs->trans("Disable").''."\n"; + } + else + { + print ''.$langs->trans("Enable").''."\n"; + } + } + */ + + if ($permissiontodelete) { print ''.$langs->trans('Delete').''."\n"; } else { print ''.$langs->trans('Delete').''."\n"; @@ -698,8 +680,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '
'; print ''; // ancre @@ -734,7 +715,9 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea } //Select mail models is same action as presend - if (GETPOST('modelselected')) $action = 'presend'; + if (GETPOST('modelselected')) { + $action = 'presend'; + } // Presend form $modelmail = 'bom'; diff --git a/htdocs/bom/bom_document.php b/htdocs/bom/bom_document.php index ddd9fe0eee6..92babe87003 100644 --- a/htdocs/bom/bom_document.php +++ b/htdocs/bom/bom_document.php @@ -50,12 +50,18 @@ $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 +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 = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} //if (! $sortfield) $sortfield="position_name"; // Initialize technical objects @@ -69,7 +75,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".get_exdir(0, 0, 0, 1, $object); +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->bom->multidir_output[$object->entity ? $object->entity : 1]."/bom/".get_exdir(0, 0, 0, 1, $object); +} /* @@ -90,8 +98,7 @@ $help_url = ''; //$help_url='EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($object->id) -{ +if ($object->id) { /* * Show tabs */ @@ -103,8 +110,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/bom/bom_list.php b/htdocs/bom/bom_list.php index 8f8c13f2556..4eaef9b096c 100644 --- a/htdocs/bom/bom_list.php +++ b/htdocs/bom/bom_list.php @@ -48,7 +48,9 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action +if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -67,14 +69,20 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // Default sort order (if not yet defined by previous GETPOST) -if (!$sortfield) $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} // Security check -if (empty($conf->bom->enabled)) accessforbidden('Module not enabled'); +if (empty($conf->bom->enabled)) { + accessforbidden('Module not enabled'); +} $socid = 0; -if ($user->socid > 0) // Protection if external user -{ +if ($user->socid > 0) { + // Protection if external user //$socid = $user->socid; accessforbidden(); } @@ -83,30 +91,31 @@ if ($user->socid > 0) // Protection if external user // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha') !== '') $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ - if ($val['searchall']) $fieldstosearchall['t.'.$key] = $val['label']; +foreach ($object->fields as $key => $val) { + if ($val['searchall']) { + $fieldstosearchall['t.'.$key] = $val['label']; + } } // Definition of fields for list $arrayfields = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // If $val['visible']==0, then we never show the field - if (!empty($val['visible'])) $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + if (!empty($val['visible'])) { + $arrayfields['t.'.$key] = array('label'=>$val['label'], 'checked'=>(($val['visible'] < 0) ? 0 : 1), 'enabled'=>($val['enabled'] && ($val['visible'] != 3)), 'position'=>$val['position']); + } } // Extra fields -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) - { +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { if (!empty($extrafields->attributes[$object->table_element]['list'][$key])) { $arrayfields["ef.".$key] = array( 'label'=>$extrafields->attributes[$object->table_element]['label'][$key], @@ -129,31 +138,33 @@ $permissiontodelete = $user->rights->bom->delete; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { - foreach ($object->fields as $key => $val) - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers + foreach ($object->fields as $key => $val) { $search[$key] = ''; } $toselect = ''; $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -167,22 +178,17 @@ if (empty($reshook)) // Validate records - if (!$error && $massaction == 'disable' && $permissiontoadd) - { + if (!$error && $massaction == 'disable' && $permissiontoadd) { $objecttmp = new $objectclass($db); - if (!$error) - { + if (!$error) { $db->begin(); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { - if ($objecttmp->status != $objecttmp::STATUS_VALIDATED) - { + if ($result > 0) { + if ($objecttmp->status != $objecttmp::STATUS_VALIDATED) { $langs->load("errors"); setEventMessages($langs->trans("ErrorObjectMustHaveStatusActiveToBeDisabled", $objecttmp->ref), null, 'errors'); $error++; @@ -191,12 +197,13 @@ if (empty($reshook)) // Can be 'cancel()' or 'close()' $result = $objecttmp->cancel($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -204,10 +211,12 @@ if (empty($reshook)) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -217,22 +226,17 @@ if (empty($reshook)) } // Validate records - if (!$error && $massaction == 'enable' && $permissiontoadd) - { + if (!$error && $massaction == 'enable' && $permissiontoadd) { $objecttmp = new $objectclass($db); - if (!$error) - { + if (!$error) { $db->begin(); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { - if ($objecttmp->status != $objecttmp::STATUS_DRAFT && $objecttmp->status != $objecttmp::STATUS_CANCELED) - { + if ($result > 0) { + if ($objecttmp->status != $objecttmp::STATUS_DRAFT && $objecttmp->status != $objecttmp::STATUS_CANCELED) { $langs->load("errors"); setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftOrDisabledToBeActivated", $objecttmp->ref), null, 'errors'); $error++; @@ -241,12 +245,13 @@ if (empty($reshook)) // Can be 'cancel()' or 'close()' $result = $objecttmp->validate($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -254,10 +259,12 @@ if (empty($reshook)) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -284,13 +291,14 @@ $title = $langs->trans('ListOfBOMs'); // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT '; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $sql .= 't.'.$key.', '; } // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.' as options_'.$key.', ' : ''); + } } // Add fields from hooks $parameters = array(); @@ -298,21 +306,33 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $obje $sql .= preg_replace('/^,/', '', $hookmanager->resPrint); $sql = preg_replace('/,\s*$/', '', $sql); $sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; -if ($object->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; -else $sql .= " WHERE 1 = 1"; -foreach ($search as $key => $val) -{ - if ($key == 'status' && $search[$key] == -1) continue; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } $mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0); if (strpos($object->fields[$key]['type'], 'integer:') === 0) { - if ($search[$key] == '-1') $search[$key] = ''; + if ($search[$key] == '-1') { + $search[$key] = ''; + } $mode_search = 2; } - if ($search[$key] != '') $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + if ($search[$key] != '') { + $sql .= natural_search($key, $search[$key], (($key == 'status') ? 2 : $mode_search)); + } } -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -341,26 +361,24 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $resql = $db->query($sql); $nbtotalofrecords = $db->num_rows($resql); - if (($page * $limit) > $nbtotalofrecords) // if total of record found is smaller than page * limit, goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0 $page = 0; $offset = 0; } } // if total of record found is smaller than limit, no need to do paging and to restart another select with limits set. -if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) -{ +if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit))) { $num = $nbtotalofrecords; } else { - if ($limit) $sql .= $db->plimit($limit + 1, $offset); + if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); + } $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); exit; } @@ -369,8 +387,7 @@ if (is_numeric($nbtotalofrecords) && ($limit > $nbtotalofrecords || empty($limit } // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/bom/bom_card.php?id='.$id); @@ -386,14 +403,24 @@ llxHeader('', $title, $help_url); $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -foreach ($search as $key => $val) -{ - if (is_array($search[$key]) && count($search[$key])) foreach ($search[$key] as $skey) $param .= '&search_'.$key.'[]='.urlencode($skey); - else $param .= '&search_'.$key.'='.urlencode($search[$key]); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +foreach ($search as $key => $val) { + if (is_array($search[$key]) && count($search[$key])) { + foreach ($search[$key] as $skey) { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } else { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); } -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -403,12 +430,18 @@ $arrayofmassactions = array( 'enable'=>$langs->trans("Enable"), 'disable'=>$langs->trans("Disable"), ); -if ($permissiontodelete) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($permissiontodelete) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -427,9 +460,10 @@ $objecttmp = new BOM($db); $trackid = 'bom'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
'; } @@ -440,11 +474,13 @@ $moreforfilter.= '
';*/ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook -if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; -else $moreforfilter = $hookmanager->resPrint; +if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} -if (!empty($moreforfilter)) -{ +if (!empty($moreforfilter)) { print '
'; print $moreforfilter; print '
'; @@ -461,20 +497,26 @@ print ''; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; } } @@ -496,15 +538,18 @@ print ''."\n"; // Fields title label // -------------------------------------------------------------------- print ''; -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n"; } } @@ -521,11 +566,11 @@ print ''."\n"; // Detect if we need a fetch on each output line $needToFetchEachLine = 0; -if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) -{ - foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) - { - if (preg_match('/\$object/', $val)) $needToFetchEachLine++; // There is at least one compute field that use $object +if (is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } } } @@ -534,38 +579,53 @@ if (is_array($extrafields->attributes[$object->table_element]['computed']) && co // -------------------------------------------------------------------- $i = 0; $totalarray = array(); -while ($i < ($limit ? min($num, $limit) : $num)) -{ +while ($i < ($limit ? min($num, $limit) : $num)) { $obj = $db->fetch_object($resql); - if (empty($obj)) break; // Should not happen + if (empty($obj)) { + break; // Should not happen + } // Store properties in $object $object->setVarsFromFetchObj($obj); // Show here line of result print ''; - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $cssforfield = (empty($val['css']) ? '' : $val['css']); - if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'center'; - elseif ($key == 'status') $cssforfield .= ($cssforfield ? ' ' : '').'center'; + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } - if (in_array($val['type'], array('timestamp'))) $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; - elseif ($key == 'ref') $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } - if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') $cssforfield .= ($cssforfield ? ' ' : '').'right'; - if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $key != 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) { + $cssforfield = 'tdoverflowmax100'; + } - if (!empty($arrayfields['t.'.$key]['checked'])) - { + if (!empty($arrayfields['t.'.$key]['checked'])) { print ''; - if ($key == 'status') print $object->getLibStatut(5); - else print $object->showOutputField($val, $key, $object->$key, ''); + if ($key == 'status') { + print $object->getLibStatut(5); + } else { + print $object->showOutputField($val, $key, $object->$key, ''); + } print ''; - if (!$i) $totalarray['nbfield']++; - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } $totalarray['val']['t.'.$key] += $object->$key; } } @@ -578,14 +638,17 @@ while ($i < ($limit ? min($num, $limit) : $num)) print $hookmanager->resPrint; // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print ''."\n"; @@ -597,10 +660,13 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; // If no record found -if ($num == 0) -{ +if ($num == 0) { $colspan = 1; - foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } print ''; } @@ -617,10 +683,11 @@ print ''."\n"; print ''."\n"; -if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) -{ +if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); diff --git a/htdocs/bom/bom_note.php b/htdocs/bom/bom_note.php index 78b38732f7f..cd288a3be3c 100644 --- a/htdocs/bom/bom_note.php +++ b/htdocs/bom/bom_note.php @@ -34,7 +34,7 @@ $langs->loadLangs(array("mrp", "companies")); $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); -$cancel = GETPOST('cancel', 'aZ09'); +$cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects @@ -53,7 +53,9 @@ $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($id > 0 || !empty($ref)) $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->bom->multidir_output[$object->entity]."/".$object->id; +} $permissionnote = 1; //$permissionnote=$user->rights->bom->creer; // Used by the include of actions_setnotes.inc.php @@ -77,8 +79,7 @@ $form = new Form($db); $help_url = ''; llxHeader('', $langs->trans('BillOfMaterials'), $help_url); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = bomPrepareHead($object); @@ -99,35 +100,35 @@ if ($id > 0 || !empty($ref)) // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='
'.$langs->trans('Project') . ' '; - if ($user->rights->bom->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.=''; - } - } + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($user->rights->bom->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 .= ''; diff --git a/htdocs/bom/class/api_boms.class.php b/htdocs/bom/class/api_boms.class.php index 563cfe35263..24ec68d0e2f 100644 --- a/htdocs/bom/class/api_boms.class.php +++ b/htdocs/bom/class/api_boms.class.php @@ -108,30 +108,42 @@ class Boms extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) $search_sale = DolibarrApiAccess::$user->id; + if ($restrictonsocid && !DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." as t"; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= " WHERE 1 = 1"; // Example of use $mode //if ($mode == 1) $sql.= " AND s.client IN (1, 3)"; //if ($mode == 2) $sql.= " AND s.client IN (2, 3)"; - if ($tmpobject->ismultientitymanaged) $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')'; - if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($restrictonsocid && $socid) $sql .= " AND t.fk_soc = ".$socid; - if ($restrictonsocid && $search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ($tmpobject->ismultientitymanaged) { + $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')'; + } + if ($restrictonsocid && (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socid) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($restrictonsocid && $socid) { + $sql .= " AND t.fk_soc = ".$socid; + } + if ($restrictonsocid && $search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($restrictonsocid && $search_sale > 0) - { + if ($restrictonsocid && $search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } - if ($sqlfilters) - { + if ($sqlfilters) { if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } @@ -141,8 +153,7 @@ class Boms extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -151,12 +162,10 @@ class Boms extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $bom_static = new BOM($this->db); if ($bom_static->fetch($obj->rowid)) { @@ -220,7 +229,9 @@ class Boms extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->bom->$field = $value; } @@ -251,8 +262,7 @@ class Boms extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if (!$this->bom->delete(DolibarrApiAccess::$user)) - { + if (!$this->bom->delete(DolibarrApiAccess::$user)) { throw new RestException(500, 'Error when deleting BOM : '.$this->bom->error); } @@ -316,8 +326,7 @@ class Boms extends DolibarrApi // If object has lines, remove $db property if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) { $nboflines = count($object->lines); - for ($i = 0; $i < $nboflines; $i++) - { + for ($i = 0; $i < $nboflines; $i++) { $this->_cleanObjectDatas($object->lines[$i]); unset($object->lines[$i]->lines); @@ -340,9 +349,12 @@ class Boms extends DolibarrApi { $myobject = array(); foreach ($this->bom->fields as $field => $propfield) { - if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) continue; // Not a mandatory field - if (!isset($data[$field])) + if (in_array($field, array('rowid', 'entity', 'date_creation', 'tms', 'fk_user_creat')) || $propfield['notnull'] != 1) { + continue; // Not a mandatory field + } + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $myobject[$field] = $data[$field]; } return $myobject; diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index 8444c4e1812..e71ec49da38 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -230,25 +230,24 @@ class BOM extends CommonObject $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -264,7 +263,9 @@ class BOM extends CommonObject */ public function create(User $user, $notrigger = false) { - if ($this->efficiency <= 0 || $this->efficiency > 1) $this->efficiency = 1; + if ($this->efficiency <= 0 || $this->efficiency > 1) { + $this->efficiency = 1; + } return $this->createCommon($user, $notrigger); } @@ -289,7 +290,9 @@ class BOM extends CommonObject // Load source object $result = $object->fetchCommon($fromid); - if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines(); + if ($result > 0 && !empty($object->table_element_line)) { + $object->fetchLines(); + } // Get lines so they will be clone //foreach ($object->lines as $line) @@ -306,14 +309,11 @@ class BOM extends CommonObject $object->status = self::STATUS_DRAFT; // ... // Clear extrafields that are unique - if (is_array($object->array_options) && count($object->array_options) > 0) - { + if (is_array($object->array_options) && count($object->array_options) > 0) { $extrafields->fetch_name_optionals_label($object->table_element); - foreach ($object->array_options as $key => $option) - { + foreach ($object->array_options as $key => $option) { $shortkey = preg_replace('/options_/', '', $key); - if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) - { + if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) { //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; unset($object->array_options[$key]); } @@ -329,22 +329,19 @@ class BOM extends CommonObject $this->errors = $object->errors; } - if (!$error) - { + if (!$error) { // copy internal contacts - if ($this->copy_linked_contact($object, 'internal') < 0) - { + if ($this->copy_linked_contact($object, 'internal') < 0) { $error++; } } - if (!$error) - { + if (!$error) { // copy external contacts if same company - if (property_exists($this, 'socid') && $this->socid == $object->socid) - { - if ($this->copy_linked_contact($object, 'external') < 0) + if (property_exists($this, 'socid') && $this->socid == $object->socid) { + if ($this->copy_linked_contact($object, 'external') < 0) { $error++; + } } } @@ -375,7 +372,9 @@ class BOM extends CommonObject { $result = $this->fetchCommon($id, $ref); - if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines(); + if ($result > 0 && !empty($this->table_element_line)) { + $this->fetchLines(); + } $this->calculateCosts(); return $result; @@ -416,8 +415,11 @@ class BOM extends CommonObject $sql = 'SELECT '; $sql .= $this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if ($this->ismultientitymanaged) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -448,8 +450,7 @@ class BOM extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $record = new self($this->db); $record->setVarsFromFetchObj($obj); @@ -475,7 +476,9 @@ class BOM extends CommonObject */ public function update(User $user, $notrigger = false) { - if ($this->efficiency <= 0 || $this->efficiency > 1) $this->efficiency = 1; + if ($this->efficiency <= 0 || $this->efficiency > 1) { + $this->efficiency = 1; + } return $this->updateCommon($user, $notrigger); } @@ -503,8 +506,7 @@ class BOM extends CommonObject */ public function deleteLine(User $user, $idline, $notrigger = false) { - if ($this->status < 0) - { + if ($this->status < 0) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -2; } @@ -524,8 +526,7 @@ class BOM extends CommonObject global $langs, $conf; $langs->load("mrp"); - if (!empty($conf->global->BOM_ADDON)) - { + if (!empty($conf->global->BOM_ADDON)) { $mybool = false; $file = $conf->global->BOM_ADDON.".php"; @@ -533,16 +534,14 @@ class BOM extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/bom/"); // Load file with numbering class (if found) $mybool |= @include_once $dir.$file; } - if ($mybool === false) - { + if ($mybool === false) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -550,8 +549,7 @@ class BOM extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($prod, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -580,27 +578,25 @@ class BOM extends CommonObject $error = 0; // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING); return 0; } /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->create)) - || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate)))) - { - $this->error='NotEnoughPermissions'; - dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); - return -1; - }*/ + || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate)))) + { + $this->error='NotEnoughPermissions'; + dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR); + return -1; + }*/ $now = dol_now(); $this->db->begin(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $this->fetch_product(); $num = $this->getNextNumRef($this->product); } else { @@ -618,50 +614,47 @@ class BOM extends CommonObject dol_syslog(get_class($this)."::validate()", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $this->error = $this->db->lasterror(); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BOM_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'bom/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->bom->dir_output.'/'.$oldref; $dirdest = $conf->bom->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->bom->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -674,14 +667,12 @@ class BOM extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->status = self::STATUS_VALIDATED; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -700,8 +691,7 @@ class BOM extends CommonObject public function setDraft($user, $notrigger = 0) { // Protection - if ($this->status <= self::STATUS_DRAFT) - { + if ($this->status <= self::STATUS_DRAFT) { return 0; } @@ -725,8 +715,7 @@ class BOM extends CommonObject public function cancel($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_VALIDATED) - { + if ($this->status != self::STATUS_VALIDATED) { return 0; } @@ -750,8 +739,7 @@ class BOM extends CommonObject public function reopen($user, $notrigger = 0) { // Protection - if ($this->status != self::STATUS_CANCELED) - { + if ($this->status != self::STATUS_CANCELED) { return 0; } @@ -780,7 +768,9 @@ class BOM extends CommonObject { global $db, $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -793,19 +783,20 @@ class BOM extends CommonObject $url = dol_buildpath('/bom/bom_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + if ($option != 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowBillOfMaterials"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -813,20 +804,26 @@ class BOM extends CommonObject $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; /* - $hookmanager->initHooks(array('bomdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + $hookmanager->initHooks(array('bomdao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = ''; $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -834,8 +831,11 @@ class BOM extends CommonObject $hookmanager->initHooks(array('bomdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -862,8 +862,7 @@ class BOM extends CommonObject public function LibStatut($status, $mode = 0) { // phpcs:enable - if (empty($this->labelStatus)) - { + if (empty($this->labelStatus)) { global $langs; //$langs->load("mrp"); $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft'); @@ -872,8 +871,12 @@ class BOM extends CommonObject } $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; - if ($status == self::STATUS_CANCELED) $statusType = 'status6'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } + if ($status == self::STATUS_CANCELED) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode); } @@ -891,28 +894,23 @@ class BOM extends CommonObject $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' WHERE t.rowid = '.$id; $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; @@ -941,8 +939,7 @@ class BOM extends CommonObject $objectline = new BOMLine($this->db); $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.$this->id)); - if (is_numeric($result)) - { + if (is_numeric($result)) { $this->error = $this->error; $this->errors = $this->errors; return $result; @@ -1051,8 +1048,7 @@ class BOM extends CommonObject } $line->unit_cost = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp); if (empty($line->unit_cost)) { - if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) - { + if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) { $line->unit_cost = $productFournisseur->fourn_unitprice; } } @@ -1197,25 +1193,24 @@ class BOMLine extends CommonObjectLine $this->db = $db; - if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0; - if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0; + if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) { + $this->fields['rowid']['visible'] = 0; + } + if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) { + $this->fields['entity']['enabled'] = 0; + } // Unset fields that are disabled - foreach ($this->fields as $key => $val) - { - if (isset($val['enabled']) && empty($val['enabled'])) - { + foreach ($this->fields as $key => $val) { + if (isset($val['enabled']) && empty($val['enabled'])) { unset($this->fields[$key]); } } // Translate some data of arrayofkeyval - foreach ($this->fields as $key => $val) - { - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) - { - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { + foreach ($this->fields as $key => $val) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + foreach ($val['arrayofkeyval'] as $key2 => $val2) { $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2); } } @@ -1231,7 +1226,9 @@ class BOMLine extends CommonObjectLine */ public function create(User $user, $notrigger = false) { - if ($this->efficiency < 0 || $this->efficiency > 1) $this->efficiency = 1; + if ($this->efficiency < 0 || $this->efficiency > 1) { + $this->efficiency = 1; + } return $this->createCommon($user, $notrigger); } @@ -1272,8 +1269,11 @@ class BOMLine extends CommonObjectLine $sql = 'SELECT '; $sql .= $this->getFieldList(); $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; - if ($this->ismultientitymanaged) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; - else $sql .= ' WHERE 1 = 1'; + if ($this->ismultientitymanaged) { + $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')'; + } else { + $sql .= ' WHERE 1 = 1'; + } // Manage filter $sqlwhere = array(); if (count($filter) > 0) { @@ -1304,8 +1304,7 @@ class BOMLine extends CommonObjectLine if ($resql) { $num = $this->db->num_rows($resql); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $record = new self($this->db); $record->setVarsFromFetchObj($obj); @@ -1331,7 +1330,9 @@ class BOMLine extends CommonObjectLine */ public function update(User $user, $notrigger = false) { - if ($this->efficiency < 0 || $this->efficiency > 1) $this->efficiency = 1; + if ($this->efficiency < 0 || $this->efficiency > 1) { + $this->efficiency = 1; + } return $this->updateCommon($user, $notrigger); } @@ -1363,7 +1364,9 @@ class BOMLine extends CommonObjectLine { global $db, $conf, $langs, $hookmanager; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; @@ -1373,19 +1376,20 @@ class BOMLine extends CommonObjectLine $url = dol_buildpath('/bom/bomline_card.php', 1).'?id='.$this->id; - if ($option != 'nolink') - { + if ($option != 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowBillOfMaterialsLine"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -1393,20 +1397,26 @@ class BOMLine extends CommonObjectLine $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; /* - $hookmanager->initHooks(array('bomlinedao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ - } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + $hookmanager->initHooks(array('bomlinedao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } $linkstart = ''; $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : ''); @@ -1414,8 +1424,11 @@ class BOMLine extends CommonObjectLine $hookmanager->initHooks(array('bomlinedao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -1458,28 +1471,23 @@ class BOMLine extends CommonObjectLine $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; $sql .= ' WHERE t.rowid = '.$id; $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_cloture) - { + if ($obj->fk_user_cloture) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_cloture); $this->user_cloture = $cluser; diff --git a/htdocs/bom/lib/bom.lib.php b/htdocs/bom/lib/bom.lib.php index 313c7a1a7ff..a5be872a096 100644 --- a/htdocs/bom/lib/bom.lib.php +++ b/htdocs/bom/lib/bom.lib.php @@ -50,7 +50,7 @@ function bomAdminPrepareHead() $head[$h][1] = $langs->trans("About"); $head[$h][2] = 'about'; $h++; - */ + */ // Show more tabs from modules // Entries must be declared in modules descriptor with line @@ -88,14 +88,19 @@ function bomPrepareHead($object) $head[$h][2] = 'card'; $h++; - if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) - { + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/bom/bom_note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.$nbNote.'' : ''); + if ($nbNote > 0) { + $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.$nbNote.'' : ''); + } $head[$h][2] = 'note'; $h++; } @@ -107,7 +112,9 @@ function bomPrepareHead($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/bom/bom_document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbFiles + $nbLinks).'' : ''); + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ''.($nbFiles + $nbLinks).'' : ''); + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/bom/tpl/linkedobjectblock.tpl.php b/htdocs/bom/tpl/linkedobjectblock.tpl.php index 3debc7e7d87..fcba37105d3 100644 --- a/htdocs/bom/tpl/linkedobjectblock.tpl.php +++ b/htdocs/bom/tpl/linkedobjectblock.tpl.php @@ -39,12 +39,13 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1) $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $product_static = new Product($db); $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } echo ''; echo ''; print ''; - if (!empty($conf->global->PRODUCT_USE_UNITS)) - { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { $coldisplay++; print ''; @@ -154,18 +156,18 @@ jQuery(document).ready(function() { { console.log("#idprod change triggered"); - /* To set focus */ - if (jQuery('#idprod').val() > 0) - { + /* To set focus */ + if (jQuery('#idprod').val() > 0) + { /* focus work on a standard textarea but not if field was replaced with CKEDITOR */ jQuery('#dp_desc').focus(); /* focus if CKEDITOR */ if (typeof CKEDITOR == "object" && typeof CKEDITOR.instances != "undefined") { var editor = CKEDITOR.instances['dp_desc']; - if (editor) { editor.focus(); } + if (editor) { editor.focus(); } + } } - } }); }); diff --git a/htdocs/bom/tpl/objectline_edit.tpl.php b/htdocs/bom/tpl/objectline_edit.tpl.php index 4d10539c824..46b57e89243 100644 --- a/htdocs/bom/tpl/objectline_edit.tpl.php +++ b/htdocs/bom/tpl/objectline_edit.tpl.php @@ -32,8 +32,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -41,7 +40,9 @@ if (empty($object) || !is_object($object)) global $forceall; -if (empty($forceall)) $forceall = 0; +if (empty($forceall)) { + $forceall = 0; +} // Define colspan for the button 'Add' @@ -79,8 +80,7 @@ if ($line->fk_product > 0) { print $tmpproduct->getNomUrl(1); } -if (is_object($hookmanager)) -{ +if (is_object($hookmanager)) { $fk_parent_line = (GETPOST('fk_parent_line') ? GETPOST('fk_parent_line') : $line->fk_parent_line); $parameters = array('line'=>$line, 'fk_parent_line'=>$fk_parent_line, 'var'=>$var, 'dateSelector'=>$dateSelector, 'seller'=>$seller, 'buyer'=>$buyer); $reshook = $hookmanager->executeHooks('formEditProductOptions', $parameters, $this, $action); @@ -90,7 +90,7 @@ print ''; /*if ($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') // We must have same test in printObjectLines { - $coldisplay++; + $coldisplay++; ?> info_bits & 2) != 2) { } print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { $coldisplay++; print ''; diff --git a/htdocs/bom/tpl/objectline_title.tpl.php b/htdocs/bom/tpl/objectline_title.tpl.php index ad9c54a34ea..d1b29ee03b0 100644 --- a/htdocs/bom/tpl/objectline_title.tpl.php +++ b/htdocs/bom/tpl/objectline_title.tpl.php @@ -34,8 +34,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -46,7 +45,9 @@ print "\n"; print ''; // Adds a line numbering column -if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) print ''; +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { + print ''; +} // Description print ''; @@ -54,8 +55,7 @@ print ''; // Qty print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; } @@ -77,8 +77,7 @@ print ''; print ''; -if ($action == 'selectlines') -{ +if ($action == 'selectlines') { print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; //Line extrafield -if (!empty($extrafields)) -{ +if (!empty($extrafields)) { print $line->showOptionals($extrafields, 'view', array('style'=>'class="drag drop oddeven"', 'colspan'=>$coldisplay), '', '', 1, 'line'); } From 70446fe28ef59fb6a663a860399a16ed50da9a46 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 17:58:31 +0100 Subject: [PATCH 09/64] code syntax cashdesk directory --- htdocs/cashdesk/admin/cashdesk.php | 37 ++++--- htdocs/cashdesk/affContenu.php | 17 ++-- htdocs/cashdesk/affIndex.php | 6 +- htdocs/cashdesk/affPied.php | 3 +- htdocs/cashdesk/class/Auth.class.php | 25 +++-- htdocs/cashdesk/class/Facturation.class.php | 57 ++++------- htdocs/cashdesk/deconnexion.php | 16 ++- htdocs/cashdesk/facturation.php | 54 +++++----- htdocs/cashdesk/facturation_dhtml.php | 61 +++++++----- htdocs/cashdesk/facturation_verif.php | 89 ++++++++--------- htdocs/cashdesk/include/environnement.php | 4 +- htdocs/cashdesk/include/keypad.php | 4 +- htdocs/cashdesk/index.php | 39 +++++--- htdocs/cashdesk/index_verif.php | 24 ++--- htdocs/cashdesk/tpl/facturation1.tpl.php | 57 ++++++----- htdocs/cashdesk/tpl/liste_articles.tpl.php | 11 +-- htdocs/cashdesk/tpl/menu.tpl.php | 18 ++-- htdocs/cashdesk/tpl/ticket.tpl.php | 76 +++++++-------- htdocs/cashdesk/tpl/validation1.tpl.php | 15 +-- htdocs/cashdesk/tpl/validation2.tpl.php | 3 +- htdocs/cashdesk/validation_ticket.php | 3 +- htdocs/cashdesk/validation_verif.php | 103 ++++++++++---------- 22 files changed, 357 insertions(+), 365 deletions(-) diff --git a/htdocs/cashdesk/admin/cashdesk.php b/htdocs/cashdesk/admin/cashdesk.php index 21e10c05fc7..382dd062131 100644 --- a/htdocs/cashdesk/admin/cashdesk.php +++ b/htdocs/cashdesk/admin/cashdesk.php @@ -27,16 +27,16 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; // If socid provided by ajax company selector -if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) -{ +if (!empty($_REQUEST['CASHDESK_ID_THIRDPARTY_id'])) { $_GET['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_POST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); $_REQUEST['CASHDESK_ID_THIRDPARTY'] = GETPOST('CASHDESK_ID_THIRDPARTY_id', 'alpha'); } // Security check -if (!$user->admin) -accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("admin", "cashdesk")); @@ -45,11 +45,12 @@ $langs->loadLangs(array("admin", "cashdesk")); /* * Actions */ -if (GETPOST('action', 'alpha') == 'set') -{ +if (GETPOST('action', 'alpha') == 'set') { $db->begin(); - if (GETPOST('socid', 'int') < 0) $_POST["socid"] = ''; + if (GETPOST('socid', 'int') < 0) { + $_POST["socid"] = ''; + } $res = dolibarr_set_const($db, "CASHDESK_ID_THIRDPARTY", (GETPOST('socid', 'int') > 0 ? GETPOST('socid', 'int') : ''), 'chaine', 0, '', $conf->entity); $res = dolibarr_set_const($db, "CASHDESK_ID_BANKACCOUNT_CASH", (GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CASH', 'alpha') : ''), 'chaine', 0, '', $conf->entity); @@ -62,10 +63,11 @@ if (GETPOST('action', 'alpha') == 'set') dol_syslog("admin/cashdesk: level ".GETPOST('level', 'alpha')); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { @@ -93,8 +95,7 @@ print '
'; print ''; print ''; -if (!empty($conf->service->enabled)) -{ +if (!empty($conf->service->enabled)) { print '
'; - if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); - elseif (strpos($val['type'], 'integer:') === 0) { + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], $search[$key], $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1); + } elseif (strpos($val['type'], 'integer:') === 0) { print $object->showInputField($val, $key, $search[$key], '', '', 'search_', 'maxwidth150', 1); - } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) print ''; + } elseif (!preg_match('/^(date|timestamp)/', $val['type'])) { + 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 - { + 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($object->id, $arrayofselected)) $selected = 1; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } print ''; } print '
'.$langs->trans("NoRecordFound").'
'.$langs->trans("Bom"); if (!empty($showImportButton) && $conf->global->MAIN_ENABLE_IMPORT_LINKED_OBJECT_LINES) { diff --git a/htdocs/bom/tpl/objectline_create.tpl.php b/htdocs/bom/tpl/objectline_create.tpl.php index 9e54fc67e8a..7cc2873b261 100644 --- a/htdocs/bom/tpl/objectline_create.tpl.php +++ b/htdocs/bom/tpl/objectline_create.tpl.php @@ -38,7 +38,9 @@ if (empty($object) || !is_object($object)) { global $forceall, $forcetoshowtitlelines; -if (empty($forceall)) $forceall = 0; +if (empty($forceall)) { + $forceall = 0; +} // Define colspan for the button 'Add' @@ -60,8 +62,7 @@ if ($nolinesbefore) { print '
'.$langs->trans('AddNewLine').''; print '
'.$langs->trans('Qty').''; print ''; print $langs->trans('Unit'); @@ -86,16 +87,18 @@ $coldisplay++; print ''; // Predefined product/service -if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) -{ - if ($forceall >= 0 && $freelines) echo '
'; +if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { + if ($forceall >= 0 && $freelines) { + echo '
'; + } echo ''; $filtertype = ''; - if (!empty($object->element) && $object->element == 'contrat' && empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) $filtertype = '1'; + if (!empty($object->element) && $object->element == 'contrat' && empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) { + $filtertype = '1'; + } $statustoshow = -1; - if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) - { + if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) { // hide products in closed warehouse, but show products for internal transfer $form->select_produits(GETPOST('idprod', 'int'), 'idprod', $filtertype, $conf->product->limit_size, $buyer->price_level, $statustoshow, 2, '', 1, array(), $buyer->id, '1', 0, 'maxwidth500', 0, 'warehouseopen,warehouseinternal', GETPOST('combinations', 'array')); } else { @@ -109,8 +112,7 @@ $coldisplay++; print '
'; print ''; print ' '; print '
  '.$langs->trans('Description').''.$langs->trans('Description').''.$form->textwithpicto($langs->trans('Qty'), $langs->trans("QtyRequiredIfNoLoss")).''.$langs->trans('Unit').''; print ''; print ''; diff --git a/htdocs/bom/tpl/objectline_view.tpl.php b/htdocs/bom/tpl/objectline_view.tpl.php index bc8506b2151..fff9d077a08 100644 --- a/htdocs/bom/tpl/objectline_view.tpl.php +++ b/htdocs/bom/tpl/objectline_view.tpl.php @@ -35,8 +35,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -44,11 +43,21 @@ if (empty($object) || !is_object($object)) global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax; -if (empty($dateSelector)) $dateSelector = 0; -if (empty($forceall)) $forceall = 0; -if (empty($senderissupplier)) $senderissupplier = 0; -if (empty($inputalsopricewithtax)) $inputalsopricewithtax = 0; -if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax = 0; +if (empty($dateSelector)) { + $dateSelector = 0; +} +if (empty($forceall)) { + $forceall = 0; +} +if (empty($senderissupplier)) { + $senderissupplier = 0; +} +if (empty($inputalsopricewithtax)) { + $inputalsopricewithtax = 0; +} +if (empty($outputalsopricetotalwithtax)) { + $outputalsopricetotalwithtax = 0; +} // add html5 elements $domData = ' data-element="'.$line->element.'"'; @@ -79,8 +88,7 @@ $coldisplay++; echo price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price print ''; $label = $tmpproduct->getLabelOfUnit('long'); if ($label !== '') { @@ -159,8 +167,7 @@ if ($action == 'selectlines') { print '
'; print ''; print ''; @@ -121,8 +122,7 @@ print ''; -if (!empty($conf->banque->enabled)) -{ +if (!empty($conf->banque->enabled)) { print ''; print ''; } -if (!empty($conf->stock->enabled)) -{ +if (!empty($conf->stock->enabled)) { print ''; // Force warehouse (this is not a default value) print ''; // Force warehouse (this is not a default value) print ' - + - + - - - - + @@ -130,8 +132,8 @@ for ($i = 0; $i < $nbtoshow; $i++) - - + +
'.$langs->trans("Parameters").''.$langs->trans("Value").'
'.$langs->trans("CashDeskThirdParty print ''; print $form->select_company($conf->global->CASHDESK_ID_THIRDPARTY, 'socid', '(s.client in (1,3) AND s.status = 1)', 1, 0, 0, array(), 0); print '
'.$langs->trans("CashDeskBankAccountForSell").''; $form->select_comptes($conf->global->CASHDESK_ID_BANKACCOUNT_CASH, 'CASHDESK_ID_BANKACCOUNT_CASH', 0, "courant=2", 1); @@ -141,8 +141,7 @@ if (!empty($conf->banque->enabled)) print '
'.$langs->trans("CashDeskDoNotDecreaseStock").''; if (empty($conf->productbatch->enabled)) { @@ -161,8 +160,7 @@ if (!empty($conf->stock->enabled)) print '
'.$langs->trans("CashDeskIdWareHouse").''; - if (!$disabled) - { + if (!$disabled) { print $formproduct->selectWarehouses($conf->global->CASHDESK_ID_WAREHOUSE, 'CASHDESK_ID_WAREHOUSE', '', 1, $disabled); print ' ('.$langs->trans("Create").')'; } else { @@ -172,8 +170,7 @@ if (!empty($conf->stock->enabled)) } // Use Dolibarr Receipt Printer -if (!empty($conf->receiptprinter->enabled)) -{ +if (!empty($conf->receiptprinter->enabled)) { print '
'; print $langs->trans("DolibarrReceiptPrinter").' ('.$langs->trans("FeatureNotYetAvailable").')'; print ''; diff --git a/htdocs/cashdesk/affContenu.php b/htdocs/cashdesk/affContenu.php index 72cb99123a4..384e3490fa1 100644 --- a/htdocs/cashdesk/affContenu.php +++ b/htdocs/cashdesk/affContenu.php @@ -25,15 +25,13 @@ require_once 'class/Facturation.class.php'; // Si nouvelle vente, reinitialisation des donnees (destruction de l'objet et vidage de la table contenant la liste des articles) -if ($_GET['id'] == 'NOUV') -{ +if ($_GET['id'] == 'NOUV') { unset($_SESSION['serObjFacturation']); unset($_SESSION['poscart']); } // Recuperation, s'il existe, de l'objet contenant les infos de la vente en cours ... -if (isset($_SESSION['serObjFacturation'])) -{ +if (isset($_SESSION['serObjFacturation'])) { $obj_facturation = unserialize($_SESSION['serObjFacturation']); unset($_SESSION['serObjFacturation']); } else { @@ -58,17 +56,18 @@ print '
'; print '
'; $page = GETPOST('menutpl', 'alpha'); -if (empty($page)) $page = 'facturation'; +if (empty($page)) { + $page = 'facturation'; +} if (in_array( - $page, - array( + $page, + array( 'deconnexion', 'index', 'index_verif', 'facturation', 'facturation_verif', 'facturation_dhtml', 'validation', 'validation_ok', 'validation_ticket', 'validation_verif', ) - )) -{ +)) { include $page.'.php'; } else { dol_print_error('', 'menu param '.$page.' is not inside allowed list'); diff --git a/htdocs/cashdesk/affIndex.php b/htdocs/cashdesk/affIndex.php index 1e3bddf1df7..931bcd76f6f 100644 --- a/htdocs/cashdesk/affIndex.php +++ b/htdocs/cashdesk/affIndex.php @@ -30,8 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/cashdesk/include/keypad.php'; $error = GETPOST('error'); // Test if already logged -if ($_SESSION['uid'] <= 0) -{ +if ($_SESSION['uid'] <= 0) { header('Location: index.php'); exit; } @@ -53,8 +52,7 @@ top_htmlhead($head, $langs->trans("CashDesk"), 0, 0, $arrayofjs, $arrayofcss); print ''."\n"; -if (!empty($error)) -{ +if (!empty($error)) { dol_htmloutput_events(); } diff --git a/htdocs/cashdesk/affPied.php b/htdocs/cashdesk/affPied.php index b3108217346..1a7c9c5b6a7 100644 --- a/htdocs/cashdesk/affPied.php +++ b/htdocs/cashdesk/affPied.php @@ -27,8 +27,7 @@ use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) -{ +if (!empty($conf->use_javascript_ajax) && empty($conf->dol_no_mouse_hover)) { print "\n\n"; print ''); diff --git a/htdocs/cashdesk/index_verif.php b/htdocs/cashdesk/index_verif.php index 45ce3857068..0c0281e5414 100644 --- a/htdocs/cashdesk/index_verif.php +++ b/htdocs/cashdesk/index_verif.php @@ -42,36 +42,31 @@ $bankid_cheque = (GETPOST("CASHDESK_ID_BANKACCOUNT_CHEQUE") > 0) ?GETPOST("CASHD $bankid_cb = (GETPOST("CASHDESK_ID_BANKACCOUNT_CB") > 0) ?GETPOST("CASHDESK_ID_BANKACCOUNT_CB", 'int') : $conf->global->CASHDESK_ID_BANKACCOUNT_CB; // Check username -if (empty($username)) -{ +if (empty($username)) { $retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Login")); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); exit; } // Check third party id -if (!($thirdpartyid > 0)) -{ +if (!($thirdpartyid > 0)) { $retour = $langs->trans("ErrorFieldRequired", $langs->transnoentities("CashDeskThirdPartyForSell")); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); exit; } // If we setup stock module to ask movement on invoices, we must not allow access if required setup not finished. -if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !($warehouseid > 0)) -{ +if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !($warehouseid > 0)) { $retour = $langs->trans("CashDeskYouDidNotDisableStockDecease"); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); exit; } // If stock decrease on bill validation, check user has stock edit permissions -if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !empty($username)) -{ +if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK) && !empty($username)) { $testuser = new User($db); $testuser->fetch(0, $username); $testuser->getrights('stock'); - if (empty($testuser->rights->stock->creer)) - { + if (empty($testuser->rights->stock->creer)) { $retour = $langs->trans("UserNeedPermissionToEditStockToUsePos"); header('Location: '.DOL_URL_ROOT.'/cashdesk/index.php?err='.urlencode($retour).'&user='.$username.'&socid='.$thirdpartyid.'&warehouseid='.$warehouseid.'&bankid_cash='.$bankid_cash.'&bankid_cheque='.$bankid_cheque.'&bankid_cb='.$bankid_cb); exit; @@ -83,8 +78,7 @@ if (!empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_S $auth = new Auth($db); $retour = $auth->verif($username, $password); -if ($retour >= 0) -{ +if ($retour >= 0) { $return = array(); $sql = "SELECT rowid, lastname, firstname"; @@ -93,12 +87,10 @@ if ($retour >= 0) $sql .= " AND entity IN (0,".$conf->entity.")"; $result = $db->query($sql); - if ($result) - { + if ($result) { $tab = $db->fetch_array($res); - foreach ($tab as $key => $value) - { + foreach ($tab as $key => $value) { $return[$key] = $value; } diff --git a/htdocs/cashdesk/tpl/facturation1.tpl.php b/htdocs/cashdesk/tpl/facturation1.tpl.php index d48fc544eb0..41a0f0b757e 100644 --- a/htdocs/cashdesk/tpl/facturation1.tpl.php +++ b/htdocs/cashdesk/tpl/facturation1.tpl.php @@ -21,8 +21,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -64,10 +63,11 @@ $id = $obj_facturation->id(); // Si trop d'articles ont ete trouves, on n'affiche que les X premiers (defini dans le fichier de configuration) ... $nbtoshow = $nbr_enreg; -if (!empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) $nbtoshow = $conf_taille_listes; +if (!empty($conf_taille_listes) && $nbtoshow > $conf_taille_listes) { + $nbtoshow = $conf_taille_listes; +} -for ($i = 0; $i < $nbtoshow; $i++) -{ +for ($i = 0; $i < $nbtoshow; $i++) { if ($id == $tab_designations[$i]['rowid']) { $selected = 'selected'; } else { @@ -96,9 +96,9 @@ for ($i = 0; $i < $nbtoshow; $i++)
trans("Qty"); ?> trans("PriceUHT"); ?> trans("Discount"); ?> (%)trans("VATRate"); ?>trans("VATRate"); ?>
@@ -106,20 +106,22 @@ for ($i = 0; $i < $nbtoshow; $i++) + + - - + + + vatrate; // To get vat rate we just have selected $buyer = new Societe($db); - if ($_SESSION["CASHDESK_ID_THIRDPARTY"] > 0) $buyer->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); + if ($_SESSION["CASHDESK_ID_THIRDPARTY"] > 0) { + $buyer->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); + } echo $form->load_tva('selTva', (GETPOSTISSET("selTva") ? GETPOST("selTva", 'alpha', 2) : $vatrate), $mysoc, $buyer, 0, 0, '', false, -1); ?> -
trans("TotalHT"); ?>
@@ -165,25 +167,28 @@ for ($i = 0; $i < $nbtoshow; $i++)
'; - if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CASH']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] < 0) - { + if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CASH']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] < 0) { $langs->load("errors"); print 'transnoentitiesnoconv("CashDesk"))).'" />'; - } else print ''; + } else { + print ''; + } print '
'; print '
'; - if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CB']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] < 0) - { + if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CB']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] < 0) { $langs->load("errors"); print 'transnoentitiesnoconv("CashDesk"))).'" />'; - } else print ''; + } else { + print ''; + } print '
'; print '
'; - if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] < 0) - { + if (empty($_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE']) || $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] < 0) { $langs->load("errors"); print 'transnoentitiesnoconv("CashDesk")).'" />'; - } else print ''; + } else { + print ''; + } print '
'; print '
'; print '
'; diff --git a/htdocs/cashdesk/tpl/liste_articles.tpl.php b/htdocs/cashdesk/tpl/liste_articles.tpl.php index e3c3c285966..74be200945f 100644 --- a/htdocs/cashdesk/tpl/liste_articles.tpl.php +++ b/htdocs/cashdesk/tpl/liste_articles.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -48,10 +47,10 @@ $societe->fetch($thirdpartyid); $tab = (!empty($_SESSION['poscart']) ? $_SESSION['poscart'] : array()); $tab_size = count($tab); -if ($tab_size <= 0) print '
'.$langs->trans("NoArticle").'

'; -else { - for ($i = 0; $i < $tab_size; $i++) - { +if ($tab_size <= 0) { + print '
'.$langs->trans("NoArticle").'

'; +} else { + for ($i = 0; $i < $tab_size; $i++) { echo ('
'."\n"); echo ('

'.$tab[$i]['ref'].' - '.$tab[$i]['label'].'

'."\n"); diff --git a/htdocs/cashdesk/tpl/menu.tpl.php b/htdocs/cashdesk/tpl/menu.tpl.php index 1e347f4d01e..67891aa67cf 100644 --- a/htdocs/cashdesk/tpl/menu.tpl.php +++ b/htdocs/cashdesk/tpl/menu.tpl.php @@ -20,8 +20,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -37,27 +36,23 @@ include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $company->fetch($_SESSION["CASHDESK_ID_THIRDPARTY"]); $companyLink = $company->getNomUrl(1); }*/ -if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) -{ +if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) { $bankcash = new Account($db); $bankcash->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]); $bankcash->label = $bankcash->ref; $bankcashLink = $bankcash->getNomUrl(1); } -if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) -{ +if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) { $bankcb = new Account($db); $bankcb->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]); $bankcbLink = $bankcb->getNomUrl(1); } -if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) -{ +if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) { $bankcheque = new Account($db); $bankcheque->fetch($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]); $bankchequeLink = $bankcheque->getNomUrl(1); } -if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled)) -{ +if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled)) { $warehouse = new Entrepot($db); $warehouse->fetch($_SESSION["CASHDESK_ID_WAREHOUSE"]); $warehouseLink = $warehouse->getNomUrl(1); @@ -87,8 +82,7 @@ print ''; print $langs->trans("CashDeskBankCB").': '.$bankcbLink.'
'; print $langs->trans("CashDeskBankCheque").': '.$bankchequeLink.'
';*/ print '
'; -if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) -{ +if (!empty($_SESSION["CASHDESK_ID_WAREHOUSE"]) && !empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) { print $langs->trans("CashDeskWarehouse").': '.$warehouseLink; } print '
'; diff --git a/htdocs/cashdesk/tpl/ticket.tpl.php b/htdocs/cashdesk/tpl/ticket.tpl.php index 101ea687e7b..9220e3daad4 100644 --- a/htdocs/cashdesk/tpl/ticket.tpl.php +++ b/htdocs/cashdesk/tpl/ticket.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -38,82 +37,81 @@ $object->fetch($facid); ?> - - <?php echo $langs->trans('PrintTicket') ?> - + + <?php echo $langs->trans('PrintTicket') ?> +
- -
-

name; ?>
-
-

+ +
+

name; ?>
+
+

-

'; print $object->ref; ?>

-
+

- + - - - - - + + + + + - - - + + - - - - - - - - + + + + + + + - +
trans("Code"); ?>trans("Label"); ?>trans("Qty"); ?>trans("Discount").' (%)'; ?>trans("TotalHT"); ?>trans("Code"); ?>trans("Label"); ?>trans("Qty"); ?>trans("Discount").' (%)'; ?>trans("TotalHT"); ?>
currency); ?>
currency); ?>
- - + + - + - +
trans("TotalHT"); ?>amountWithoutTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>trans("TotalHT"); ?>amountWithoutTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>
trans("TotalVAT").''.price(price2num($obj_facturation->amountVat(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>trans("TotalVAT").''.price(price2num($obj_facturation->amountVat(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>
trans("TotalTTC").''.price(price2num($obj_facturation->amountWithTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>trans("TotalTTC").''.price(price2num($obj_facturation->amountWithTax(), 'MT'), '', $langs, 0, -1, -1, $conf->currency)."\n"; ?>
trans("Close"); ?> diff --git a/htdocs/cashdesk/tpl/validation1.tpl.php b/htdocs/cashdesk/tpl/validation1.tpl.php index cc558cca058..c2a9124f300 100644 --- a/htdocs/cashdesk/tpl/validation1.tpl.php +++ b/htdocs/cashdesk/tpl/validation1.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -47,25 +46,27 @@ if ($obj_facturation->amountVat()) { trans("TotalTTC"); ?> amountWithTax(), 'MT'), 0, $langs, 0, 0, -1, $conf->currency); ?> trans("PaymentMode"); ?> getSetPaymentMode()) - { + switch ($obj_facturation->getSetPaymentMode()) { case 'ESP': echo $langs->trans("Cash"); $filtre = 'courant=2'; - if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) + if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"])) { $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]; + } break; case 'CB': echo $langs->trans("CreditCard"); $filtre = 'courant=1'; - if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) + if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CB"])) { $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CB"]; + } break; case 'CHQ': echo $langs->trans("Cheque"); $filtre = 'courant=1'; - if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) + if (!empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"])) { $selected = $_SESSION["CASHDESK_ID_BANKACCOUNT_CHEQUE"]; + } break; case 'DIF': echo $langs->trans("Reported"); diff --git a/htdocs/cashdesk/tpl/validation2.tpl.php b/htdocs/cashdesk/tpl/validation2.tpl.php index 8b3ca9c76d5..d89edfdc41a 100644 --- a/htdocs/cashdesk/tpl/validation2.tpl.php +++ b/htdocs/cashdesk/tpl/validation2.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } diff --git a/htdocs/cashdesk/validation_ticket.php b/htdocs/cashdesk/validation_ticket.php index 28ad91dc4e7..0c32dfa8c44 100644 --- a/htdocs/cashdesk/validation_ticket.php +++ b/htdocs/cashdesk/validation_ticket.php @@ -33,8 +33,7 @@ $hookmanager->initHooks(array('cashdeskTplTicket')); $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $obj_facturation); -if (empty($reshook)) -{ +if (empty($reshook)) { require 'tpl/ticket.tpl.php'; } diff --git a/htdocs/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php index da320c7d855..b9ad0d94a02 100644 --- a/htdocs/cashdesk/validation_verif.php +++ b/htdocs/cashdesk/validation_verif.php @@ -36,8 +36,7 @@ $obj_facturation = unserialize($_SESSION['serObjFacturation']); $action = GETPOST('action', 'aZ09'); $bankaccountid = GETPOST('cashdeskbank'); -switch ($action) -{ +switch ($action) { default: $redirection = DOL_URL_ROOT.'/cashdesk/affIndex.php?menutpl=validation'; break; @@ -55,15 +54,18 @@ switch ($action) // To use a specific numbering module for POS, reset $conf->global->FACTURE_ADDON and other vars here // and restore values just after $sav_FACTURE_ADDON = ''; - if (!empty($conf->global->POS_ADDON)) - { + if (!empty($conf->global->POS_ADDON)) { $sav_FACTURE_ADDON = $conf->global->FACTURE_ADDON; $conf->global->FACTURE_ADDON = $conf->global->POS_ADDON; // To force prefix only for POS with terre module - if (!empty($conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX)) $conf->global->INVOICE_NUMBERING_TERRE_FORCE_PREFIX = $conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX; + if (!empty($conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX)) { + $conf->global->INVOICE_NUMBERING_TERRE_FORCE_PREFIX = $conf->global->POS_NUMBERING_TERRE_FORCE_PREFIX; + } // To force prefix only for POS with mars module - if (!empty($conf->global->POS_NUMBERING_MARS_FORCE_PREFIX)) $conf->global->INVOICE_NUMBERING_MARS_FORCE_PREFIX = $conf->global->POS_NUMBERING_MARS_FORCE_PREFIX; + if (!empty($conf->global->POS_NUMBERING_MARS_FORCE_PREFIX)) { + $conf->global->INVOICE_NUMBERING_MARS_FORCE_PREFIX = $conf->global->POS_NUMBERING_MARS_FORCE_PREFIX; + } // To force rule only for POS with mercure //... } @@ -71,8 +73,7 @@ switch ($action) $num = $invoice->getNextNumRef($company); // Restore save values - if (!empty($sav_FACTURE_ADDON)) - { + if (!empty($sav_FACTURE_ADDON)) { $conf->global->FACTURE_ADDON = $sav_FACTURE_ADDON; } @@ -120,14 +121,12 @@ switch ($action) $heure = dol_print_date($now, 'hour'); $note = ''; - if (!is_object($obj_facturation)) - { + if (!is_object($obj_facturation)) { dol_print_error('', 'Empty context'); exit; } - switch ($obj_facturation->getSetPaymentMode()) - { + switch ($obj_facturation->getSetPaymentMode()) { case 'DIF': $mode_reglement_id = 0; //$cond_reglement_id = dol_getIdFromCode($db,'RECEP','cond_reglement','code','rowid') @@ -151,8 +150,12 @@ switch ($action) $cond_reglement_id = 0; break; } - if (empty($mode_reglement_id)) $mode_reglement_id = 0; // If mode_reglement_id not found - if (empty($cond_reglement_id)) $cond_reglement_id = 0; // If cond_reglement_id not found + if (empty($mode_reglement_id)) { + $mode_reglement_id = 0; // If mode_reglement_id not found + } + if (empty($cond_reglement_id)) { + $cond_reglement_id = 0; // If cond_reglement_id not found + } $note .= $_POST['txtaNotes']; dol_syslog("obj_facturation->getSetPaymentMode()=".$obj_facturation->getSetPaymentMode()." mode_reglement_id=".$mode_reglement_id." cond_reglement_id=".$cond_reglement_id); @@ -175,8 +178,7 @@ switch ($action) // Loop on each line into cart $tab_liste_size = count($tab_liste); - for ($i = 0; $i < $tab_liste_size; $i++) - { + for ($i = 0; $i < $tab_liste_size; $i++) { $tmp = getTaxesFromId($tab_liste[$i]['fk_tva']); $vat_rate = $tmp['rate']; $vat_npr = $tmp['npr']; @@ -218,32 +220,32 @@ switch ($action) //print "c=".$invoice->cond_reglement_id." m=".$invoice->mode_reglement_id; exit; // Si paiement differe ... - if ($obj_facturation->getSetPaymentMode() == 'DIF') - { + if ($obj_facturation->getSetPaymentMode() == 'DIF') { $resultcreate = $invoice->create($user, 0, dol_stringtotime($obj_facturation->paiementLe())); - if ($resultcreate > 0) - { + if ($resultcreate > 0) { $warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0); - if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice + if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) { + $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice + } $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0); - if ($warehouseidtodecrease > 0) - { + if ($warehouseidtodecrease > 0) { // Decrease require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); // Loop on each line $cpt = count($invoice->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($invoice->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($invoice->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($db); $mouvP->origin = &$invoice; // We decrease stock for product - if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); - else $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) { + $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + } else { + $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + } if ($result < 0) { $error++; } @@ -258,29 +260,30 @@ switch ($action) $id = $invoice->id; } else { $resultcreate = $invoice->create($user, 0, 0); - if ($resultcreate > 0) - { + if ($resultcreate > 0) { $warehouseidtodecrease = (isset($_SESSION["CASHDESK_ID_WAREHOUSE"]) ? $_SESSION["CASHDESK_ID_WAREHOUSE"] : 0); - if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice + if (!empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) { + $warehouseidtodecrease = 0; // If a particular stock is defined, we disable choice + } $resultvalid = $invoice->validate($user, $obj_facturation->numInvoice(), 0); - if ($warehouseidtodecrease > 0) - { + if ($warehouseidtodecrease > 0) { // Decrease require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); // Loop on each line $cpt = count($invoice->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($invoice->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($invoice->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($db); $mouvP->origin = &$invoice; // We decrease stock for product - if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); - else $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + if ($invoice->type == $invoice::TYPE_CREDIT_NOTE) { + $result = $mouvP->reception($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + } else { + $result = $mouvP->livraison($user, $invoice->lines[$i]->fk_product, $warehouseidtodecrease, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos", $invoice->newref)); + } if ($result < 0) { setEventMessages($mouvP->error, $mouvP->errors, 'errors'); $error++; @@ -301,26 +304,21 @@ switch ($action) $payment->num_payment = ''; $paiement_id = $payment->create($user); - if ($paiement_id > 0) - { - if (!$error) - { + if ($paiement_id > 0) { + if (!$error) { $result = $payment->addPaymentToBank($user, 'payment', '(CustomerInvoicePayment)', $bankaccountid, '', ''); - if (!$result > 0) - { + if (!$result > 0) { $errmsg = $paiement->error; $error++; } } - if (!$error) - { + if (!$error) { if ($invoice->total_ttc == $obj_facturation->amountWithTax() - && $obj_facturation->getSetPaymentMode() != 'DIFF') - { + && $obj_facturation->getSetPaymentMode() != 'DIFF') { // We set status to paid $result = $invoice->setPaid($user); - //print 'set paid';exit; + //print 'set paid';exit; } } } else { @@ -334,8 +332,7 @@ switch ($action) } - if (!$error) - { + if (!$error) { $db->commit(); $redirection = 'affIndex.php?menutpl=validation_ok&facid='.$id; // Ajout de l'id de la facture, pour l'inclure dans un lien pointant directement vers celle-ci dans Dolibarr } else { From 6fcb7a96a1afd058b627d6acd47e9c7a9a2d398a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 18:04:37 +0100 Subject: [PATCH 10/64] code syntax categorie collab directory --- htdocs/categories/admin/categorie.php | 23 +- .../admin/categorie_extrafields.php | 17 +- htdocs/categories/card.php | 111 +++---- .../categories/class/api_categories.class.php | 31 +- htdocs/categories/class/categorie.class.php | 156 ++++++--- htdocs/categories/edit.php | 13 +- htdocs/categories/index.php | 63 ++-- htdocs/categories/info.php | 10 +- htdocs/categories/photos.php | 85 +++-- htdocs/categories/traduction.php | 79 +++-- htdocs/categories/viewcat.php | 300 ++++++++---------- htdocs/collab/index.php | 86 +++-- 12 files changed, 505 insertions(+), 469 deletions(-) diff --git a/htdocs/categories/admin/categorie.php b/htdocs/categories/admin/categorie.php index 693a3e53a2a..bddeb9a771a 100644 --- a/htdocs/categories/admin/categorie.php +++ b/htdocs/categories/admin/categorie.php @@ -27,8 +27,9 @@ require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/categories.lib.php'; -if (!$user->admin) -accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array("categories", "admin")); @@ -40,11 +41,9 @@ $action = GETPOST('action', 'aZ09'); */ $reg = array(); -if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) - { + if (dolibarr_set_const($db, $code, 1, 'chaine', 0, '', $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -52,11 +51,9 @@ if (preg_match('/set_([a-z0-9_\-]+)/i', $action, $reg)) } } -if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) -{ +if (preg_match('/del_([a-z0-9_\-]+)/i', $action, $reg)) { $code = $reg[1]; - if (dolibarr_del_const($db, $code, $conf->entity) > 0) - { + if (dolibarr_del_const($db, $code, $conf->entity) > 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; } else { @@ -100,12 +97,10 @@ print ''.$langs->trans("CategorieRecursiv").''; print ''.$form->textwithpicto('', $langs->trans("CategorieRecursivHelp"), 1, 'help').''; print ''; -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print ajax_constantonoff('CATEGORIE_RECURSIV_ADD'); } else { - if (empty($conf->global->CATEGORIE_RECURSIV_ADD)) - { + if (empty($conf->global->CATEGORIE_RECURSIV_ADD)) { print ''.img_picto($langs->trans("Disabled"), 'off').''; } else { print ''.img_picto($langs->trans("Enabled"), 'on').''; diff --git a/htdocs/categories/admin/categorie_extrafields.php b/htdocs/categories/admin/categorie_extrafields.php index ff6a4ca7881..0d691995c29 100644 --- a/htdocs/categories/admin/categorie_extrafields.php +++ b/htdocs/categories/admin/categorie_extrafields.php @@ -37,13 +37,17 @@ $form = new Form($db); // List of supported format $tmptype2label = ExtraFields::$type2label; $type2label = array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); +foreach ($tmptype2label as $key => $val) { + $type2label[$key] = $langs->transnoentitiesnoconv($val); +} $action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'categorie'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -76,8 +80,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -90,8 +93,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -103,8 +105,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/categories/card.php b/htdocs/categories/card.php index 74e16f9082d..5b54666b674 100644 --- a/htdocs/categories/card.php +++ b/htdocs/categories/card.php @@ -37,14 +37,16 @@ $langs->load("categories"); // Security check $socid = (int) GETPOST('socid', 'int'); -if (!$user->rights->categorie->lire) accessforbidden(); +if (!$user->rights->categorie->lire) { + accessforbidden(); +} -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'alpha'); $origin = GETPOST('origin', 'alpha'); $catorigin = (int) GETPOST('catorigin', 'int'); -$type = GETPOST('type', 'aZ09'); -$urlfrom = GETPOST('urlfrom', 'alpha'); +$type = GETPOST('type', 'aZ09'); +$urlfrom = GETPOST('urlfrom', 'alpha'); $backtopage = GETPOST('backtopage', 'alpha'); $label = (string) GETPOST('label', 'alphanohtml'); @@ -54,15 +56,29 @@ $visible = (int) GETPOST('visible', 'int'); $parent = (int) GETPOST('parent', 'int'); if ($origin) { - if ($type == Categorie::TYPE_PRODUCT) $idProdOrigin = $origin; - if ($type == Categorie::TYPE_SUPPLIER) $idSupplierOrigin = $origin; - if ($type == Categorie::TYPE_CUSTOMER) $idCompanyOrigin = $origin; - if ($type == Categorie::TYPE_MEMBER) $idMemberOrigin = $origin; - if ($type == Categorie::TYPE_CONTACT) $idContactOrigin = $origin; - if ($type == Categorie::TYPE_PROJECT) $idProjectOrigin = $origin; + if ($type == Categorie::TYPE_PRODUCT) { + $idProdOrigin = $origin; + } + if ($type == Categorie::TYPE_SUPPLIER) { + $idSupplierOrigin = $origin; + } + if ($type == Categorie::TYPE_CUSTOMER) { + $idCompanyOrigin = $origin; + } + if ($type == Categorie::TYPE_MEMBER) { + $idMemberOrigin = $origin; + } + if ($type == Categorie::TYPE_CONTACT) { + $idContactOrigin = $origin; + } + if ($type == Categorie::TYPE_PROJECT) { + $idProjectOrigin = $origin; + } } -if ($catorigin && $type == Categorie::TYPE_PRODUCT) $idCatOrigin = $catorigin; +if ($catorigin && $type == Categorie::TYPE_PRODUCT) { + $idCatOrigin = $catorigin; +} $object = new Categorie($db); @@ -80,13 +96,10 @@ $error = 0; */ // Add action -if ($action == 'add' && $user->rights->categorie->creer) -{ +if ($action == 'add' && $user->rights->categorie->creer) { // Action ajout d'une categorie - if ($cancel) - { - if ($urlfrom) - { + if ($cancel) { + if ($urlfrom) { header("Location: ".$urlfrom); exit; } elseif ($backtopage) { @@ -125,24 +138,25 @@ if ($action == 'add' && $user->rights->categorie->creer) $object->visible = $visible; $object->type = $type; - if ($parent != "-1") $object->fk_parent = $parent; + if ($parent != "-1") { + $object->fk_parent = $parent; + } $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$object->label) - { + if (!$object->label) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); $action = 'create'; } // Create category in database - if (!$error) - { + if (!$error) { $result = $object->create($user); - if ($result > 0) - { + if ($result > 0) { $action = 'confirmed'; $_POST["addcat"] = ''; } else { @@ -152,41 +166,31 @@ if ($action == 'add' && $user->rights->categorie->creer) } // Confirm action -if (($action == 'add' || $action == 'confirmed') && $user->rights->categorie->creer) -{ +if (($action == 'add' || $action == 'confirmed') && $user->rights->categorie->creer) { // Action confirmation de creation categorie - if ($action == 'confirmed') - { - if ($urlfrom) - { + if ($action == 'confirmed') { + if ($urlfrom) { header("Location: ".$urlfrom); exit; - } elseif ($backtopage) - { + } elseif ($backtopage) { header("Location: ".$backtopage); exit; - } elseif ($idProdOrigin) - { + } elseif ($idProdOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProdOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idCompanyOrigin) - { + } elseif ($idCompanyOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idCompanyOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idSupplierOrigin) - { + } elseif ($idSupplierOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idSupplierOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idMemberOrigin) - { + } elseif ($idMemberOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idMemberOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idContactOrigin) - { + } elseif ($idContactOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idContactOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; - } elseif ($idProjectOrigin) - { + } elseif ($idProjectOrigin) { header("Location: ".DOL_URL_ROOT.'/categories/viewcat.php?id='.$idProjectOrigin.'&type='.$type.'&mesg='.urlencode($langs->trans("CatCreated"))); exit; } @@ -207,11 +211,9 @@ $formother = new FormOther($db); $helpurl = ''; llxHeader("", $langs->trans("Categories"), $helpurl); -if ($user->rights->categorie->creer) -{ +if ($user->rights->categorie->creer) { // Create or add - if ($action == 'create' || GETPOST("addcat") == 'addcat') - { + if ($action == 'create' || GETPOST("addcat") == 'addcat') { dol_set_focus('#label'); print '
'; @@ -222,8 +224,12 @@ if ($user->rights->categorie->creer) print ''; print ''; print ''; - if ($origin) print ''; - if ($catorigin) print ''; + if ($origin) { + print ''; + } + if ($catorigin) { + print ''; + } print load_fiche_titre($langs->trans("CreateCat")); @@ -257,8 +263,7 @@ if ($user->rights->categorie->creer) $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)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index 03610100c9c..65483a561af 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -140,15 +140,12 @@ class Categories extends DolibarrApi $sql = "SELECT t.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."categorie as t"; $sql .= ' WHERE t.entity IN ('.getEntity('category').')'; - if (!empty($type)) - { + if (!empty($type)) { $sql .= ' AND t.type='.array_search($type, Categories::$TYPES); } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -157,8 +154,7 @@ class Categories extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -167,13 +163,11 @@ class Categories extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $category_static = new Categorie($this->db); if ($category_static->fetch($obj->rowid)) { @@ -181,8 +175,7 @@ class Categories extends DolibarrApi } $i++; } - } - else { + } else { throw new RestException(503, 'Error when retrieve category list : '.$this->db->lasterror()); } if (!count($obj_ret)) { @@ -238,7 +231,9 @@ class Categories extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->category->$field = $value; } @@ -721,8 +716,9 @@ class Categories extends DolibarrApi { $category = array(); foreach (Categories::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $category[$field] = $data[$field]; } return $category; @@ -747,8 +743,7 @@ class Categories extends DolibarrApi throw new RestException(401); } - if (empty($type)) - { + if (empty($type)) { throw new RestException(500, 'The "type" parameter is required.'); } diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index a050c21c249..d83bc794baa 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -98,7 +98,7 @@ class Categorie extends CommonObject 8 => 'bank_line', 9 => 'warehouse', 10 => 'actioncomm', - 11 => 'website_page' + 11 => 'website_page' ); /** @@ -197,7 +197,7 @@ class Categorie extends CommonObject /** * @var string Category label */ - public $label; + public $label; /** * @var string description @@ -231,9 +231,9 @@ class Categorie extends CommonObject * @see Categorie::TYPE_PROJECT * @see Categorie::TYPE_ACCOUNT * @see Categorie::TYPE_BANK_LINE - * @see Categorie::TYPE_WAREHOUSE - * @see Categorie::TYPE_ACTIONCOMM - * @see Categorie::TYPE_WEBSITE_PAGE + * @see Categorie::TYPE_WAREHOUSE + * @see Categorie::TYPE_ACTIONCOMM + * @see Categorie::TYPE_WEBSITE_PAGE */ public $type; @@ -266,9 +266,9 @@ class Categorie extends CommonObject $mapList = $hookmanager->resArray; $mapId = $mapList['id']; $mapCode = $mapList['code']; - self::$MAP_ID_TO_CODE[$mapId] = $mapCode; - $this->MAP_ID[$mapCode] = $mapId; - $this->MAP_CAT_FK[$mapCode] = $mapList['cat_fk']; + self::$MAP_ID_TO_CODE[$mapId] = $mapCode; + $this->MAP_ID[$mapCode] = $mapId; + $this->MAP_CAT_FK[$mapCode] = $mapList['cat_fk']; $this->MAP_CAT_TABLE[$mapCode] = $mapList['cat_table']; $this->MAP_OBJ_CLASS[$mapCode] = $mapList['obj_class']; $this->MAP_OBJ_TABLE[$mapCode] = $mapList['obj_table']; @@ -313,8 +313,12 @@ class Categorie extends CommonObject global $conf; // Check parameters - if (empty($id) && empty($label) && empty($ref_ext)) return -1; - if (!is_null($type) && !is_numeric($type)) $type = $this->MAP_ID[$type]; + if (empty($id) && empty($label) && empty($ref_ext)) { + return -1; + } + if (!is_null($type) && !is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } $sql = "SELECT rowid, fk_parent, entity, label, description, color, fk_soc, visible, type, ref_ext"; $sql .= ", date_creation, tms, fk_user_creat, fk_user_modif"; @@ -325,7 +329,9 @@ class Categorie extends CommonObject $sql .= " WHERE ref_ext LIKE '".$this->db->escape($ref_ext)."'"; } else { $sql .= " WHERE label = '".$this->db->escape($label)."' AND entity IN (".getEntity('category').")"; - if (!is_null($type)) $sql .= " AND type = ".((int) $type); + if (!is_null($type)) { + $sql .= " AND type = ".((int) $type); + } } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); @@ -357,7 +363,9 @@ class Categorie extends CommonObject $this->db->free($resql); // multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) $this->getMultiLangs(); + if (!empty($conf->global->MAIN_MULTILANGS)) { + $this->getMultiLangs(); + } return 1; } else { @@ -387,7 +395,9 @@ class Categorie extends CommonObject $type = $this->type; - if (!is_numeric($type)) $type = $this->MAP_ID[$type]; + if (!is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } $error = 0; @@ -399,7 +409,9 @@ class Categorie extends CommonObject $this->color = trim($this->color); $this->import_key = trim($this->import_key); $this->ref_ext = trim($this->ref_ext); - if (empty($this->visible)) $this->visible = 0; + if (empty($this->visible)) { + $this->visible = 0; + } $this->fk_parent = ($this->fk_parent != "" ? intval($this->fk_parent) : 0); if ($this->already_exists()) { @@ -463,7 +475,9 @@ class Categorie extends CommonObject if (!$error) { // Call trigger $result = $this->call_trigger('CATEGORY_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -542,7 +556,9 @@ class Categorie extends CommonObject if (!$error) { // Call trigger $result = $this->call_trigger('CATEGORY_MODIFY', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers } @@ -579,7 +595,9 @@ class Categorie extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CATEGORY_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -649,9 +667,13 @@ class Categorie extends CommonObject $error = 0; - if ($this->id == -1) return -2; + if ($this->id == -1) { + return -2; + } - if (empty($type)) $type = $obj->element; + if (empty($type)) { + $type = $obj->element; + } $this->db->begin(); @@ -699,7 +721,9 @@ class Categorie extends CommonObject // Call trigger $this->context = array('linkto'=>$obj); // Save object we want to link category to into category instance to provide information to trigger $result = $this->call_trigger('CATEGORY_LINK', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers if (!$error) { @@ -757,7 +781,9 @@ class Categorie extends CommonObject // Call trigger $this->context = array('unlinkoff'=>$obj); // Save object we want to link category to into category instance to provide information to trigger $result = $this->call_trigger('CATEGORY_UNLINK', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers if (!$error) { @@ -805,7 +831,9 @@ class Categorie extends CommonObject if (($type == 'customer' || $type == 'supplier') && $user->socid > 0) { $sql .= " AND o.rowid = ".$user->socid; } - if ($limit > 0 || $offset > 0) $sql .= $this->db->plimit($limit + 1, $offset); + if ($limit > 0 || $offset > 0) { + $sql .= $this->db->plimit($limit + 1, $offset); + } $sql .= $this->db->order($sortfield, $sortorder); dol_syslog(get_class($this)."::getObjectsInCateg", LOG_DEBUG); @@ -1037,7 +1065,9 @@ class Categorie extends CommonObject // phpcs:enable global $conf, $langs; - if (!is_numeric($type)) $type = $this->MAP_ID[$type]; + if (!is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } if (is_null($type)) { $this->error = 'BadValueForParameterType'; return -1; @@ -1063,9 +1093,13 @@ class Categorie extends CommonObject // Init $this->cats array $sql = "SELECT DISTINCT c.rowid, c.label, c.ref_ext, c.description, c.color, c.fk_parent, c.visible"; // Distinct reduce pb with old tables with duplicates - if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= ", t.label as label_trans, t.description as description_trans"; + if (!empty($conf->global->MAIN_MULTILANGS)) { + $sql .= ", t.label as label_trans, t.description as description_trans"; + } $sql .= " FROM ".MAIN_DB_PREFIX."categorie as c"; - if (!empty($conf->global->MAIN_MULTILANGS)) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'"; + if (!empty($conf->global->MAIN_MULTILANGS)) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_lang as t ON t.fk_category=c.rowid AND t.lang='".$this->db->escape($current_lang)."'"; + } $sql .= " WHERE c.entity IN (".getEntity('category').")"; $sql .= " AND c.type = ".(int) $type; @@ -1204,14 +1238,18 @@ class Categorie extends CommonObject public function get_all_categories($type = null, $parent = false) { // phpcs:enable - if (!is_numeric($type)) $type = $this->MAP_ID[$type]; + if (!is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."categorie"; $sql .= " WHERE entity IN (".getEntity('category').")"; - if (!is_null($type)) + if (!is_null($type)) { $sql .= " AND type = ".(int) $type; - if ($parent) + } + if ($parent) { $sql .= " AND fk_parent = 0"; + } $res = $this->db->query($sql); if ($res) { @@ -1252,7 +1290,9 @@ class Categorie extends CommonObject // phpcs:enable $type = $this->type; - if (!is_numeric($type)) $type = $this->MAP_ID[$type]; + if (!is_numeric($type)) { + $type = $this->MAP_ID[$type]; + } /* We have to select any rowid from llx_categorie which category's mother and label * are equals to those of the calling category @@ -1318,7 +1358,9 @@ class Categorie extends CommonObject // Check contrast with background and correct text color $forced_color = 'categtextwhite'; if ($cat->color) { - if (colorIsLight($cat->color)) $forced_color = 'categtextblack'; + if (colorIsLight($cat->color)) { + $forced_color = 'categtextblack'; + } } } } @@ -1399,8 +1441,9 @@ class Categorie extends CommonObject } } - if (count($ways) == 0) + if (count($ways) == 0) { $ways[0][0] = $this; + } return $ways; } @@ -1419,7 +1462,9 @@ class Categorie extends CommonObject { $cats = array(); - if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; + if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; + } if ($type === Categorie::TYPE_BANK_LINE) { // TODO Remove this with standard category code after migration of llx_bank_categ into llx_categorie // Load bank categories @@ -1509,11 +1554,14 @@ class Categorie extends CommonObject $sql .= " WHERE type = ".$this->MAP_ID[$type]; $sql .= " AND entity IN (".getEntity('category').")"; if ($nom) { - if (!$exact) + if (!$exact) { $nom = '%'.str_replace('*', '%', $nom).'%'; - if (!$case) + } + if (!$case) { $sql .= " AND label LIKE '".$this->db->escape($nom)."'"; - else $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'"; + } else { + $sql .= " AND label LIKE BINARY '".$this->db->escape($nom)."'"; + } } if ($id) { $sql .= " AND rowid = '".$id."'"; @@ -1554,7 +1602,9 @@ class Categorie extends CommonObject // Check contrast with background and correct text color $forced_color = 'categtextwhite'; if ($this->color) { - if (colorIsLight($this->color)) $forced_color = 'categtextblack'; + if (colorIsLight($this->color)) { + $forced_color = 'categtextblack'; + } } $link = ''; @@ -1563,9 +1613,15 @@ class Categorie extends CommonObject $picto = 'category'; - if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.dol_trunc(($this->ref ? $this->ref : $this->label), $maxlength).$linkend; + } return $result; } @@ -1653,13 +1709,18 @@ class Categorie extends CommonObject // Objet $obj = array(); $obj['photo'] = $photo; - if ($photo_vignette && is_file($dirthumb.$photo_vignette)) $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; - else $obj['photo_vignette'] = ""; + if ($photo_vignette && is_file($dirthumb.$photo_vignette)) { + $obj['photo_vignette'] = 'thumbs/'.$photo_vignette; + } else { + $obj['photo_vignette'] = ""; + } $tabobj[$nbphoto - 1] = $obj; // On continue ou on arrete de boucler - if ($nbmax && $nbphoto >= $nbmax) break; + if ($nbmax && $nbphoto >= $nbmax) { + break; + } } } @@ -1764,8 +1825,9 @@ class Categorie extends CommonObject } // on ne sauvegarde pas des champs vides - if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"]) + if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"] || $this->multilangs["$key"]["note"]) { dol_syslog(get_class($this).'::setMultiLangs', LOG_DEBUG); + } if (!$this->db->query($sql2)) { $this->error = $this->db->lasterror(); return -1; @@ -1876,7 +1938,9 @@ class Categorie extends CommonObject */ public static function getFilterJoinQuery($type, $rowIdName) { - if ($type == 'bank_account') $type = 'account'; + if ($type == 'bank_account') { + $type = 'account'; + } return " LEFT JOIN ".MAIN_DB_PREFIX."categorie_".$type." as cp ON ".$rowIdName." = cp.fk_".$type; } @@ -1891,7 +1955,9 @@ class Categorie extends CommonObject */ public static function getFilterSelectQuery($type, $rowIdName, $searchList) { - if ($type == 'bank_account') $type = 'account'; + if ($type == 'bank_account') { + $type = 'account'; + } if (empty($searchList) && !is_array($searchList)) { return ""; diff --git a/htdocs/categories/edit.php b/htdocs/categories/edit.php index a5578032a3d..176b39ca008 100644 --- a/htdocs/categories/edit.php +++ b/htdocs/categories/edit.php @@ -62,7 +62,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); @@ -90,7 +92,7 @@ if ($cancel) { // Action mise a jour d'une categorie if ($action == 'update' && $user->rights->categorie->creer) { $object->oldcopy = dol_clone($object); - $object->label = $label; + $object->label = $label; $object->description = dol_htmlcleanlastbr($description); $object->color = $color; $object->socid = ($socid > 0 ? $socid : 0); @@ -105,10 +107,11 @@ if ($action == 'update' && $user->rights->categorie->creer) { } if (!$error && empty($object->error)) { $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error && $object->update($user) > 0) - { + if (!$error && $object->update($user) > 0) { if ($backtopage) { header("Location: ".$backtopage); exit; diff --git a/htdocs/categories/index.php b/htdocs/categories/index.php index ff897db86a7..aa2dc20e2b2 100644 --- a/htdocs/categories/index.php +++ b/htdocs/categories/index.php @@ -34,7 +34,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; // Load translation files required by the page $langs->load("categories"); -if (!$user->rights->categorie->lire) accessforbidden(); +if (!$user->rights->categorie->lire) { + accessforbidden(); +} $id = GETPOST('id', 'int'); $type = (GETPOST('type', 'aZ09') ? GETPOST('type', 'aZ09') : Categorie::TYPE_PRODUCT); @@ -42,7 +44,9 @@ $catname = GETPOST('catname', 'alpha'); $nosearch = GETPOST('nosearch', 'int'); $categstatic = new Categorie($db); -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} /* @@ -54,11 +58,15 @@ $form = new Form($db); $moreparam = ($nosearch ? '&nosearch=1' : ''); $typetext = $type; -if ($type == Categorie::TYPE_ACCOUNT) $title = $langs->trans('AccountsCategoriesArea'); -elseif ($type == Categorie::TYPE_WAREHOUSE) $title = $langs->trans('StocksCategoriesArea'); -elseif ($type == Categorie::TYPE_ACTIONCOMM) $title = $langs->trans('ActionCommCategoriesArea'); -elseif ($type == Categorie::TYPE_WEBSITE_PAGE) $title = $langs->trans('WebsitePagesCategoriesArea'); -else { +if ($type == Categorie::TYPE_ACCOUNT) { + $title = $langs->trans('AccountsCategoriesArea'); +} elseif ($type == Categorie::TYPE_WAREHOUSE) { + $title = $langs->trans('StocksCategoriesArea'); +} elseif ($type == Categorie::TYPE_ACTIONCOMM) { + $title = $langs->trans('ActionCommCategoriesArea'); +} elseif ($type == Categorie::TYPE_WEBSITE_PAGE) { + $title = $langs->trans('WebsitePagesCategoriesArea'); +} else { $title = $langs->trans(ucfirst($type).'sCategoriesArea'); } @@ -100,15 +108,13 @@ if (empty($nosearch)) { /* * Categories found */ - if ($catname || $id > 0) - { + if ($catname || $id > 0) { $cats = $categstatic->rechercher($id, $catname, $typetext); print ''; print ''; - foreach ($cats as $cat) - { + foreach ($cats as $cat) { $color = $categstatic->color ? ' style="background: #'.sprintf("%06s", $categstatic->color).';"' : ' style="background: #bbb"'; print "\t".''."\n"; @@ -128,7 +134,9 @@ if (empty($nosearch)) { print "\t\n"; } print "
'.$langs->trans("FoundCats").'
"; - } else print ' '; + } else { + print ' '; + } print '
'; } @@ -143,19 +151,25 @@ $cate_arbo = $categstatic->get_full_arbo($typetext); $fulltree = $cate_arbo; // Load possible missing includes -if ($conf->global->CATEGORY_SHOW_COUNTS) -{ - if ($type == Categorie::TYPE_MEMBER) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - if ($type == Categorie::TYPE_ACCOUNT) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - if ($type == Categorie::TYPE_PROJECT) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - if ($type == Categorie::TYPE_USER) require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; +if ($conf->global->CATEGORY_SHOW_COUNTS) { + if ($type == Categorie::TYPE_MEMBER) { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + } + if ($type == Categorie::TYPE_ACCOUNT) { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + } + if ($type == Categorie::TYPE_PROJECT) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + } + if ($type == Categorie::TYPE_USER) { + require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + } } // Define data (format for treeview) $data = array(); $data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); -foreach ($fulltree as $key => $val) -{ +foreach ($fulltree as $key => $val) { $categstatic->id = $val['id']; $categstatic->ref = $val['label']; $categstatic->color = $val['color']; @@ -163,8 +177,7 @@ foreach ($fulltree as $key => $val) $desc = dol_htmlcleanlastbr($val['description']); $counter = ''; - if ($conf->global->CATEGORY_SHOW_COUNTS) - { + if ($conf->global->CATEGORY_SHOW_COUNTS) { // we need only a count of the elements, so it is enough to consume only the id's from the database $elements = $type == Categorie::TYPE_ACCOUNT ? $categstatic->getObjectsInCateg("account", 1) // Categorie::TYPE_ACCOUNT is "bank_account" instead of "account" @@ -206,15 +219,13 @@ foreach ($fulltree as $key => $val) print ''; print ''; $nbofentries = (count($data) - 1); -if ($nbofentries > 0) -{ +if ($nbofentries > 0) { print ''; diff --git a/htdocs/categories/info.php b/htdocs/categories/info.php index 536b0c20a2c..5666664b848 100644 --- a/htdocs/categories/info.php +++ b/htdocs/categories/info.php @@ -20,7 +20,7 @@ /** * \file htdocs/categories/info.php * \ingroup categories - * \brief Category info page + * \brief Category info page */ require '../main.inc.php'; @@ -40,7 +40,9 @@ $id = GETPOST('id', 'int'); $label = GETPOST('label', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'categorie', $id, '&category'); $object = new Categorie($db); @@ -50,7 +52,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} /* * View diff --git a/htdocs/categories/photos.php b/htdocs/categories/photos.php index 6bb5d79980c..cfc722df83f 100644 --- a/htdocs/categories/photos.php +++ b/htdocs/categories/photos.php @@ -38,11 +38,10 @@ $langs->loadlangs(array('categories', 'bills')); $id = GETPOST('id', 'int'); $label = GETPOST('label', 'alpha'); -$action = GETPOST('action', 'aZ09'); +$action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm'); -if ($id == '' && $label == '') -{ +if ($id == '' && $label == '') { dol_print_error('', 'Missing parameter id'); exit(); } @@ -57,7 +56,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} $upload_dir = $conf->categorie->multidir_output[$object->entity]; @@ -65,16 +66,12 @@ $upload_dir = $conf->categorie->multidir_output[$object->entity]; * Actions */ -if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sendit"] && !empty($conf->global->MAIN_UPLOAD_DOC)) -{ +if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sendit"] && !empty($conf->global->MAIN_UPLOAD_DOC)) { if ($object->id) { $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])) - { + 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]); } @@ -87,13 +84,11 @@ if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0 && $_POST["sen } } -if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer) -{ +if ($action == 'confirm_delete' && $_GET["file"] && $confirm == 'yes' && $user->rights->categorie->creer) { $object->delete_photo($upload_dir."/".$_GET["file"]); } -if ($action == 'addthumb' && $_GET["file"]) -{ +if ($action == 'addthumb' && $_GET["file"]) { $object->addThumbs($upload_dir."/".$_GET["file"]); } @@ -107,8 +102,7 @@ llxHeader("", "", $langs->trans("Categories")); $form = new Form($db); $formother = new FormOther($db); -if ($object->id) -{ +if ($object->id) { $title = Categorie::$MAP_TYPE_TITLE_AREA[$type]; $head = categories_prepare_head($object, $type); @@ -119,8 +113,7 @@ if ($object->id) $object->ref = $object->label; $morehtmlref = '
'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); - foreach ($ways as $way) - { + foreach ($ways as $way) { $morehtmlref .= $way."
\n"; } $morehtmlref .= '
'; @@ -130,8 +123,7 @@ if ($object->id) /* * Confirmation de la suppression de photo */ - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&file='.$_GET["file"], $langs->trans('DeletePicture'), $langs->trans('ConfirmDeletePicture'), 'confirm_delete', '', 0, 1); } @@ -168,10 +160,8 @@ if ($object->id) print '
'."\n"; - if ($action != 'ajout_photo' && $user->rights->categorie->creer) - { - if (!empty($conf->global->MAIN_UPLOAD_DOC)) - { + if ($action != 'ajout_photo' && $user->rights->categorie->creer) { + if (!empty($conf->global->MAIN_UPLOAD_DOC)) { print ''; print $langs->trans("AddPhoto").''; } else { @@ -185,16 +175,14 @@ if ($object->id) /* * Ajouter une photo */ - if ($action == 'ajout_photo' && $user->rights->categorie->creer && !empty($conf->global->MAIN_UPLOAD_DOC)) - { + if ($action == 'ajout_photo' && $user->rights->categorie->creer && !empty($conf->global->MAIN_UPLOAD_DOC)) { // Affiche formulaire upload $formfile = new FormFile($db); $formfile->form_attach_new_file($_SERVER['PHP_SELF'].'?id='.$object->id.'&type='.$type, $langs->trans("AddPhoto"), 1, '', $user->rights->categorie->creer, 50, $object, '', false, '', 0); } // Affiche photos - if ($action != 'ajout_photo') - { + if ($action != 'ajout_photo') { $nbphoto = 0; $nbbyrow = 5; @@ -206,23 +194,24 @@ if ($object->id) $listofphoto = $object->liste_photos($dir); - if (is_array($listofphoto) && count($listofphoto)) - { + if (is_array($listofphoto) && count($listofphoto)) { print '
'; print '
'.$langs->trans("Categories").''; -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print ''; } print '
'; tree_recur($data, $data[0], 0); print '
'; - foreach ($listofphoto as $key => $obj) - { + foreach ($listofphoto as $key => $obj) { $nbphoto++; - if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) print ''; - if ($nbbyrow) print ''; + } + if ($nbbyrow) { + print ''; - if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) print ''; + if ($nbbyrow) { + print ''; + } + if ($nbbyrow && ($nbphoto % $nbbyrow == 0)) { + print ''; + } } // Ferme tableau - while ($nbphoto % $nbbyrow) - { + while ($nbphoto % $nbbyrow) { print ''; $nbphoto++; } @@ -266,8 +256,7 @@ if ($object->id) print '
'; + if ($nbbyrow && ($nbphoto % $nbbyrow == 1)) { + print '
'; + } print ''; // Si fichier vignette disponible, on l'utilise, sinon on utilise photo origine - if ($obj['photo_vignette']) - { + if ($obj['photo_vignette']) { $filename = $obj['photo_vignette']; } else { $filename = $obj['photo']; @@ -243,22 +232,23 @@ if ($object->id) 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)) - { + 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) - { + if ($user->rights->categorie->creer) { print ''; print img_delete().''; } - if ($nbbyrow) print '
 
'; } - if ($nbphoto < 1) - { + if ($nbphoto < 1) { print '
'.$langs->trans("NoPhotoYet")."
"; } } diff --git a/htdocs/categories/traduction.php b/htdocs/categories/traduction.php index 898484d0d51..9f2ed6936ef 100644 --- a/htdocs/categories/traduction.php +++ b/htdocs/categories/traduction.php @@ -35,13 +35,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; // Load translation files required by the page $langs->loadLangs(array('categories', 'languages')); -$id = GETPOST('id', 'int'); -$label = GETPOST('label', 'alpha'); +$id = GETPOST('id', 'int'); +$label = GETPOST('label', 'alpha'); $action = GETPOST('action', 'aZ09'); $cancel = GETPOST('cancel', 'alpha'); -if ($id == '' && $label == '') -{ +if ($id == '' && $label == '') { dol_print_error('', 'Missing parameter id'); exit(); } @@ -56,7 +55,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} /* * Actions @@ -64,8 +65,7 @@ if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backwar $error = 0; // retour a l'affichage des traduction si annulation -if ($cancel == $langs->trans("Cancel")) -{ +if ($cancel == $langs->trans("Cancel")) { $action = ''; } @@ -73,8 +73,7 @@ if ($cancel == $langs->trans("Cancel")) // Validation de l'ajout if ($action == 'vadd' && $cancel != $langs->trans("Cancel") && -($user->rights->categorie->creer)) -{ +($user->rights->categorie->creer)) { $object->fetch($id); $current_lang = $langs->getDefaultLang(); @@ -106,7 +105,9 @@ $cancel != $langs->trans("Cancel") && // sauvegarde en base $res = $object->setMultiLangs($user); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } } @@ -121,13 +122,11 @@ $cancel != $langs->trans("Cancel") && // Validation de l'edition if ($action == 'vedit' && $cancel != $langs->trans("Cancel") && -($user->rights->categorie->creer)) -{ +($user->rights->categorie->creer)) { $object->fetch($id); $current_lang = $langs->getDefaultLang(); - foreach ($object->multilangs as $key => $value) // enregistrement des nouvelles valeurs dans l'objet - { + foreach ($object->multilangs as $key => $value) { // enregistrement des nouvelles valeurs dans l'objet $libelle = GETPOST('libelle-'.$key, 'alpha'); $desc = GETPOST('desc-'.$key); @@ -147,7 +146,9 @@ $cancel != $langs->trans("Cancel") && if (!$error) { $res = $object->setMultiLangs($user); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } if ($error) { @@ -175,10 +176,8 @@ $head = categories_prepare_head($object, $type); // Calculate $cnt_trans $cnt_trans = 0; -if (!empty($object->multilangs)) -{ - foreach ($object->multilangs as $key => $value) - { +if (!empty($object->multilangs)) { + foreach ($object->multilangs as $key => $value) { $cnt_trans++; } } @@ -232,12 +231,12 @@ print dol_get_fiche_end(); print "\n
\n"; -if ($action == '') -{ - if ($user->rights->produit->creer || $user->rights->service->creer) - { +if ($action == '') { + if ($user->rights->produit->creer || $user->rights->service->creer) { print ''.$langs->trans('Add').''; - if ($cnt_trans > 0) print ''.$langs->trans('Update').''; + if ($cnt_trans > 0) { + print ''.$langs->trans('Update').''; + } } } @@ -245,8 +244,7 @@ print "\n
\n"; -if ($action == 'edit') -{ +if ($action == 'edit') { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -256,10 +254,8 @@ if ($action == 'edit') print ''; print ''; - if (!empty($object->multilangs)) - { - foreach ($object->multilangs as $key => $value) - { + if (!empty($object->multilangs)) { + foreach ($object->multilangs as $key => $value) { print "
".$langs->trans('Language_'.$key)." :
"; print ''; @@ -287,27 +283,27 @@ if ($action == 'edit') print ''; print ''; -} elseif ($action != 'add') -{ - if ($cnt_trans) print '
'; +} elseif ($action != 'add') { + if ($cnt_trans) { + print '
'; + } - if (!empty($object->multilangs)) - { - foreach ($object->multilangs as $key => $value) - { + if (!empty($object->multilangs)) { + foreach ($object->multilangs as $key => $value) { $s = picto_from_langcode($key); print '
'; print ''; print ''; print ''; - if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION)) - { + if (!empty($conf->global->CATEGORY_USE_OTHER_FIELD_IN_TRANSLATION)) { 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"].'
'; } } - if (!$cnt_trans && $action != 'add') print '
'.$langs->trans('NoTranslation').'
'; + if (!$cnt_trans && $action != 'add') { + print '
'.$langs->trans('NoTranslation').'
'; + } } @@ -315,8 +311,7 @@ if ($action == 'edit') * Form to add a new translation */ -if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service->creer)) -{ +if ($action == 'add' && ($user->rights->produit->creer || $user->rights->service->creer)) { //WYSIWYG Editor require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; diff --git a/htdocs/categories/viewcat.php b/htdocs/categories/viewcat.php index 187691293e4..7f19194a3c3 100644 --- a/htdocs/categories/viewcat.php +++ b/htdocs/categories/viewcat.php @@ -49,7 +49,7 @@ $cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'categorylist'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page -$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') // Load variable for pagination @@ -57,13 +57,14 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action +if (empty($page) || $page == -1 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha') || (empty($toselect) && $massaction === '0')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters or if we select empty mass action $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if ($id == "" && $label == "") -{ +if ($id == "" && $label == "") { dol_print_error('', 'Missing parameter id'); exit(); } @@ -78,7 +79,9 @@ if ($result <= 0) { } $type = $object->type; -if (is_numeric($type)) $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +if (is_numeric($type)) { + $type = Categorie::$MAP_ID_TO_CODE[$type]; // For backward compatibility +} $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); @@ -90,8 +93,7 @@ $hookmanager->initHooks(array('categorycard', 'globalcard')); * Actions */ -if ($confirm == 'no') -{ +if ($confirm == 'no') { if ($backtopage) { header("Location: ".$backtopage); exit; @@ -101,26 +103,21 @@ if ($confirm == 'no') $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks // Remove element from category -if ($id > 0 && $removeelem > 0) -{ - if ($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer)) - { +if ($id > 0 && $removeelem > 0) { + if ($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer)) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $tmpobject = new Product($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'product'; - } elseif ($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer) - { + } elseif ($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer) { $tmpobject = new Societe($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'supplier'; - } elseif ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) - { + } elseif ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) { $tmpobject = new Societe($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'customer'; - } elseif ($type == Categorie::TYPE_MEMBER && $user->rights->adherent->creer) - { + } elseif ($type == Categorie::TYPE_MEMBER && $user->rights->adherent->creer) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $tmpobject = new Adherent($db); $result = $tmpobject->fetch($removeelem); @@ -130,20 +127,17 @@ if ($id > 0 && $removeelem > 0) $tmpobject = new Contact($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'contact'; - } elseif ($type == Categorie::TYPE_ACCOUNT && $user->rights->banque->configurer) - { + } elseif ($type == Categorie::TYPE_ACCOUNT && $user->rights->banque->configurer) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $tmpobject = new Account($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'account'; - } elseif ($type == Categorie::TYPE_PROJECT && $user->rights->projet->creer) - { + } elseif ($type == Categorie::TYPE_PROJECT && $user->rights->projet->creer) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $tmpobject = new Project($db); $result = $tmpobject->fetch($removeelem); $elementtype = 'project'; - } elseif ($type == Categorie::TYPE_USER && $user->rights->user->user->creer) - { + } elseif ($type == Categorie::TYPE_USER && $user->rights->user->user->creer) { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $tmpobject = new User($db); $result = $tmpobject->fetch($removeelem); @@ -151,13 +145,13 @@ if ($id > 0 && $removeelem > 0) } $result = $object->del_type($tmpobject, $elementtype); - if ($result < 0) dol_print_error('', $object->error); + if ($result < 0) { + dol_print_error('', $object->error); + } } -if ($user->rights->categorie->supprimer && $action == 'confirm_delete' && $confirm == 'yes') -{ - if ($object->delete($user) >= 0) - { +if ($user->rights->categorie->supprimer && $action == 'confirm_delete' && $confirm == 'yes') { + if ($object->delete($user) >= 0) { if ($backtopage) { header("Location: ".$backtopage); exit; @@ -174,20 +168,16 @@ if ($elemid && $action == 'addintocategory' && (($type == Categorie::TYPE_PRODUCT && ($user->rights->produit->creer || $user->rights->service->creer)) || ($type == Categorie::TYPE_CUSTOMER && $user->rights->societe->creer) || ($type == Categorie::TYPE_SUPPLIER && $user->rights->societe->creer) - )) -{ - if ($type == Categorie::TYPE_PRODUCT) - { + )) { + if ($type == Categorie::TYPE_PRODUCT) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; $newobject = new Product($db); $elementtype = 'product'; - } elseif ($type == Categorie::TYPE_CUSTOMER) - { + } elseif ($type == Categorie::TYPE_CUSTOMER) { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $newobject = new Societe($db); $elementtype = 'customer'; - } elseif ($type == Categorie::TYPE_SUPPLIER) - { + } elseif ($type == Categorie::TYPE_SUPPLIER) { require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; $newobject = new Societe($db); $elementtype = 'supplier'; @@ -196,12 +186,10 @@ if ($elemid && $action == 'addintocategory' && // TODO Add into categ $result = $object->add_type($newobject, $elementtype); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("WasAddedSuccessfully", $newobject->ref), null, 'mesgs'); } else { - if ($cat->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($cat->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { setEventMessages($langs->trans("ObjectAlreadyLinkedToCategory"), null, 'warnings'); } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -233,8 +221,7 @@ $object->next_prev_filter = ' type = '.$object->type; $object->ref = $object->label; $morehtmlref = '
'.$langs->trans("Root").' >> '; $ways = $object->print_all_ways(" >> ", '', 1); -foreach ($ways as $way) -{ +foreach ($ways as $way) { $morehtmlref .= $way."
\n"; } $morehtmlref .= '
'; @@ -246,8 +233,7 @@ dol_banner_tab($object, 'label', $linkback, ($user->socid ? 0 : 1), 'label', 'la * Confirmation suppression */ -if ($action == 'delete') -{ +if ($action == 'delete') { if ($backtopage) { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&type='.$type.'&backtopage='.urlencode($backtopage), $langs->trans('DeleteCategory'), $langs->trans('ConfirmDeleteCategory'), 'confirm_delete', '', '', 2); } else { @@ -288,16 +274,16 @@ print dol_get_fiche_end(); print "
\n"; $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} if (empty($reshook)) { - if ($user->rights->categorie->creer) - { + if ($user->rights->categorie->creer) { $socid = ($object->socid ? "&socid=".$object->socid : ""); print ''.$langs->trans("Modify").''; } - if ($user->rights->categorie->supprimer) - { + if ($user->rights->categorie->supprimer) { print 'id.'&type='.$type.'&backtolist='.urlencode($backtolist).'">'.$langs->trans("Delete").''; } } @@ -305,8 +291,7 @@ if (empty($reshook)) { print "
"; $newcardbutton = ''; -if (!empty($user->rights->categorie->creer)) -{ +if (!empty($user->rights->categorie->creer)) { $link = DOL_URL_ROOT.'/categories/card.php'; $link .= '?action=create'; $link .= '&type='.$type; @@ -335,8 +320,7 @@ print ''.$langs->trans("SubCats").''; print ''; print ''; -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print '
'; print ''.img_picto('', 'folder').' '.$langs->trans("UndoExpandAll").''; print " | "; @@ -348,11 +332,9 @@ print ''; print ''; $cats = $object->get_filles(); -if ($cats < 0) -{ +if ($cats < 0) { dol_print_error($db, $object->error, $object->errors); -} elseif (count($cats) < 1) -{ +} elseif (count($cats) < 1) { print ''; print ''.$langs->trans("NoSubCat").''; print ''; @@ -362,19 +344,25 @@ if ($cats < 0) $fulltree = $categstatic->get_full_arbo($type, $object->id, 1); // Load possible missing includes - if ($conf->global->CATEGORY_SHOW_COUNTS) - { - if ($type == Categorie::TYPE_MEMBER) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; - if ($type == Categorie::TYPE_ACCOUNT) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - if ($type == Categorie::TYPE_PROJECT) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; - if ($type == Categorie::TYPE_USER) require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + if ($conf->global->CATEGORY_SHOW_COUNTS) { + if ($type == Categorie::TYPE_MEMBER) { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; + } + if ($type == Categorie::TYPE_ACCOUNT) { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + } + if ($type == Categorie::TYPE_PROJECT) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; + } + if ($type == Categorie::TYPE_USER) { + require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; + } } // Define data (format for treeview) $data = array(); $data[] = array('rowid'=>0, 'fk_menu'=>-1, 'title'=>"racine", 'mainmenu'=>'', 'leftmenu'=>'', 'fk_mainmenu'=>'', 'fk_leftmenu'=>''); - foreach ($fulltree as $key => $val) - { + foreach ($fulltree as $key => $val) { $categstatic->id = $val['id']; $categstatic->ref = $val['label']; $categstatic->color = $val['color']; @@ -382,8 +370,7 @@ if ($cats < 0) $desc = dol_htmlcleanlastbr($val['description']); $counter = ''; - if ($conf->global->CATEGORY_SHOW_COUNTS) - { + if ($conf->global->CATEGORY_SHOW_COUNTS) { // we need only a count of the elements, so it is enough to consume only the id's from the database $elements = $type == Categorie::TYPE_ACCOUNT ? $categstatic->getObjectsInCateg("account", 1) // Categorie::TYPE_ACCOUNT is "bank_account" instead of "account" @@ -421,8 +408,7 @@ if ($cats < 0) } $nbofentries = (count($data) - 1); - if ($nbofentries > 0) - { + if ($nbofentries > 0) { require_once DOL_DOCUMENT_ROOT.'/core/lib/treeview.lib.php'; print ''; print ''; @@ -465,19 +451,16 @@ $typeid = $type; // List of products or services (type is type of category) -if ($type == Categorie::TYPE_PRODUCT) -{ +if ($type == Categorie::TYPE_PRODUCT) { $permission = ($user->rights->produit->creer || $user->rights->service->creer); $prods = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($prods < 0) - { + if ($prods < 0) { dol_print_error($db, $object->error, $object->errors); } else { // Form to add record into a category $showclassifyform = 1; - if ($showclassifyform) - { + if ($showclassifyform) { print '
'; print '
'; print ''; @@ -510,13 +493,13 @@ if ($type == Categorie::TYPE_PRODUCT) print ''."\n"; print ''."\n"; - if (count($prods) > 0) - { + if (count($prods) > 0) { $i = 0; - foreach ($prods as $prod) - { + foreach ($prods as $prod) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; print ''; print ''; - if ($num) - { + if ($num) { $i = 0; $tot_ttc = 0; $othernb = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); if ($i >= $max) { @@ -822,8 +836,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) /* * Customers orders to be billed */ -if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user->rights->commande->lire && empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) -{ +if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user->rights->commande->lire && empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) { $commandestatic = new Commande($db); $langs->load("orders"); @@ -834,14 +847,20 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user $sql .= ", c.rowid, c.ref, c.facture, c.fk_statut as status, c.total_ht, c.total_tva, c.total_ttc,"; $sql .= " cc.rowid as country_id, cc.code as country_code"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ", ".MAIN_DB_PREFIX."commande as c"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_source = c.rowid AND el.sourcetype = 'commande'"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."facture AS f ON el.fk_target = f.rowid AND el.targettype = 'facture'"; $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity = ".$conf->entity; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND c.fk_soc = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; + } $sql .= " AND c.fk_statut = ".Commande::STATUS_CLOSED; $sql .= " AND c.facture = 0"; // Add where from hooks @@ -852,12 +871,10 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user $sql .= " GROUP BY s.nom, s.email, s.rowid, s.code_client, s.code_compta, c.rowid, c.ref, c.facture, c.fk_statut, c.total_ht, c.total_tva, c.total_ttc, cc.rowid, cc.code"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; $othernb = 0; @@ -872,7 +889,9 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user print ''; print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; @@ -880,8 +899,7 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user $tot_ht = $tot_ttc = $tot_tobill = 0; $societestatic = new Societe($db); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); if ($i >= $max) { @@ -930,7 +948,9 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; @@ -951,7 +971,9 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user } print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; @@ -967,8 +989,7 @@ if (!empty($conf->facture->enabled) && !empty($conf->commande->enabled) && $user /* * Unpaid customers invoices */ -if (!empty($conf->facture->enabled) && $user->rights->facture->lire) -{ +if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $tmpinvoice = new Facture($db); $sql = "SELECT f.rowid, f.ref, f.fk_statut as status, f.datef, f.type, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.paye, f.tms"; @@ -980,11 +1001,17 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $sql .= ", sum(pf.amount) as am"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays,".MAIN_DB_PREFIX."facture as f"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.rowid = f.fk_soc AND f.paye = 0 AND f.fk_statut = ".Facture::STATUS_VALIDATED; $sql .= " AND f.entity IN (".getEntity('invoice').')'; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhereCustomerUnpaid', $parameters); @@ -995,8 +1022,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $sql .= " ORDER BY f.datef ASC, f.ref ASC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $othernb = 0; @@ -1013,17 +1039,17 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) print ''; print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; print ''; - if ($num) - { + if ($num) { $societestatic = new Societe($db); $total_ttc = $totalam = $total = 0; - while ($i < $num && $i < $conf->liste_limit) - { + while ($i < $num && $i < $conf->liste_limit) { $obj = $db->fetch_object($resql); if ($i >= $max) { @@ -1079,7 +1105,9 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) print $societestatic->getNomUrl(1, 'customer'); print ''; print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; @@ -1094,7 +1122,9 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) if ($othernb) { $colspan = 6; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + $colspan++; + } print ''; print ''; print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; print ''; } else { $colspan = 6; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + $colspan++; + } print ''; } print '
'.$langs->trans("Ref").'
'; @@ -525,8 +508,7 @@ if ($type == Categorie::TYPE_PRODUCT) print ''.$prod->label."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -544,19 +526,16 @@ if ($type == Categorie::TYPE_PRODUCT) } } -if ($type == Categorie::TYPE_CUSTOMER) -{ +if ($type == Categorie::TYPE_CUSTOMER) { $permission = $user->rights->societe->creer; $socs = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($socs < 0) - { + if ($socs < 0) { dol_print_error($db, $object->error, $object->errors); } else { // Form to add record into a category $showclassifyform = 1; - if ($showclassifyform) - { + if ($showclassifyform) { print '
'; print ''; print ''; @@ -588,13 +567,13 @@ if ($type == Categorie::TYPE_CUSTOMER) print ''."\n"; print ''."\n"; - if (count($socs) > 0) - { + if (count($socs) > 0) { $i = 0; - foreach ($socs as $key => $soc) - { + foreach ($socs as $key => $soc) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; print ''; print ''; - if ($num) - { + if ($num) { $total_ttc = $totalam = $total = 0; - while ($i < $num && $i < $max) - { + while ($i < $num && $i < $max) { $objp = $db->fetch_object($result); if ($i >= $max) { @@ -694,7 +709,9 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) $donationstatic->status = $objp->status; $label = $donationstatic->getFullName($langs); - if ($objp->societe) $label .= ($label ? ' - ' : '').$objp->societe; + if ($objp->societe) { + $label .= ($label ? ' - ' : '').$objp->societe; + } print ''; print ''; @@ -718,16 +735,16 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) print ''; } print '
'.$langs->trans("Name").'
'; @@ -602,8 +581,7 @@ if ($type == Categorie::TYPE_CUSTOMER) print "'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -622,19 +600,16 @@ if ($type == Categorie::TYPE_CUSTOMER) } -if ($type == Categorie::TYPE_SUPPLIER) -{ +if ($type == Categorie::TYPE_SUPPLIER) { $permission = $user->rights->societe->creer; $socs = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($socs < 0) - { + if ($socs < 0) { dol_print_error($db, $object->error, $object->errors); } else { // Form to add record into a category $showclassifyform = 1; - if ($showclassifyform) - { + if ($showclassifyform) { print '
'; print ''; print ''; @@ -666,13 +641,13 @@ if ($type == Categorie::TYPE_SUPPLIER) print ''."\n"; print '\n"; - if (count($socs) > 0) - { + if (count($socs) > 0) { $i = 0; - foreach ($socs as $soc) - { + foreach ($socs as $soc) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; $result .= ''; $result .= ''; - } - elseif ($total > 0) - { + } elseif ($total > 0) { $result .= ''; $result .= ''; $result .= ''; diff --git a/htdocs/compta/facture/info.php b/htdocs/compta/facture/info.php index f26f4ea0255..97646d56103 100644 --- a/htdocs/compta/facture/info.php +++ b/htdocs/compta/facture/info.php @@ -71,15 +71,14 @@ $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_cl // Thirdparty $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') + 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 .= ''; diff --git a/htdocs/compta/facture/invoicetemplate_list.php b/htdocs/compta/facture/invoicetemplate_list.php index 6f3f8088a63..d45439286fb 100644 --- a/htdocs/compta/facture/invoicetemplate_list.php +++ b/htdocs/compta/facture/invoicetemplate_list.php @@ -59,9 +59,13 @@ $socid = GETPOST('socid', 'int'); $id = (GETPOST('facid', 'int') ?GETPOST('facid', 'int') : GETPOST('id', 'int')); $lineid = GETPOST('lineid', 'int'); $ref = GETPOST('ref', 'alpha'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $objecttype = 'facture_rec'; -if ($action == "create" || $action == "add") $objecttype = ''; +if ($action == "create" || $action == "add") { + $objecttype = ''; +} $result = restrictedArea($user, 'facture', $id, $objecttype); $search_ref = GETPOST('search_ref'); @@ -86,19 +90,23 @@ $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 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; -if (!$sortorder) $sortorder = 'DESC'; -if (!$sortfield) $sortfield = 'f.titre'; +if (!$sortorder) { + $sortorder = 'DESC'; +} +if (!$sortfield) { + $sortfield = 'f.titre'; +} $pageprev = $page - 1; $pagenext = $page + 1; $object = new FactureRec($db); -if (($id > 0 || $ref) && $action != 'create' && $action != 'add') -{ +if (($id > 0 || $ref) && $action != 'create' && $action != 'add') { $ret = $object->fetch($id, $ref); - if (!$ret) - { + if (!$ret) { setEventMessages($langs->trans("ErrorRecordNotFound"), null, 'errors'); } } @@ -143,37 +151,47 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); if ($socid > 0) { $tmpthirdparty = new Societe($db); $res = $tmpthirdparty->fetch($socid); - if ($res > 0) $search_societe = $tmpthirdparty->name; + if ($res > 0) { + $search_societe = $tmpthirdparty->name; + } } if ($socid > 0) { $tmpthirdparty = new Societe($db); $res = $tmpthirdparty->fetch($socid); - if ($res > 0) $search_societe = $tmpthirdparty->name; + if ($res > 0) { + $search_societe = $tmpthirdparty->name; + } } /* * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $parameters = array('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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if (GETPOST('cancel', 'alpha')) $action = ''; +if (empty($reshook)) { + if (GETPOST('cancel', 'alpha')) { + $action = ''; + } // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? - 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 - { + 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_ref = ''; $search_societe = ''; $search_montant_ht = ''; @@ -196,11 +214,11 @@ if (empty($reshook)) // Mass actions /*$objectclass='MyObject'; - $objectlabel='MyObject'; - $permissiontoread = $user->rights->mymodule->read; - $permissiontodelete = $user->rights->mymodule->delete; - $uploaddir = $conf->mymodule->dir_output; - include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/ + $objectlabel='MyObject'; + $permissiontoread = $user->rights->mymodule->read; + $permissiontodelete = $user->rights->mymodule->delete; + $uploaddir = $conf->mymodule->dir_output; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';*/ } @@ -212,7 +230,9 @@ llxHeader('', $langs->trans("RepeatableInvoices"), 'ch-facture.html#s-fac-factur $form = new Form($db); $formother = new FormOther($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $companystatic = new Societe($db); $invoicerectmp = new FactureRec($db); @@ -231,7 +251,9 @@ $sql .= " f.datec, f.tms,"; $sql .= " f.fk_cond_reglement, f.fk_mode_reglement"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); @@ -249,23 +271,52 @@ $sql .= ' AND f.entity IN ('.getEntity('invoice').')'; if (!$user->rights->societe->client->voir && !$socid) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } -if ($search_ref) $sql .= natural_search('f.titre', $search_ref); -if ($socid) $sql .= ' AND s.rowid = '.(int) $socid; -if ($search_societe) $sql .= natural_search('s.nom', $search_societe); -if ($search_montant_ht != '') $sql .= natural_search('f.total', $search_montant_ht, 1); -if ($search_montant_vat != '') $sql .= natural_search('f.tva', $search_montant_vat, 1); -if ($search_montant_ttc != '') $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1); -if (!empty($search_payment_mode) && $search_payment_mode != '-1') $sql .= natural_search('f.fk_mode_reglement', $search_payment_mode, 1); -if (!empty($search_payment_term) && $search_payment_term != '-1') $sql .= natural_search('f.fk_cond_reglement', $search_payment_term, 1); -if ($search_recurring == '1') $sql .= ' AND f.frequency > 0'; -if ($search_recurring == '0') $sql .= ' AND (f.frequency IS NULL or f.frequency = 0)'; -if ($search_frequency != '') $sql .= natural_search('f.frequency', $search_frequency, 1); -if ($search_unit_frequency != '') $sql .= ' AND f.frequency > 0'.natural_search('f.unit_frequency', $search_unit_frequency); -if ($search_status != '' && $search_status >= -1) -{ - if ($search_status == 0) $sql .= ' AND frequency = 0 AND suspended = 0'; - if ($search_status == 1) $sql .= ' AND frequency != 0 AND suspended = 0'; - if ($search_status == -1) $sql .= ' AND suspended = 1'; +if ($search_ref) { + $sql .= natural_search('f.titre', $search_ref); +} +if ($socid) { + $sql .= ' AND s.rowid = '.(int) $socid; +} +if ($search_societe) { + $sql .= natural_search('s.nom', $search_societe); +} +if ($search_montant_ht != '') { + $sql .= natural_search('f.total', $search_montant_ht, 1); +} +if ($search_montant_vat != '') { + $sql .= natural_search('f.tva', $search_montant_vat, 1); +} +if ($search_montant_ttc != '') { + $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1); +} +if (!empty($search_payment_mode) && $search_payment_mode != '-1') { + $sql .= natural_search('f.fk_mode_reglement', $search_payment_mode, 1); +} +if (!empty($search_payment_term) && $search_payment_term != '-1') { + $sql .= natural_search('f.fk_cond_reglement', $search_payment_term, 1); +} +if ($search_recurring == '1') { + $sql .= ' AND f.frequency > 0'; +} +if ($search_recurring == '0') { + $sql .= ' AND (f.frequency IS NULL or f.frequency = 0)'; +} +if ($search_frequency != '') { + $sql .= natural_search('f.frequency', $search_frequency, 1); +} +if ($search_unit_frequency != '') { + $sql .= ' AND f.frequency > 0'.natural_search('f.unit_frequency', $search_unit_frequency); +} +if ($search_status != '' && $search_status >= -1) { + if ($search_status == 0) { + $sql .= ' AND frequency = 0 AND suspended = 0'; + } + if ($search_status == 1) { + $sql .= ' AND frequency != 0 AND suspended = 0'; + } + if ($search_status == -1) { + $sql .= ' AND suspended = 1'; + } } $sql .= dolSqlDateFilter('f.date_last_gen', $search_day, $search_month, $search_year); $sql .= dolSqlDateFilter('f.date_when', $search_day_date_when, $search_month_date_when, $search_year_date_when); @@ -273,12 +324,10 @@ $sql .= dolSqlDateFilter('f.date_when', $search_day_date_when, $search_month_dat $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -287,32 +336,73 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if ($resql) -{ +if ($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 ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($search_day) $param .= '&search_day='.urlencode($search_day); - if ($search_month) $param .= '&search_month='.urlencode($search_month); - if ($search_year) $param .= '&search_year='.urlencode($search_year); - if ($search_day_date_when) $param .= '&search_day_date_when='.urlencode($search_day_date_when); - if ($search_month_date_when) $param .= '&search_month_date_when='.urlencode($search_month_date_when); - if ($search_year_date_when) $param .= '&search_year_date_when='.urlencode($search_year_date_when); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_societe) $param .= '&search_societe='.urlencode($search_societe); - if ($search_montant_ht != '') $param .= '&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_vat != '') $param .= '&search_montant_vat='.urlencode($search_montant_vat); - if ($search_montant_ttc != '') $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); - if ($search_payment_mode != '') $param .= '&search_payment_mode='.urlencode($search_payment_mode); - if ($search_payment_term != '') $param .= '&search_payment_term='.urlencode($search_payment_term); - if ($search_recurring != '' && $search_recurrning != '-1') $param .= '&search_recurring='.urlencode($search_recurring); - if ($search_frequency > 0) $param .= '&search_frequency='.urlencode($search_frequency); - if ($search_unit_frequency != '') $param .= '&search_unit_frequency='.urlencode($search_unit_frequency); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($search_day) { + $param .= '&search_day='.urlencode($search_day); + } + if ($search_month) { + $param .= '&search_month='.urlencode($search_month); + } + if ($search_year) { + $param .= '&search_year='.urlencode($search_year); + } + if ($search_day_date_when) { + $param .= '&search_day_date_when='.urlencode($search_day_date_when); + } + if ($search_month_date_when) { + $param .= '&search_month_date_when='.urlencode($search_month_date_when); + } + if ($search_year_date_when) { + $param .= '&search_year_date_when='.urlencode($search_year_date_when); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_societe) { + $param .= '&search_societe='.urlencode($search_societe); + } + if ($search_montant_ht != '') { + $param .= '&search_montant_ht='.urlencode($search_montant_ht); + } + if ($search_montant_vat != '') { + $param .= '&search_montant_vat='.urlencode($search_montant_vat); + } + if ($search_montant_ttc != '') { + $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); + } + if ($search_payment_mode != '') { + $param .= '&search_payment_mode='.urlencode($search_payment_mode); + } + if ($search_payment_term != '') { + $param .= '&search_payment_term='.urlencode($search_payment_term); + } + if ($search_recurring != '' && $search_recurrning != '-1') { + $param .= '&search_recurring='.urlencode($search_recurring); + } + if ($search_frequency > 0) { + $param .= '&search_frequency='.urlencode($search_frequency); + } + if ($search_unit_frequency != '') { + $param .= '&search_unit_frequency='.urlencode($search_unit_frequency); + } + if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -323,7 +413,9 @@ if ($resql) //$selectedfields.=$form->showCheckAddButtons('checkforselect', 1); print ''; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -348,93 +440,84 @@ if ($resql) // Filters lines print ''; // Ref - if (!empty($arrayfields['f.titre']['checked'])) - { + if (!empty($arrayfields['f.titre']['checked'])) { print ''; } // Thirpdarty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; } - if (!empty($arrayfields['f.total']['checked'])) - { + if (!empty($arrayfields['f.total']['checked'])) { // Amount net print ''; } - if (!empty($arrayfields['f.tva']['checked'])) - { + if (!empty($arrayfields['f.tva']['checked'])) { // Amount Vat print ''; } - if (!empty($arrayfields['f.total_ttc']['checked'])) - { + if (!empty($arrayfields['f.total_ttc']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { // Payment term print '"; } - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { // Payment mode print ''; } - if (!empty($arrayfields['recurring']['checked'])) - { + if (!empty($arrayfields['recurring']['checked'])) { // Recurring or not print ''; } - if (!empty($arrayfields['f.frequency']['checked'])) - { + if (!empty($arrayfields['f.frequency']['checked'])) { // Recurring or not print ''; } - if (!empty($arrayfields['f.unit_frequency']['checked'])) - { + if (!empty($arrayfields['f.unit_frequency']['checked'])) { // Frequency unit print ''; } - if (!empty($arrayfields['f.nb_gen_done']['checked'])) - { + if (!empty($arrayfields['f.nb_gen_done']['checked'])) { // Nb generation print ''; } // Date invoice - if (!empty($arrayfields['f.date_last_gen']['checked'])) - { + if (!empty($arrayfields['f.date_last_gen']['checked'])) { print ''; } // Date next generation - if (!empty($arrayfields['f.date_when']['checked'])) - { + if (!empty($arrayfields['f.date_when']['checked'])) { print ''; @@ -447,20 +530,17 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print ''; } // Date modification - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print ''; } // Status - if (!empty($arrayfields['status']['checked'])) - { + if (!empty($arrayfields['status']['checked'])) { print '\n"; print ''; - if (!empty($arrayfields['f.titre']['checked'])) print_liste_field_titre($arrayfields['f.titre']['label'], $_SERVER['PHP_SELF'], "f.titre", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], "s.nom", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.total']['checked'])) print_liste_field_titre($arrayfields['f.total']['label'], $_SERVER['PHP_SELF'], "f.total", "", $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.tva']['checked'])) print_liste_field_titre($arrayfields['f.tva']['label'], $_SERVER['PHP_SELF'], "f.tva", "", $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], "f.total_ttc", "", $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER['PHP_SELF'], "f.fk_cond_reglement", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER['PHP_SELF'], "f.fk_mode_reglement", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['recurring']['checked'])) print_liste_field_titre($arrayfields['recurring']['label'], $_SERVER['PHP_SELF'], "recurring", "", $param, 'class="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.frequency']['checked'])) print_liste_field_titre($arrayfields['f.frequency']['label'], $_SERVER['PHP_SELF'], "f.frequency", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.unit_frequency']['checked'])) print_liste_field_titre($arrayfields['f.unit_frequency']['label'], $_SERVER['PHP_SELF'], "f.unit_frequency", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.nb_gen_done']['checked'])) print_liste_field_titre($arrayfields['f.nb_gen_done']['label'], $_SERVER['PHP_SELF'], "f.nb_gen_done", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.date_last_gen']['checked'])) print_liste_field_titre($arrayfields['f.date_last_gen']['label'], $_SERVER['PHP_SELF'], "f.date_last_gen", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.date_when']['checked'])) print_liste_field_titre($arrayfields['f.date_when']['label'], $_SERVER['PHP_SELF'], "f.date_when", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER['PHP_SELF'], "f.datec", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER['PHP_SELF'], "f.tms", "", $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['f.titre']['checked'])) { + print_liste_field_titre($arrayfields['f.titre']['label'], $_SERVER['PHP_SELF'], "f.titre", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], "s.nom", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['f.total']['checked'])) { + print_liste_field_titre($arrayfields['f.total']['label'], $_SERVER['PHP_SELF'], "f.total", "", $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.tva']['checked'])) { + print_liste_field_titre($arrayfields['f.tva']['label'], $_SERVER['PHP_SELF'], "f.tva", "", $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], "f.total_ttc", "", $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER['PHP_SELF'], "f.fk_cond_reglement", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER['PHP_SELF'], "f.fk_mode_reglement", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['recurring']['checked'])) { + print_liste_field_titre($arrayfields['recurring']['label'], $_SERVER['PHP_SELF'], "recurring", "", $param, 'class="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.frequency']['checked'])) { + print_liste_field_titre($arrayfields['f.frequency']['label'], $_SERVER['PHP_SELF'], "f.frequency", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.unit_frequency']['checked'])) { + print_liste_field_titre($arrayfields['f.unit_frequency']['label'], $_SERVER['PHP_SELF'], "f.unit_frequency", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.nb_gen_done']['checked'])) { + print_liste_field_titre($arrayfields['f.nb_gen_done']['label'], $_SERVER['PHP_SELF'], "f.nb_gen_done", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.date_last_gen']['checked'])) { + print_liste_field_titre($arrayfields['f.date_last_gen']['label'], $_SERVER['PHP_SELF'], "f.date_last_gen", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.date_when']['checked'])) { + print_liste_field_titre($arrayfields['f.date_when']['label'], $_SERVER['PHP_SELF'], "f.date_when", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.datec']['checked'])) { + print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER['PHP_SELF'], "f.datec", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.tms']['checked'])) { + print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER['PHP_SELF'], "f.tms", "", $param, 'align="center"', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; - if (!empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'], $_SERVER['PHP_SELF'], "f.suspended,f.frequency", "", $param, 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['status']['checked'])) { + print_liste_field_titre($arrayfields['status']['label'], $_SERVER['PHP_SELF'], "f.suspended,f.frequency", "", $param, 'align="center"', $sortfield, $sortorder); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; - if ($num > 0) - { + if ($num > 0) { $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); - if (empty($objp)) break; + if (empty($objp)) { + break; + } $companystatic->id = $objp->socid; $companystatic->name = $objp->name; @@ -521,115 +633,137 @@ if ($resql) print ''; - if (!empty($arrayfields['f.titre']['checked'])) - { + if (!empty($arrayfields['f.titre']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['f.total']['checked'])) - { + if (!empty($arrayfields['f.total']['checked'])) { print ''."\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total'; + } $totalarray['val']['f.total'] += $objp->total; } - if (!empty($arrayfields['f.tva']['checked'])) - { + if (!empty($arrayfields['f.tva']['checked'])) { print ''."\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.tva'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.tva'; + } $totalarray['val']['f.tva'] += $objp->total_vat; } - if (!empty($arrayfields['f.total_ttc']['checked'])) - { + if (!empty($arrayfields['f.total_ttc']['checked'])) { print ''."\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; + } $totalarray['val']['f.total_ttc'] += $objp->total_ttc; } // Payment term - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { print ''."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment mode - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { print ''."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['recurring']['checked'])) - { + if (!empty($arrayfields['recurring']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['f.frequency']['checked'])) - { + if (!empty($arrayfields['f.frequency']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['f.unit_frequency']['checked'])) - { + if (!empty($arrayfields['f.unit_frequency']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['f.nb_gen_done']['checked'])) - { + if (!empty($arrayfields['f.nb_gen_done']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date last generation - if (!empty($arrayfields['f.date_last_gen']['checked'])) - { + if (!empty($arrayfields['f.date_last_gen']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date next generation - if (!empty($arrayfields['f.date_when']['checked'])) - { + if (!empty($arrayfields['f.date_when']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } $obj = $objp; @@ -644,17 +778,16 @@ if ($resql) print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '"; print "\n"; @@ -672,7 +807,11 @@ if ($resql) } } else { $colspan = 1; - foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } print ''; } diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index 249df885435..9f5281dc20b 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -52,7 +52,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/invoice.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -if (!empty($conf->commande->enabled)) require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +if (!empty($conf->commande->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('bills', 'companies', 'products', 'categories')); @@ -71,8 +73,7 @@ $confirm = GETPOST('confirm', 'alpha'); $toselect = GETPOST('toselect', 'array'); $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'invoicelist'; -if ($contextpage == 'poslist') -{ +if ($contextpage == 'poslist') { $_GET['optioncss'] = 'print'; } @@ -129,17 +130,27 @@ $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 < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } // If $page is not defined, or '' or -1 or if we click on clear filters +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} // If $page is not defined, or '' or -1 or if we click on clear filters $offset = $limit * $page; -if (!$sortorder && !empty($conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER) && $search_status == '1') $sortorder = $conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER; -if (!$sortorder) $sortorder = 'DESC'; -if (!$sortfield) $sortfield = 'f.datef'; +if (!$sortorder && !empty($conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER) && $search_status == '1') { + $sortorder = $conf->global->INVOICE_DEFAULT_UNPAYED_SORT_ORDER; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} +if (!$sortfield) { + $sortfield = 'f.datef'; +} $pageprev = $page - 1; $pagenext = $page + 1; // Security check $fieldid = (!empty($ref) ? 'ref' : 'rowid'); -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid); $diroutputmassaction = $conf->facture->dir_output.'/temp/massgeneration/'.$user->id; @@ -169,7 +180,9 @@ $fieldstosearchall = array( 's.town'=>"Town", 'f.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["f.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["f.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; $arrayfields = array( @@ -219,8 +232,7 @@ $arrayfields = array( 'f.fk_statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), ); -if ($conf->global->INVOICE_USE_SITUATION && $conf->global->INVOICE_USE_RETAINED_WARRANTY) -{ +if ($conf->global->INVOICE_USE_SITUATION && $conf->global->INVOICE_USE_RETAINED_WARRANTY) { $arrayfields['f.retained_warranty'] = array('label'=>$langs->trans("RetainedWarranty"), 'checked'=>0, 'position'=>86); } @@ -235,18 +247,23 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $parameters = array('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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Do we click on purge search criteria ? -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha')) // All tests are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha')) { // All tests are required to be compatible with all browsers $search_user = ''; $search_sale = ''; $search_product_category = ''; @@ -292,8 +309,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', $search_categ_cus = 0; } -if (empty($reshook)) -{ +if (empty($reshook)) { $objectclass = 'Facture'; $objectlabel = 'Invoices'; $permissiontoread = $user->rights->facture->lire; @@ -322,8 +338,7 @@ if ($massaction == 'makepayment') { $arrayofselected = is_array($toselect) ? $toselect : array(); $listofbills = array(); - foreach ($arrayofselected as $toselectid) - { + foreach ($arrayofselected as $toselectid) { $objecttmp = new Facture($db); $result = $objecttmp->fetch($toselectid); if ($result > 0) { @@ -355,8 +370,7 @@ if ($massaction == 'makepayment') { $rsql .= " ORDER BY pfd.date_demande DESC"; $result_sql = $db->query($rsql); - if ($result_sql) - { + if ($result_sql) { $numprlv = $db->num_rows($result_sql); } @@ -373,15 +387,12 @@ if ($massaction == 'makepayment') { } //Massive withdraw request for request with no errors - if (!empty($listofbills)) - { + if (!empty($listofbills)) { $nbwithdrawrequestok = 0; - foreach ($listofbills as $aBill) - { + foreach ($listofbills as $aBill) { $db->begin(); $result = $aBill->demande_prelevement($user, $aBill->resteapayer, 'direct-debit', 'facture'); - if ($result > 0) - { + if ($result > 0) { $db->commit(); $nbwithdrawrequestok++; } else { @@ -389,8 +400,7 @@ if ($massaction == 'makepayment') { setEventMessages($aBill->error, $aBill->errors, 'errors'); } } - if ($nbwithdrawrequestok > 0) - { + if ($nbwithdrawrequestok > 0) { setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs'); } } @@ -416,7 +426,9 @@ $formcompany = new FormCompany($db); $thirdpartystatic = new Societe($db); $sql = 'SELECT'; -if ($sall || $search_product_category > 0 || $search_user > 0) $sql = 'SELECT DISTINCT'; +if ($sall || $search_product_category > 0 || $search_user > 0) { + $sql = 'SELECT DISTINCT'; +} $sql .= ' f.rowid as id, f.ref, f.ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.fk_cond_reglement, f.total as total_ht, f.tva as total_vat, f.total_ttc,'; $sql .= ' f.localtax1 as total_localtax1, f.localtax2 as total_localtax2,'; $sql .= ' f.fk_user_author,'; @@ -433,11 +445,17 @@ $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label, $sql .= " u.login"; // We need dynamount_payed to be able to sort on status (value is surely wrong because we can count several lines several times due to other left join or link with contacts. But what we need is just 0 or > 0) // TODO Better solution to be able to sort on already payed or remain to pay is to store amount_payed in a denormalized field. -if (!$sall) $sql .= ', SUM(pf.amount) as dynamount_payed, SUM(pf.multicurrency_amount) as multicurrency_dynamount_payed'; -if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; +if (!$sall) { + $sql .= ', SUM(pf.amount) as dynamount_payed, SUM(pf.multicurrency_amount) as multicurrency_dynamount_payed'; +} +if ($search_categ_cus) { + $sql .= ", cc.fk_categorie, cc.fk_soc"; +} // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); @@ -447,96 +465,196 @@ $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; -if (!empty($search_categ_cus)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ +if (!empty($search_categ_cus)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ +} $sql .= ', '.MAIN_DB_PREFIX.'facture as f'; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; -if (!$sall) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid'; -if ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as pd ON f.rowid=pd.fk_facture'; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; +} +if (!$sall) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiement_facture as pf ON pf.fk_facture = f.rowid'; +} +if ($sall || $search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facturedet as pd ON f.rowid=pd.fk_facture'; +} +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = f.fk_projet"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user AS u ON f.fk_user_author = u.rowid'; // We'll need this table joined to the select in order to filter by sale -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -if ($search_user > 0) -{ +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql .= ' WHERE f.fk_soc = s.rowid'; $sql .= ' AND f.entity IN ('.getEntity('invoice').')'; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$db->escape($search_product_category); -if ($socid > 0) $sql .= ' AND s.rowid = '.$socid; -if ($userid) -{ - if ($userid == -1) $sql .= ' AND f.fk_user_author IS NULL'; - else $sql .= ' AND f.fk_user_author = '.$userid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } -if ($filtre) -{ +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$db->escape($search_product_category); +} +if ($socid > 0) { + $sql .= ' AND s.rowid = '.$socid; +} +if ($userid) { + if ($userid == -1) { + $sql .= ' AND f.fk_user_author IS NULL'; + } else { + $sql .= ' AND f.fk_user_author = '.$userid; + } +} +if ($filtre) { $aFilter = explode(',', $filtre); - foreach ($aFilter as $filter) - { + foreach ($aFilter as $filter) { $filt = explode(':', $filter); $sql .= ' AND '.$db->escape(trim($filt[0])).' = '.$db->escape(trim($filt[1])); } } -if ($search_ref) $sql .= natural_search('f.ref', $search_ref); -if ($search_refcustomer) $sql .= natural_search('f.ref_client', $search_refcustomer); -if ($search_type != '' && $search_type != '-1') $sql .= " AND f.type IN (".$db->sanitize($db->escape($search_type)).")"; -if ($search_project_ref) $sql .= natural_search('p.ref', $search_project_ref); -if ($search_project) $sql .= natural_search('p.title', $search_project); -if ($search_societe) $sql .= natural_search('s.nom', $search_societe); -if ($search_societe_alias) $sql .= natural_search('s.name_alias', $search_societe_alias); -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty != '-1') $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_company_alias) $sql .= natural_search('s.name_alias', $search_company_alias); -if ($search_montant_ht != '') $sql .= natural_search('f.total', $search_montant_ht, 1); -if ($search_montant_vat != '') $sql .= natural_search('f.tva', $search_montant_vat, 1); -if ($search_montant_localtax1 != '') $sql .= natural_search('f.localtax1', $search_montant_localtax1, 1); -if ($search_montant_localtax2 != '') $sql .= natural_search('f.localtax2', $search_montant_localtax2, 1); -if ($search_montant_ttc != '') $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1); -if ($search_multicurrency_code != '') $sql .= ' AND f.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; -if ($search_multicurrency_tx != '') $sql .= natural_search('f.multicurrency_tx', $search_multicurrency_tx, 1); -if ($search_multicurrency_montant_ht != '') $sql .= natural_search('f.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); -if ($search_multicurrency_montant_vat != '') $sql .= natural_search('f.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); -if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); -if ($search_login) $sql .= natural_search('u.login', $search_login); -if ($search_categ_cus > 0) $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); -if ($search_categ_cus == -2) $sql .= " AND cc.fk_categorie IS NULL"; -if ($search_status != '-1' && $search_status != '') -{ - if (is_numeric($search_status) && $search_status >= 0) - { - if ($search_status == '0') $sql .= " AND f.fk_statut = 0"; // draft - if ($search_status == '1') $sql .= " AND f.fk_statut = 1"; // unpayed - if ($search_status == '2') $sql .= " AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) - if ($search_status == '3') $sql .= " AND f.fk_statut = 3"; // abandonned +if ($search_ref) { + $sql .= natural_search('f.ref', $search_ref); +} +if ($search_refcustomer) { + $sql .= natural_search('f.ref_client', $search_refcustomer); +} +if ($search_type != '' && $search_type != '-1') { + $sql .= " AND f.type IN (".$db->sanitize($db->escape($search_type)).")"; +} +if ($search_project_ref) { + $sql .= natural_search('p.ref', $search_project_ref); +} +if ($search_project) { + $sql .= natural_search('p.title', $search_project); +} +if ($search_societe) { + $sql .= natural_search('s.nom', $search_societe); +} +if ($search_societe_alias) { + $sql .= natural_search('s.name_alias', $search_societe_alias); +} +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; +} +if ($search_type_thirdparty != '' && $search_type_thirdparty != '-1') { + $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_company_alias) { + $sql .= natural_search('s.name_alias', $search_company_alias); +} +if ($search_montant_ht != '') { + $sql .= natural_search('f.total', $search_montant_ht, 1); +} +if ($search_montant_vat != '') { + $sql .= natural_search('f.tva', $search_montant_vat, 1); +} +if ($search_montant_localtax1 != '') { + $sql .= natural_search('f.localtax1', $search_montant_localtax1, 1); +} +if ($search_montant_localtax2 != '') { + $sql .= natural_search('f.localtax2', $search_montant_localtax2, 1); +} +if ($search_montant_ttc != '') { + $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1); +} +if ($search_multicurrency_code != '') { + $sql .= ' AND f.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +} +if ($search_multicurrency_tx != '') { + $sql .= natural_search('f.multicurrency_tx', $search_multicurrency_tx, 1); +} +if ($search_multicurrency_montant_ht != '') { + $sql .= natural_search('f.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +} +if ($search_multicurrency_montant_vat != '') { + $sql .= natural_search('f.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); +} +if ($search_multicurrency_montant_ttc != '') { + $sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +} +if ($search_login) { + $sql .= natural_search('u.login', $search_login); +} +if ($search_categ_cus > 0) { + $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ_cus); +} +if ($search_categ_cus == -2) { + $sql .= " AND cc.fk_categorie IS NULL"; +} +if ($search_status != '-1' && $search_status != '') { + if (is_numeric($search_status) && $search_status >= 0) { + if ($search_status == '0') { + $sql .= " AND f.fk_statut = 0"; // draft + } + if ($search_status == '1') { + $sql .= " AND f.fk_statut = 1"; // unpayed + } + if ($search_status == '2') { + $sql .= " AND f.fk_statut = 2"; // payed Not that some corrupted data may contains f.fk_statut = 1 AND f.paye = 1 (it means payed too but should not happend. If yes, reopen and reclassify billed) + } + if ($search_status == '3') { + $sql .= " AND f.fk_statut = 3"; // abandonned + } } else { $sql .= " AND f.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; // When search_status is '1,2' for example } } -if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".$db->escape($search_paymentmode); -if ($search_paymentterms > 0) $sql .= " AND f.fk_cond_reglement = ".$db->escape($search_paymentterms); -if ($search_module_source) $sql .= natural_search("f.module_source", $search_module_source); -if ($search_pos_source) $sql .= natural_search("f.pos_source", $search_pos_source); -if ($search_date_start) $sql .= " AND f.datef >= '".$db->idate($search_date_start)."'"; -if ($search_date_end) $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; -if ($search_date_valid_start) $sql .= " AND f.date_valid >= '".$db->idate($search_date_valid_start)."'"; -if ($search_date_valid_end) $sql .= " AND f.date_valid <= '".$db->idate($search_date_valid_end)."'"; -if ($search_datelimit_start) $sql .= " AND f.date_lim_reglement >= '".$db->idate($search_datelimit_start)."'"; -if ($search_datelimit_end) $sql .= " AND f.date_lim_reglement <= '".$db->idate($search_datelimit_end)."'"; -if ($option == 'late') $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->client->warning_delay)."'"; -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".(int) $search_sale; -if ($search_user > 0) -{ +if ($search_paymentmode > 0) { + $sql .= " AND f.fk_mode_reglement = ".$db->escape($search_paymentmode); +} +if ($search_paymentterms > 0) { + $sql .= " AND f.fk_cond_reglement = ".$db->escape($search_paymentterms); +} +if ($search_module_source) { + $sql .= natural_search("f.module_source", $search_module_source); +} +if ($search_pos_source) { + $sql .= natural_search("f.pos_source", $search_pos_source); +} +if ($search_date_start) { + $sql .= " AND f.datef >= '".$db->idate($search_date_start)."'"; +} +if ($search_date_end) { + $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; +} +if ($search_date_valid_start) { + $sql .= " AND f.date_valid >= '".$db->idate($search_date_valid_start)."'"; +} +if ($search_date_valid_end) { + $sql .= " AND f.date_valid <= '".$db->idate($search_date_valid_end)."'"; +} +if ($search_datelimit_start) { + $sql .= " AND f.date_lim_reglement >= '".$db->idate($search_datelimit_start)."'"; +} +if ($search_datelimit_end) { + $sql .= " AND f.date_lim_reglement <= '".$db->idate($search_datelimit_end)."'"; +} +if ($option == 'late') { + $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->client->warning_delay)."'"; +} +if ($search_sale > 0) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".(int) $search_sale; +} +if ($search_user > 0) { $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='facture' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } // Add where from extra fields @@ -546,8 +664,7 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -if (!$sall) -{ +if (!$sall) { $sql .= ' GROUP BY f.rowid, f.ref, ref_client, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.fk_cond_reglement, f.total, f.tva, f.total_ttc,'; $sql .= ' f.localtax1, f.localtax2,'; $sql .= ' f.datef, f.date_valid, f.date_lim_reglement, f.module_source, f.pos_source,'; @@ -562,10 +679,14 @@ if (!$sall) $sql .= ' country.code,'; $sql .= " p.rowid, p.ref, p.title,"; $sql .= " u.login"; - if ($search_categ_cus) $sql .= ", cc.fk_categorie, cc.fk_soc"; + if ($search_categ_cus) { + $sql .= ", cc.fk_categorie, cc.fk_soc"; + } // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : ''); + } } } else { $sql .= natural_search(array_keys($fieldstosearchall), $sall); @@ -574,16 +695,16 @@ if (!$sall) $sql .= ' ORDER BY '; $listfield = explode(',', $sortfield); $listorder = explode(',', $sortorder); -foreach ($listfield as $key => $value) $sql .= $listfield[$key].' '.($listorder[$key] ? $listorder[$key] : 'DESC').','; +foreach ($listfield as $key => $value) { + $sql .= $listfield[$key].' '.($listorder[$key] ? $listorder[$key] : 'DESC').','; +} $sql .= ' f.rowid DESC '; $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -593,14 +714,12 @@ $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); $id = $obj->id; @@ -610,55 +729,138 @@ if ($resql) llxHeader('', $langs->trans('CustomersInvoices'), 'EN:Customers_Invoices|FR:Factures_Clients|ES:Facturas_a_clientes'); - if ($socid) - { + if ($socid) { $soc = new Societe($db); $soc->fetch($socid); - if (empty($search_societe)) $search_societe = $soc->name; + if (empty($search_societe)) { + $search_societe = $soc->name; + } } $param = '&socid='.$socid; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sall) $param .= '&sall='.urlencode($sall); - if ($search_date_start) $param .= '&search_date_start='.urlencode($search_date_start); - if ($search_date_end) $param .= '&search_date_end='.urlencode($search_date_end); - if ($search_date_valid_start) $param .= '&search_date_valid_start='.urlencode($search_date_valid_start); - if ($search_date_valid_end) $param .= '&search_date_valid_end='.urlencode($search_date_valid_end); - if ($search_datelimit_start) $param .= '&search_datelimit_start='.urlencode($search_datelimit_start); - if ($search_datelimit_end) $param .= '&search_datelimit_end='.urlencode($search_datelimit_end); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_refcustomer) $param .= '&search_refcustomer='.urlencode($search_refcustomer); - if ($search_project_ref) $param .= '&search_project_ref='.urlencode($search_project_ref); - if ($search_project) $param .= '&search_project='.urlencode($search_project); - if ($search_type != '') $param .= '&search_type='.urlencode($search_type); - if ($search_societe) $param .= '&search_societe='.urlencode($search_societe); - if ($search_societe_alias) $param .= '&search_societe_alias='.urlencode($search_societe_alias); - if ($search_town) $param .= '&search_town='.urlencode($search_town); - if ($search_zip) $param .= '&search_zip='.urlencode($search_zip); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_login) $param .= '&search_login='.urlencode($search_login); - if ($search_product_category > 0) $param .= '&search_product_category='.urlencode($search_product_category); - if ($search_montant_ht != '') $param .= '&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_vat != '') $param .= '&search_montant_vat='.urlencode($search_montant_vat); - if ($search_montant_localtax1 != '') $param .= '&search_montant_localtax1='.urlencode($search_montant_localtax1); - if ($search_montant_localtax2 != '') $param .= '&search_montant_localtax2='.urlencode($search_montant_localtax2); - if ($search_montant_ttc != '') $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); - if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); - if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); - if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); - if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); - if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($search_paymentmode > 0) $param .= '&search_paymentmode='.urlencode($search_paymentmode); - if ($search_paymentterms > 0) $param .= '&search_paymentterms='.urlencode($search_paymentterms); - if ($search_module_source) $param .= '&search_module_source='.urlencode($search_module_source); - if ($search_pos_source) $param .= '&search_pos_source='.urlencode($search_pos_source); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($option) $param .= "&search_option=".urlencode($option); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_categ_cus > 0) $param .= '&search_categ_cus='.urlencode($search_categ_cus); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($sall) { + $param .= '&sall='.urlencode($sall); + } + if ($search_date_start) { + $param .= '&search_date_start='.urlencode($search_date_start); + } + if ($search_date_end) { + $param .= '&search_date_end='.urlencode($search_date_end); + } + if ($search_date_valid_start) { + $param .= '&search_date_valid_start='.urlencode($search_date_valid_start); + } + if ($search_date_valid_end) { + $param .= '&search_date_valid_end='.urlencode($search_date_valid_end); + } + if ($search_datelimit_start) { + $param .= '&search_datelimit_start='.urlencode($search_datelimit_start); + } + if ($search_datelimit_end) { + $param .= '&search_datelimit_end='.urlencode($search_datelimit_end); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_refcustomer) { + $param .= '&search_refcustomer='.urlencode($search_refcustomer); + } + if ($search_project_ref) { + $param .= '&search_project_ref='.urlencode($search_project_ref); + } + if ($search_project) { + $param .= '&search_project='.urlencode($search_project); + } + if ($search_type != '') { + $param .= '&search_type='.urlencode($search_type); + } + if ($search_societe) { + $param .= '&search_societe='.urlencode($search_societe); + } + if ($search_societe_alias) { + $param .= '&search_societe_alias='.urlencode($search_societe_alias); + } + if ($search_town) { + $param .= '&search_town='.urlencode($search_town); + } + if ($search_zip) { + $param .= '&search_zip='.urlencode($search_zip); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_login) { + $param .= '&search_login='.urlencode($search_login); + } + if ($search_product_category > 0) { + $param .= '&search_product_category='.urlencode($search_product_category); + } + if ($search_montant_ht != '') { + $param .= '&search_montant_ht='.urlencode($search_montant_ht); + } + if ($search_montant_vat != '') { + $param .= '&search_montant_vat='.urlencode($search_montant_vat); + } + if ($search_montant_localtax1 != '') { + $param .= '&search_montant_localtax1='.urlencode($search_montant_localtax1); + } + if ($search_montant_localtax2 != '') { + $param .= '&search_montant_localtax2='.urlencode($search_montant_localtax2); + } + if ($search_montant_ttc != '') { + $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); + } + if ($search_multicurrency_code != '') { + $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + } + if ($search_multicurrency_tx != '') { + $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + } + if ($search_multicurrency_montant_ht != '') { + $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + } + if ($search_multicurrency_montant_vat != '') { + $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); + } + if ($search_multicurrency_montant_ttc != '') { + $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); + } + if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); + } + if ($search_paymentmode > 0) { + $param .= '&search_paymentmode='.urlencode($search_paymentmode); + } + if ($search_paymentterms > 0) { + $param .= '&search_paymentterms='.urlencode($search_paymentterms); + } + if ($search_module_source) { + $param .= '&search_module_source='.urlencode($search_module_source); + } + if ($search_pos_source) { + $param .= '&search_pos_source='.urlencode($search_pos_source); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($option) { + $param .= "&search_option=".urlencode($option); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_categ_cus > 0) { + $param .= '&search_categ_cus='.urlencode($search_categ_cus); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -681,21 +883,26 @@ if ($resql) $arrayofmassactions['predelete'] = $langs->trans("Delete"); } } - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); // Show the new button only when this page is not opend from the Extended POS - if ($contextpage != 'poslist') - { + if ($contextpage != 'poslist') { $url = DOL_URL_ROOT.'/compta/facture/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', $url, '', $user->rights->facture->creer); } $i = 0; print ''."\n"; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -712,33 +919,31 @@ if ($resql) $trackid = 'inv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } - // If the user can view prospects other than his' - $moreforfilter = ''; - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter .= '
'; - $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; - $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); - $moreforfilter .= '
'; - } // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + $moreforfilter = ''; + if ($user->rights->societe->client->voir || $socid) { + $langs->load("commercial"); + $moreforfilter .= '
'; + $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; + $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); + $moreforfilter .= '
'; + } + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) { $moreforfilter .= '
'; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter .= '
'; + $moreforfilter .= ''; } // If the user can view prospects other than his' - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
'; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -746,22 +951,23 @@ if ($resql) $moreforfilter .= $form->selectarray('search_product_category', $cate_arbo, $search_product_category, 1, 0, 0, '', 0, 0, 0, 0, 'maxwidth300', 1); $moreforfilter .= '
'; } - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
'; - $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; + $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; $moreforfilter .= $formother->select_categories('customer', $search_categ_cus, 'search_categ_cus', 1); - $moreforfilter .= '
'; + $moreforfilter .= ''; } $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint; - else $moreforfilter = $hookmanager->resPrint; + if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; + } else { + $moreforfilter = $hookmanager->resPrint; + } - if ($moreforfilter) - { - print '
'; + if ($moreforfilter) { + print '
'; print $moreforfilter; print '
'; } @@ -769,7 +975,9 @@ if ($resql) $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields // Show the massaction checkboxes only when this page is not opend from the Extended POS - if ($massactionbutton && $contextpage != 'poslist') $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + if ($massactionbutton && $contextpage != 'poslist') { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + } print '
'; print '
'.$langs->trans("Name")."
'; @@ -680,8 +655,7 @@ if ($type == Categorie::TYPE_SUPPLIER) print "'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -701,15 +675,13 @@ if ($type == Categorie::TYPE_SUPPLIER) } // List of members -if ($type == Categorie::TYPE_MEMBER) -{ +if ($type == Categorie::TYPE_MEMBER) { require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; $permission = $user->rights->adherent->creer; $prods = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($prods < 0) - { + if ($prods < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -726,13 +698,13 @@ if ($type == Categorie::TYPE_MEMBER) print "\n"; print ''."\n"; - if (count($prods) > 0) - { + if (count($prods) > 0) { $i = 0; - foreach ($prods as $key => $member) - { + foreach ($prods as $key => $member) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; $result .= ''; - if ($num < 1) - { + if ($num < 1) { $result .= '
'.$langs->trans("Name").'
'; @@ -743,8 +715,7 @@ if ($type == Categorie::TYPE_MEMBER) print ''.$member->firstname."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -762,13 +733,11 @@ if ($type == Categorie::TYPE_MEMBER) } // Categorie contact -if ($type == Categorie::TYPE_CONTACT) -{ +if ($type == Categorie::TYPE_CONTACT) { $permission = $user->rights->societe->creer; $contacts = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($contacts < 0) - { + if ($contacts < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -788,13 +757,13 @@ if ($type == Categorie::TYPE_CONTACT) print ''."\n"; print ''."\n"; - if (count($contacts) > 0) - { + if (count($contacts) > 0) { $i = 0; - foreach ($contacts as $key => $contact) - { + foreach ($contacts as $key => $contact) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; $result .= ''; $result .= ''; - } - elseif ($total > 0) - { + } elseif ($total > 0) { $result .= ''; $result .= ''; $result .= ''; @@ -325,17 +323,22 @@ function getLatestEditTable($maxCount = 5, $socid = 0) $sql .= " f.datec"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture').")"; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " ORDER BY f.tms DESC"; $sql .= $db->plimit($maxCount, 0); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); } @@ -348,8 +351,7 @@ function getLatestEditTable($maxCount = 5, $socid = 0) $result .= ''; $result .= ''; - if ($num < 1) - { + if ($num < 1) { $result .= '
'.$langs->trans("Ref").'
'; @@ -802,8 +771,7 @@ if ($type == Categorie::TYPE_CONTACT) print "'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -822,15 +790,13 @@ if ($type == Categorie::TYPE_CONTACT) } // List of bank accounts -if ($type == Categorie::TYPE_ACCOUNT) -{ +if ($type == Categorie::TYPE_ACCOUNT) { require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $permission = $user->rights->banque->creer; $accounts = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($accounts < 0) - { + if ($accounts < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -847,13 +813,13 @@ if ($type == Categorie::TYPE_ACCOUNT) print "\n"; print ''."\n"; - if (count($accounts) > 0) - { + if (count($accounts) > 0) { $i = 0; - foreach ($accounts as $key => $account) - { + foreach ($accounts as $key => $account) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; print ''; print ''; - if (!empty($conf->banque->enabled)) print ''; + if (!empty($conf->banque->enabled)) { + print ''; + } print ''; print ''; print ''; @@ -4597,7 +4729,9 @@ if ($action == 'create') print ''; print ''; print ''; - if (!empty($conf->banque->enabled)) print ''; + if (!empty($conf->banque->enabled)) { + print ''; + } print ''; print ''; print ''; @@ -4615,7 +4749,9 @@ if ($action == 'create') print ''; print ''; print ''; - if (!empty($conf->banque->enabled)) print ''; + if (!empty($conf->banque->enabled)) { + print ''; + } print ''; print ''; print ''; @@ -4629,12 +4765,16 @@ if ($action == 'create') foreach ($current_situation_counter as $sit) { $curSign = $sit > 0 ? '+' : '-'; $curType = $sit > 0 ? $langs->trans('situationInvoiceShortcode_S') : $langs->trans('situationInvoiceShortcode_AS'); - if ($i > 0) print ' '.$curSign.' '; + if ($i > 0) { + print ' '.$curSign.' '; + } print $curType.abs($sit); $i++; } print ''; - if (!empty($conf->banque->enabled)) print ''; + if (!empty($conf->banque->enabled)) { + print ''; + } print ''; print ''; print ''; @@ -4644,14 +4784,14 @@ if ($action == 'create') if (count($object->tab_next_situation_invoice) > 0) { // List of next invoices /*print ''; - print ''; - print ''; - print ''; - if (! empty($conf->banque->enabled)) print ''; - print ''; - print ''; - print ''; - print '';*/ + print ''; + print ''; + print ''; + if (! empty($conf->banque->enabled)) print ''; + print ''; + print ''; + print ''; + print '';*/ $total_next_ht = $total_next_ttc = 0; @@ -4664,7 +4804,9 @@ if ($action == 'create') print ''; print ''; print ''; - if (!empty($conf->banque->enabled)) print ''; + if (!empty($conf->banque->enabled)) { + print ''; + } print ''; print ''; print ''; @@ -4676,7 +4818,9 @@ if ($action == 'create') print ''; print ''; - if (!empty($conf->banque->enabled)) print ''; + if (!empty($conf->banque->enabled)) { + print ''; + } print ''; print ''; print ''; @@ -4687,7 +4831,9 @@ if ($action == 'create') } $sign = 1; - if ($object->type == $object::TYPE_CREDIT_NOTE) $sign = -1; + if ($object->type == $object::TYPE_CREDIT_NOTE) { + $sign = -1; + } // List of payments already done @@ -4816,10 +4962,12 @@ if ($action == 'create') $invoice->fetch($obj->fk_facture_source); print ''; @@ -4828,10 +4976,12 @@ if ($action == 'create') print 'rowid.'">'.img_delete().''; print ''; $i++; - if ($invoice->type == Facture::TYPE_CREDIT_NOTE) + if ($invoice->type == Facture::TYPE_CREDIT_NOTE) { $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == Facture::TYPE_DEPOSIT) + } + if ($invoice->type == Facture::TYPE_DEPOSIT) { $depositamount += $obj->amount_ttc; + } } } else { dol_print_error($db); @@ -4871,8 +5021,9 @@ if ($action == 'create') if (($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED) && $object->close_code == 'abandon') { print ''; print ''; print ''; @@ -5093,10 +5245,8 @@ if ($action == 'create') || ($object->type == Facture::TYPE_CREDIT_NOTE && empty($discount->id)) || ($object->type == Facture::TYPE_DEPOSIT && empty($discount->id))) && ($object->statut == Facture::STATUS_CLOSED || $object->statut == Facture::STATUS_ABANDONED || ($object->statut == 1 && $object->paye == 1)) // Condition ($object->statut == 1 && $object->paye == 1) should not happened but can be found due to corrupted data - && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || $usercanreopen)) // A paid invoice (partially or completely) - { - if ($object->close_code != 'replaced' || (!$objectidnext)) // Not replaced by another invoice or replaced but the replacement invoice has been deleted - { + && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && $usercancreate) || $usercanreopen)) { // A paid invoice (partially or completely) + if ($object->close_code != 'replaced' || (!$objectidnext)) { // Not replaced by another invoice or replaced but the replacement invoice has been deleted print ''.$langs->trans('ReOpen').''; } else { print ''.$langs->trans('ReOpen').''; @@ -5105,8 +5255,7 @@ if ($action == 'create') // Validate if ($object->statut == Facture::STATUS_DRAFT && count($object->lines) > 0 && ((($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION) && (!empty($conf->global->FACTURE_ENABLE_NEGATIVE) || $object->total_ttc >= 0)) || ($object->type == Facture::TYPE_CREDIT_NOTE && $object->total_ttc <= 0))) { - if ($usercanvalidate) - { + if ($usercanvalidate) { print ''.$langs->trans('Validate').''; } } @@ -5119,7 +5268,9 @@ if ($action == 'create') } else { if ($usercansend) { print ''.$langs->trans('SendMail').''; - } else print ''.$langs->trans('SendMail').''; + } else { + print ''.$langs->trans('SendMail').''; + } } } } @@ -5173,8 +5324,7 @@ if ($action == 'create') } // For standard invoice with excess received - if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->statut == Facture::STATUS_VALIDATED && empty($object->paye) && $resteapayer < 0 && $usercancreate && empty($discount->id)) - { + if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_SITUATION) && $object->statut == Facture::STATUS_VALIDATED && empty($object->paye) && $resteapayer < 0 && $usercancreate && empty($discount->id)) { print ''.$langs->trans('ConvertExcessReceivedToReduc').''; } // For credit note @@ -5192,23 +5342,19 @@ if ($action == 'create') // Classify paid if (($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $usercanissuepayment && (($object->type != Facture::TYPE_CREDIT_NOTE && $object->type != Facture::TYPE_DEPOSIT && $resteapayer <= 0) || ($object->type == Facture::TYPE_CREDIT_NOTE && $resteapayer >= 0))) || ($object->type == Facture::TYPE_DEPOSIT && $object->paye == 0 && $object->total_ttc > 0 && $resteapayer == 0 && $usercanissuepayment && empty($discount->id)) - ) - { + ) { print ''.$langs->trans('ClassifyPaid').''; } // Classify 'closed not completely paid' (possible si validee et pas encore classee payee) - if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && $usercanissuepayment) - { + if ($object->statut == Facture::STATUS_VALIDATED && $object->paye == 0 && $resteapayer > 0 && $usercanissuepayment) { if ($totalpaye > 0 || $totalcreditnotes > 0) { // If one payment or one credit note was linked to this invoice print ''.$langs->trans('ClassifyPaidPartially').''; } else { - if (empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED)) - { - if ($objectidnext) - { + if (empty($conf->global->INVOICE_CAN_NEVER_BE_CANCELED)) { + if ($objectidnext) { print ''.$langs->trans('ClassifyCanceled').''; } else { print ''.$langs->trans('ClassifyCanceled').''; @@ -5218,8 +5364,7 @@ if ($action == 'create') } // Create a credit note - if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $usercancreate) - { + if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut > 0 && $usercancreate) { if (!$objectidnext) { print ''.$langs->trans("CreateCreditNote").''; } @@ -5233,8 +5378,7 @@ if ($action == 'create') && !$objectidnext && $object->is_last_in_cycle() && $conf->global->INVOICE_USE_SITUATION_CREDIT_NOTE - ) - { + ) { if ($usercanunvalidate) { print ''.$langs->trans("CreateCreditNote").''; } else { @@ -5243,30 +5387,26 @@ if ($action == 'create') } // Clone - if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $usercancreate) - { + if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $usercancreate) { print ''.$langs->trans("ToClone").''; } // Clone as predefined / Create template - if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut == 0 && $usercancreate) - { - if (!$objectidnext && count($object->lines) > 0) - { + if (($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA) && $object->statut == 0 && $usercancreate) { + if (!$objectidnext && count($object->lines) > 0) { print ''.$langs->trans("ChangeIntoRepeatableInvoice").''; } } // Remove situation from cycle if (in_array($object->statut, array(Facture::STATUS_CLOSED, Facture::STATUS_VALIDATED)) - && $object->type == Facture::TYPE_SITUATION - && $usercancreate - && !$objectidnext - && $object->situation_counter > 1 - && $object->is_last_in_cycle() + && $object->type == Facture::TYPE_SITUATION + && $usercancreate + && !$objectidnext + && $object->situation_counter > 1 + && $object->is_last_in_cycle() && $usercanunvalidate - ) - { + ) { if (($object->total_ttc - $totalcreditnotes) == 0) { print ''.$langs->trans("RemoveSituationFromCycle").''; } else { @@ -5287,8 +5427,7 @@ if ($action == 'create') // Delete $isErasable = $object->is_erasable(); - if ($usercandelete || ($usercancreate && $isErasable == 1)) // isErasable = 1 means draft with temporary ref (draft can always be deleted with no need of permissions) - { + if ($usercandelete || ($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 ''.$langs->trans('Delete').''; @@ -5298,11 +5437,9 @@ if ($action == 'create') print ''.$langs->trans('Delete').''; } elseif ($isErasable == -1) { print ''.$langs->trans('Delete').''; - } elseif ($isErasable <= 0) // Any other cases - { + } elseif ($isErasable <= 0) { // Any other cases print ''.$langs->trans('Delete').''; - } elseif ($objectidnext) - { + } elseif ($objectidnext) { print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; @@ -5330,9 +5467,27 @@ if ($action == 'create') $delallowed = $usercancreate; print $formfile->showdocuments( - 'facture', $filename, $filedir, $urlsource, $genallowed, - $delallowed, $object->model_pdf, 1, 0, 0, 28, 0, '', '', '', - $soc->default_lang, '', $object, 0, 'remove_file_comfirm'); + 'facture', + $filename, + $filedir, + $urlsource, + $genallowed, + $delallowed, + $object->model_pdf, + 1, + 0, + 0, + 28, + 0, + '', + '', + '', + $soc->default_lang, + '', + $object, + 0, + 'remove_file_comfirm' + ); $somethingshown = $formfile->numoffiles; @@ -5342,8 +5497,7 @@ if ($action == 'create') $compatibleImportElementsList = false; if ($usercancreate && $object->statut == Facture::STATUS_DRAFT - && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION)) - { + && ($object->type == Facture::TYPE_STANDARD || $object->type == Facture::TYPE_REPLACEMENT || $object->type == Facture::TYPE_DEPOSIT || $object->type == Facture::TYPE_PROFORMA || $object->type == Facture::TYPE_SITUATION)) { $compatibleImportElementsList = array('commande', 'propal'); // import from linked elements } $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem, $compatibleImportElementsList); diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index 444fca3155a..c16d79d2574 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -172,35 +172,52 @@ class Invoices extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."facture as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('invoice').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Filter by status - if ($status == 'draft') $sql .= " AND t.fk_statut IN (0)"; - if ($status == 'unpaid') $sql .= " AND t.fk_statut IN (1)"; - if ($status == 'paid') $sql .= " AND t.fk_statut IN (2)"; - if ($status == 'cancelled') $sql .= " AND t.fk_statut IN (3)"; + if ($status == 'draft') { + $sql .= " AND t.fk_statut IN (0)"; + } + if ($status == 'unpaid') { + $sql .= " AND t.fk_statut IN (1)"; + } + if ($status == 'paid') { + $sql .= " AND t.fk_statut IN (2)"; + } + if ($status == 'cancelled') { + $sql .= " AND t.fk_statut IN (3)"; + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -208,10 +225,8 @@ class Invoices extends DolibarrApi } $sql .= $this->db->order($sortfield, $sortorder); - if ($limit) - { - if ($page < 0) - { + if ($limit) { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -220,17 +235,14 @@ class Invoices extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $invoice_static = new Facture($this->db); - if ($invoice_static->fetch($obj->rowid)) - { + if ($invoice_static->fetch($obj->rowid)) { // Get payment details $invoice_static->totalpaid = $invoice_static->getSommePaiement(); $invoice_static->totalcreditnotes = $invoice_static->getSumCreditNotesUsed(); @@ -274,13 +286,13 @@ class Invoices extends DolibarrApi $this->invoice->date = dol_now(); } /* We keep lines as an array - if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->invoice->lines = $lines; - }*/ + if (isset($request_data["lines"])) { + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->invoice->lines = $lines; + }*/ if ($this->invoice->create(DolibarrApiAccess::$user, 0, (empty($request_data["date_lim_reglement"]) ? 0 : $request_data["date_lim_reglement"])) < 0) { throw new RestException(500, "Error creating invoice", array_merge(array($this->invoice->error), $this->invoice->errors)); @@ -585,20 +597,22 @@ class Invoices extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->invoice->$field = $value; } // update bank account - if (!empty($this->invoice->fk_account)) - { + if (!empty($this->invoice->fk_account)) { if ($this->invoice->setBankAccount($this->invoice->fk_account) == 0) { throw new RestException(400, $this->invoice->error); } } - if ($this->invoice->update(DolibarrApiAccess::$user)) + if ($this->invoice->update(DolibarrApiAccess::$user)) { return $this->get($id); + } return false; } @@ -624,8 +638,7 @@ class Invoices extends DolibarrApi } $result = $this->invoice->delete(DolibarrApiAccess::$user); - if ($result < 0) - { + if ($result < 0) { throw new RestException(500); } @@ -1062,10 +1075,13 @@ class Invoices extends DolibarrApi $result = $discountcheck->fetch(0, $this->invoice->id); $canconvert = 0; - if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) - if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) - if ($canconvert) - { + if ($this->invoice->type == Facture::TYPE_DEPOSIT && empty($discountcheck->id)) { + $canconvert = 1; // we can convert deposit into discount if deposit is payed (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) + } + if (($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_STANDARD) && $this->invoice->paye == 0 && empty($discountcheck->id)) { + $canconvert = 1; // we can convert credit note into discount if credit note is not payed back and not already converted and amount of payment is 0 (see real condition into condition used to show button converttoreduc) + } + if ($canconvert) { $this->db->begin(); $amount_ht = $amount_tva = $amount_ttc = array(); @@ -1073,10 +1089,9 @@ class Invoices extends DolibarrApi // Loop on each vat rate $i = 0; - foreach ($this->invoice->lines as $line) - { - if ($line->product_type < 9 && $line->total_ht != 0) // Remove lines with product_type greater than or equal to 9 - { // no need to create discount if amount is null + foreach ($this->invoice->lines as $line) { + if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 + // no need to create discount if amount is null $amount_ht[$line->tva_tx] += $line->total_ht; $amount_tva[$line->tva_tx] += $line->total_tva; $amount_ttc[$line->tva_tx] += $line->total_ttc; @@ -1104,8 +1119,7 @@ class Invoices extends DolibarrApi $error = 0; - if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) - { + if ($this->invoice->type == Facture::TYPE_STANDARD || $this->invoice->type == Facture::TYPE_REPLACEMENT || $this->invoice->type == Facture::TYPE_SITUATION) { // If we're on a standard invoice, we have to get excess received to create a discount in TTC without VAT // Total payments @@ -1116,7 +1130,9 @@ class Invoices extends DolibarrApi $sql .= ' AND pf.fk_paiement = p.rowid'; $sql .= ' AND p.entity IN ('.getEntity('invoice').')'; $resql = $this->db->query($sql); - if (!$resql) dol_print_error($this->db); + if (!$resql) { + dol_print_error($this->db); + } $res = $this->db->fetch_object($resql); $total_payments = $res->total_payments; @@ -1129,23 +1145,24 @@ class Invoices extends DolibarrApi $sql .= " WHERE fk_facture = ".$this->invoice->id; $resql = $this->db->query($sql); if (!empty($resql)) { - while ($obj = $this->db->fetch_object($resql)) $total_creditnote_and_deposit += $obj->amount_ttc; - } else dol_print_error($this->db); + while ($obj = $this->db->fetch_object($resql)) { + $total_creditnote_and_deposit += $obj->amount_ttc; + } + } else { + dol_print_error($this->db); + } $discount->amount_ht = $discount->amount_ttc = $total_payments + $total_creditnote_and_deposit - $this->invoice->total_ttc; $discount->amount_tva = 0; $discount->tva_tx = 0; $result = $discount->create(DolibarrApiAccess::$user); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) - { - foreach ($amount_ht as $tva_tx => $xxx) - { + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE || $this->invoice->type == Facture::TYPE_DEPOSIT) { + foreach ($amount_ht as $tva_tx => $xxx) { $discount->amount_ht = abs($amount_ht[$tva_tx]); $discount->amount_tva = abs($amount_tva[$tva_tx]); $discount->amount_ttc = abs($amount_ttc[$tva_tx]); @@ -1155,21 +1172,18 @@ class Invoices extends DolibarrApi $discount->tva_tx = abs($tva_tx); $result = $discount->create(DolibarrApiAccess::$user); - if ($result < 0) - { + if ($result < 0) { $error++; break; } } } - if (empty($error)) - { + if (empty($error)) { if ($this->invoice->type != Facture::TYPE_DEPOSIT) { // Classe facture $result = $this->invoice->setPaid(DolibarrApiAccess::$user); - if ($result >= 0) - { + if ($result >= 0) { $this->db->commit(); } else { $this->db->rollback(); @@ -1417,8 +1431,7 @@ class Invoices extends DolibarrApi $paymentobj->note_private = $comment; $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices - if ($payment_id < 0) - { + if ($payment_id < 0) { $this->db->rollback(); throw new RestException(400, 'Payment error : '.$paymentobj->error); } @@ -1429,10 +1442,11 @@ class Invoices extends DolibarrApi if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) { throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode); } - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + } $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error); } @@ -1501,8 +1515,7 @@ class Invoices extends DolibarrApi $multicurrency_amounts = array(); // Loop on each invoice to pay - foreach ($arrayofamounts as $id => $amountarray) - { + foreach ($arrayofamounts as $id => $amountarray) { $result = $this->invoice->fetch($id); if (!$result) { $this->db->rollback(); @@ -1528,13 +1541,11 @@ class Invoices extends DolibarrApi $totaldeposits = $this->invoice->getSumDepositsUsed($is_multicurrency); $remainstopay = $amount = price2num($total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); - if (!$is_multicurrency && $amountarray["amount"] != 'remain') - { + if (!$is_multicurrency && $amountarray["amount"] != 'remain') { $amount = price2num($amountarray["amount"], 'MT'); } - if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') - { + if ($is_multicurrency && $amountarray["multicurrency_amount"] != 'remain') { $amount = price2num($amountarray["multicurrency_amount"], 'MT'); } @@ -1569,8 +1580,7 @@ class Invoices extends DolibarrApi $paymentobj->note_private = $comment; $paymentobj->ref_ext = $ref_ext; $payment_id = $paymentobj->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices - if ($payment_id < 0) - { + if ($payment_id < 0) { $this->db->rollback(); throw new RestException(400, 'Payment error : '.$paymentobj->error); } @@ -1579,10 +1589,11 @@ class Invoices extends DolibarrApi if ($paymentobj->paiementcode == 'CHQ' && empty($chqemetteur)) { throw new RestException(400, 'Emetteur is mandatory when payment code is '.$paymentobj->paiementcode); } - if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { + $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + } $result = $paymentobj->addPaymentToBank(DolibarrApiAccess::$user, 'payment', $label, $accountid, $chqemetteur, $chqbank); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); throw new RestException(400, 'Add payment to bank error : '.$paymentobj->error); } diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 13a58a3e075..ad880470b50 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -218,11 +218,12 @@ class FactureRec extends CommonInvoice $this->titre = trim(isset($this->titre) ? $this->titre : $this->title); // deprecated $this->title = trim($this->title); $this->usenewprice = empty($this->usenewprice) ? 0 : $this->usenewprice; - if (empty($this->suspended)) $this->suspended = 0; + if (empty($this->suspended)) { + $this->suspended = 0; + } // No frequency defined then no next date to execution - if (empty($this->frequency)) - { + if (empty($this->frequency)) { $this->frequency = 0; $this->date_when = null; } @@ -238,8 +239,7 @@ class FactureRec extends CommonInvoice // Charge facture modele $facsrc = new Facture($this->db); $result = $facsrc->fetch($facid); - if ($result > 0) - { + if ($result > 0) { // On positionne en mode brouillon la facture $this->brouillon = 1; @@ -301,8 +301,7 @@ class FactureRec extends CommonInvoice $sql .= ", ".$this->db->escape($this->suspended); $sql .= ")"; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."facture_rec"); // Fields used into addline later @@ -312,10 +311,11 @@ class FactureRec extends CommonInvoice // Add lines $num = count($facsrc->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $tva_tx = $facsrc->lines[$i]->tva_tx; - if (!empty($facsrc->lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$facsrc->lines[$i]->vat_src_code.')'; + if (!empty($facsrc->lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) { + $tva_tx .= ' ('.$facsrc->lines[$i]->vat_src_code.')'; + } $result_insert = $this->addline( $facsrc->lines[$i]->desc, @@ -338,13 +338,11 @@ class FactureRec extends CommonInvoice $facsrc->lines[$i]->multicurrency_subprice ); - if ($result_insert < 0) - { + if ($result_insert < 0) { $error++; } else { $objectline = new FactureLigneRec($this->db); - if ($objectline->fetch($result_insert)) - { + if ($objectline->fetch($result_insert)) { // Extrafields if (method_exists($facsrc->lines[$i], 'fetch_optionals')) { $facsrc->lines[$i]->fetch_optionals($facsrc->lines[$i]->id); @@ -352,31 +350,24 @@ class FactureRec extends CommonInvoice } $result = $objectline->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } } } - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -385,8 +376,7 @@ class FactureRec extends CommonInvoice { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -396,26 +386,22 @@ class FactureRec extends CommonInvoice if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BILLREC_CREATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -2; } // End call triggers } - if ($error) - { + if ($error) { $this->db->rollback(); } else { $this->db->commit(); @@ -453,23 +439,18 @@ class FactureRec extends CommonInvoice dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { + if ($resql) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BILLREC_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -2; } @@ -512,18 +493,19 @@ class FactureRec extends CommonInvoice $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; //$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."element_element as el ON el.fk_target = f.rowid AND el.targettype = 'facture'"; $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; - if ($rowid) $sql .= ' AND f.rowid='.$rowid; - elseif ($ref) $sql .= " AND f.titre='".$this->db->escape($ref)."'"; + if ($rowid) { + $sql .= ' AND f.rowid='.$rowid; + } elseif ($ref) { + $sql .= " AND f.titre='".$this->db->escape($ref)."'"; + } /* This field are not used for template invoice if ($ref_ext) $sql.= " AND f.ref_ext='".$this->db->escape($ref_ext)."'"; if ($ref_int) $sql.= " AND f.ref_int='".$this->db->escape($ref_int)."'"; */ $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -584,7 +566,9 @@ class FactureRec extends CommonInvoice $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; + if ($this->statut == self::STATUS_DRAFT) { + $this->brouillon = 1; + } // Retrieve all extrafield // fetch optionals attributes and labels @@ -594,8 +578,7 @@ class FactureRec extends CommonInvoice * Lines */ $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); return -3; } @@ -638,8 +621,7 @@ class FactureRec extends CommonInvoice // Retrieve all extrafield for line // fetch optionals attributes and labels - if (!is_object($extrafields)) - { + if (!is_object($extrafields)) { require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); } @@ -662,12 +644,10 @@ class FactureRec extends CommonInvoice dol_syslog('FactureRec::fetch_lines', LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new FactureLigneRec($this->db); @@ -764,18 +744,20 @@ class FactureRec extends CommonInvoice dol_syslog($sqlef); $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet_rec WHERE fk_facture = ".$rowid; dol_syslog($sql); - if ($this->db->query($sqlef) && $this->db->query($sql)) - { + if ($this->db->query($sqlef) && $this->db->query($sql)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."facture_rec WHERE rowid = ".$rowid; dol_syslog($sql); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error = -3; + if ($res < 0) { + $error = -3; + } // Delete extrafields $res = $this->deleteExtraFields(); - if ($res < 0) $error = -4; + if ($res < 0) { + $error = -4; + } } else { $this->error = $this->db->lasterror(); $error = -1; @@ -785,8 +767,7 @@ class FactureRec extends CommonInvoice $error = -2; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -833,23 +814,25 @@ class FactureRec extends CommonInvoice include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } $localtaxes_type = getLocalTaxesFromRate($txtva, 0, $this->thirdparty, $mysoc); // Clean vat code $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } - if ($this->brouillon) - { + if ($this->brouillon) { // Clean parameters $remise_percent = price2num($remise_percent); - if (empty($remise_percent)) $remise_percent = 0; + if (empty($remise_percent)) { + $remise_percent = 0; + } $qty = price2num($qty); $pu_ht = price2num($pu_ht); $pu_ttc = price2num($pu_ttc); @@ -858,13 +841,20 @@ class FactureRec extends CommonInvoice } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; - if (empty($info_bits)) $info_bits = 0; + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; @@ -890,8 +880,7 @@ class FactureRec extends CommonInvoice $pu_ht_devise = $tabprice[19]; $product_type = $type; - if ($fk_product) - { + if ($fk_product) { $product = new Product($this->db); $result = $product->fetch($fk_product); $product_type = $product->type; @@ -967,8 +956,7 @@ class FactureRec extends CommonInvoice $sql .= ")"; dol_syslog(get_class($this)."::addline", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $lineId = $this->db->last_insert_id(MAIN_DB_PREFIX."facturedet_rec"); $this->id = $facid; $this->update_price(); @@ -1019,35 +1007,51 @@ class FactureRec extends CommonInvoice include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (empty($remise_percent)) $remise_percent = 0; + if (empty($remise_percent)) { + $remise_percent = 0; + } // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } - if ($this->brouillon) - { + if ($this->brouillon) { // Clean parameters $remise_percent = price2num($remise_percent); $qty = price2num($qty); - if (empty($info_bits)) $info_bits = 0; + if (empty($info_bits)) { + $info_bits = 0; + } $pu_ht = price2num($pu_ht); $pu_ttc = price2num($pu_ttc); $pu_ht_devise = price2num($pu_ht_devise); - if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' - } + if (!preg_match('/\((.*)\)/', $txtva)) { + $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' + } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; + if (empty($this->multicurrency_subprice)) { + $this->multicurrency_subprice = 0; + } + if (empty($this->multicurrency_total_ht)) { + $this->multicurrency_total_ht = 0; + } + if (empty($this->multicurrency_total_tva)) { + $this->multicurrency_total_tva = 0; + } + if (empty($this->multicurrency_total_ttc)) { + $this->multicurrency_total_ttc = 0; + } - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; @@ -1061,9 +1065,8 @@ class FactureRec extends CommonInvoice // Clean vat code $vat_src_code = ''; - $reg = array(); - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + $reg = array(); + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -1086,8 +1089,7 @@ class FactureRec extends CommonInvoice $pu_ht_devise = $tabprice[19]; $product_type = $type; - if ($fk_product) - { + if ($fk_product) { $product = new Product($this->db); $result = $product->fetch($fk_product); $product_type = $product->type; @@ -1129,8 +1131,7 @@ class FactureRec extends CommonInvoice $sql .= " WHERE rowid = ".$rowid; dol_syslog(get_class($this)."::updateline", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->id = $facid; $this->update_price(); return 1; @@ -1149,7 +1150,9 @@ class FactureRec extends CommonInvoice */ public function getNextDate() { - if (empty($this->date_when)) return false; + if (empty($this->date_when)) { + return false; + } return dol_time_plus_duree($this->date_when, $this->frequency, $this->unit_frequency); } @@ -1161,7 +1164,9 @@ class FactureRec extends CommonInvoice public function isMaxNbGenReached() { $ret = false; - if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) $ret = true; + if ($this->nb_gen_max > 0 && ($this->nb_gen_done >= $this->nb_gen_max)) { + $ret = true; + } return $ret; } @@ -1209,8 +1214,9 @@ class FactureRec extends CommonInvoice $sql .= ' AND (nb_gen_done < nb_gen_max OR nb_gen_max = 0)'; $sql .= ' AND suspended = 0'; $sql .= ' AND entity = '.$conf->entity; // MUST STAY = $conf->entity here - if ($restrictioninvoiceid > 0) + if ($restrictioninvoiceid > 0) { $sql .= ' AND rowid = '.$restrictioninvoiceid; + } $sql .= $this->db->order('entity', 'ASC'); //print $sql;exit; $parameters = array( @@ -1220,19 +1226,19 @@ class FactureRec extends CommonInvoice $reshook = $hookmanager->executeHooks('beforeCreationOfRecurringInvoices', $parameters, $sql); // note that $sql might be modified by hooks $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $this->db->num_rows($resql); - if ($num) + if ($num) { $this->output .= $langs->trans("FoundXQualifiedRecurringInvoiceTemplate", $num)."\n"; - else $this->output .= $langs->trans("NoQualifiedRecurringInvoiceTemplateFound"); + } else { + $this->output .= $langs->trans("NoQualifiedRecurringInvoiceTemplateFound"); + } $saventity = $conf->entity; - while ($i < $num) // Loop on each template invoice. If $num = 0, test is false at first pass. - { + while ($i < $num) { // Loop on each template invoice. If $num = 0, test is false at first pass. $line = $this->db->fetch_object($resql); $this->db->begin(); @@ -1243,8 +1249,7 @@ class FactureRec extends CommonInvoice $facturerec = new FactureRec($this->db); $facturerec->fetch($line->rowid); - if ($facturerec->id > 0) - { + if ($facturerec->id > 0) { // Set entity context $conf->entity = $facturerec->entity; @@ -1260,24 +1265,20 @@ class FactureRec extends CommonInvoice $facture->socid = $facturerec->socid; $invoiceidgenerated = $facture->create($user); - if ($invoiceidgenerated <= 0) - { + if ($invoiceidgenerated <= 0) { $this->errors = $facture->errors; $this->error = $facture->error; $error++; } - if (!$error && ($facturerec->auto_validate || $forcevalidation)) - { + if (!$error && ($facturerec->auto_validate || $forcevalidation)) { $result = $facture->validate($user); - if ($result <= 0) - { + if ($result <= 0) { $this->errors = $facture->errors; $this->error = $facture->error; $error++; } } - if (!$error && $facturerec->generate_pdf) - { + if (!$error && $facturerec->generate_pdf) { // We refresh the object in order to have all necessary data (like date_lim_reglement) $facture->fetch($facture->id); $result = $facture->generateDocument($facturerec->model_pdf, $langs); @@ -1294,8 +1295,7 @@ class FactureRec extends CommonInvoice dol_syslog("createRecurringInvoices Failed to load invoice template with id=".$line->rowid.", entity=".$conf->entity); } - if (!$error && $invoiceidgenerated >= 0) - { + if (!$error && $invoiceidgenerated >= 0) { $this->db->commit("createRecurringInvoices Process invoice template id=".$facturerec->id.", ref=".$facturerec->ref); dol_syslog("createRecurringInvoices Process invoice template ".$facturerec->ref." is finished with a success generation"); $nb_create++; @@ -1318,7 +1318,9 @@ class FactureRec extends CommonInvoice } $conf->entity = $saventity; // Restore entity context - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } $this->output = trim($this->output); @@ -1357,28 +1359,39 @@ class FactureRec extends CommonInvoice if (!empty($this->date_when)) { $label .= '
'.$langs->trans('NextDateToExecution').': '; $label .= (empty($this->suspended) ? '' : '').dol_print_date($this->date_when, 'day').(empty($this->suspended) ? '' : ''); // No hour for this property - if (!empty($this->suspended)) $label .= ' ('.$langs->trans("Disabled").')'; + if (!empty($this->suspended)) { + $label .= ' ('.$langs->trans("Disabled").')'; + } } } $url = DOL_URL_ROOT.'/compta/facture/card-rec.php?facid='.$this->id; - if ($short) return $url; + if ($short) { + return $url; + } - if ($option != 'nolink') - { + if ($option != 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } } $linkstart = ''; $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; return $result; @@ -1417,11 +1430,9 @@ class FactureRec extends CommonInvoice $statusType = 'status0'; //print "$recur,$status,$mode,$alreadypaid,$type"; - if ($mode == 0) - { + if ($mode == 0) { $prefix = ''; - if ($recur) - { + if ($recur) { if ($status == self::STATUS_SUSPENDED) { $labelStatus = $langs->trans('Disabled'); } else { @@ -1434,11 +1445,9 @@ class FactureRec extends CommonInvoice $labelStatus = $langs->trans("Draft"); } } - } elseif ($mode == 1) - { + } elseif ($mode == 1) { $prefix = 'Short'; - if ($recur) - { + if ($recur) { if ($status == self::STATUS_SUSPENDED) { $labelStatus = $langs->trans('Disabled'); } else { @@ -1451,10 +1460,8 @@ class FactureRec extends CommonInvoice $labelStatus = $langs->trans("Draft"); } } - } elseif ($mode == 2) - { - if ($recur) - { + } elseif ($mode == 2) { + if ($recur) { if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); @@ -1471,10 +1478,8 @@ class FactureRec extends CommonInvoice $labelStatus = $langs->trans('Draft'); } } - } elseif ($mode == 3) - { - if ($recur) - { + } elseif ($mode == 3) { + if ($recur) { $prefix = 'Short'; if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; @@ -1492,11 +1497,9 @@ class FactureRec extends CommonInvoice $labelStatus = $langs->trans('Draft'); } } - } elseif ($mode == 4) - { + } elseif ($mode == 4) { $prefix = ''; - if ($recur) - { + if ($recur) { if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); @@ -1513,12 +1516,12 @@ class FactureRec extends CommonInvoice $labelStatus = $langs->trans('Draft'); } } - } elseif ($mode == 5 || $mode == 6) - { + } elseif ($mode == 5 || $mode == 6) { $prefix = ''; - if ($mode == 5) $prefix = 'Short'; - if ($recur) - { + if ($mode == 5) { + $prefix = 'Short'; + } + if ($recur) { if ($status == self::STATUS_SUSPENDED) { $statusType = 'status6'; $labelStatus = $langs->trans('Disabled'); @@ -1537,7 +1540,9 @@ class FactureRec extends CommonInvoice } } - if (empty($labelStatusShort)) $labelStatusShort = $labelStatus; + if (empty($labelStatusShort)) { + $labelStatusShort = $labelStatus; + } return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode); } @@ -1568,12 +1573,10 @@ class FactureRec extends CommonInvoice $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -1598,13 +1601,11 @@ class FactureRec extends CommonInvoice $this->fk_incoterms = 0; $this->location_incoterms = ''; - if (empty($option) || $option != 'nolines') - { + if (empty($option) || $option != 'nolines') { // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new FactureLigne($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->qty = 1; @@ -1613,23 +1614,20 @@ class FactureRec extends CommonInvoice $line->localtax1_tx = 0; $line->localtax2_tx = 0; $line->remise_percent = 0; - if ($xnbp == 1) // Qty is negative (product line) - { + if ($xnbp == 1) { // Qty is negative (product line) $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; $line->qty = -1; $line->total_ht = -100; $line->total_ttc = -119.6; $line->total_tva = -19.6; - } elseif ($xnbp == 2) // UP is negative (free line) - { + } elseif ($xnbp == 2) { // UP is negative (free line) $line->subprice = -100; $line->total_ht = -100; $line->total_ttc = -119.6; $line->total_tva = -19.6; $line->remise_percent = 0; - } elseif ($xnbp == 3) // Discount is 50% (product line) - { + } elseif ($xnbp == 3) { // Discount is 50% (product line) $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; $line->total_ht = 50; @@ -1723,7 +1721,9 @@ class FactureRec extends CommonInvoice dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); if ($this->db->query($sql)) { $this->frequency = $frequency; - if (!empty($unit)) $this->unit_frequency = $unit; + if (!empty($unit)) { + $this->unit_frequency = $unit; + } return 1; } else { dol_print_error($this->db); @@ -1740,21 +1740,23 @@ class FactureRec extends CommonInvoice */ public function setNextDate($date, $increment_nb_gen_done = 0) { - if (!$this->table_element) - { + if (!$this->table_element) { dol_syslog(get_class($this)."::setNextDate was called on objet with property table_element not defined", LOG_ERR); return -1; } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null"); - if ($increment_nb_gen_done > 0) $sql .= ', nb_gen_done = nb_gen_done + 1'; + if ($increment_nb_gen_done > 0) { + $sql .= ', nb_gen_done = nb_gen_done + 1'; + } $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->date_when = $date; - if ($increment_nb_gen_done > 0) $this->nb_gen_done++; + if ($increment_nb_gen_done > 0) { + $this->nb_gen_done++; + } return 1; } else { dol_print_error($this->db); @@ -1770,21 +1772,21 @@ class FactureRec extends CommonInvoice */ public function setMaxPeriod($nb) { - if (!$this->table_element) - { + if (!$this->table_element) { dol_syslog(get_class($this)."::setMaxPeriod was called on objet with property table_element not defined", LOG_ERR); return -1; } - if (empty($nb)) $nb = 0; + if (empty($nb)) { + $nb = 0; + } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET nb_gen_max = '.$nb; $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setMaxPeriod", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->nb_gen_max = $nb; return 1; } else { @@ -1801,8 +1803,7 @@ class FactureRec extends CommonInvoice */ public function setAutoValidate($validate) { - if (!$this->table_element) - { + if (!$this->table_element) { dol_syslog(get_class($this)."::setAutoValidate was called on objet with property table_element not defined", LOG_ERR); return -1; } @@ -1812,8 +1813,7 @@ class FactureRec extends CommonInvoice $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setAutoValidate", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->auto_validate = $validate; return 1; } else { @@ -1830,8 +1830,7 @@ class FactureRec extends CommonInvoice */ public function setGeneratePdf($validate) { - if (!$this->table_element) - { + if (!$this->table_element) { dol_syslog(get_class($this)."::setGeneratePdf was called on objet with property table_element not defined", LOG_ERR); return -1; } @@ -1841,8 +1840,7 @@ class FactureRec extends CommonInvoice $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setGeneratePdf", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->generate_pdf = $validate; return 1; } else { @@ -1859,8 +1857,7 @@ class FactureRec extends CommonInvoice */ public function setModelPdf($model) { - if (!$this->table_element) - { + if (!$this->table_element) { dol_syslog(get_class($this)."::setModelPdf was called on objet with property table_element not defined", LOG_ERR); return -1; } @@ -1870,8 +1867,7 @@ class FactureRec extends CommonInvoice $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setModelPdf", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->model_pdf = $model; return 1; } else { @@ -1918,21 +1914,21 @@ class FactureLigneRec extends CommonInvoiceLine if (!$notrigger) { // Call triggers $result = $this->call_trigger('LINEBILLREC_DELETE', $user); - if ($result < 0) { $error++; } // Do also here what you must do to rollback action if trigger fail + if ($result < 0) { + $error++; + } // Do also here what you must do to rollback action if trigger fail // End call triggers } } - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); if ($result < 0) { $error++; } } - if (!$error) - { + if (!$error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.$this->table_element.' WHERE rowid='.$this->id; $res = $this->db->query($sql); @@ -1974,8 +1970,7 @@ class FactureLigneRec extends CommonInvoiceLine dol_syslog('FactureRec::fetch', LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); $this->id = $objp->rowid; @@ -2075,23 +2070,18 @@ class FactureLigneRec extends CommonInvoiceLine dol_syslog(get_class($this)."::updateline", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { + if ($resql) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEBILLREC_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $error++; } // End call triggers diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 7f686accb4e..983e42f5ff5 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -45,8 +45,12 @@ require_once DOL_DOCUMENT_ROOT.'/societe/class/client.class.php'; require_once DOL_DOCUMENT_ROOT.'/margin/lib/margins.lib.php'; require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +} +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +} /** * Class to manage invoices @@ -428,20 +432,28 @@ class Facture extends CommonInvoice $error = 0; // Clean parameters - if (empty($this->type)) $this->type = self::TYPE_STANDARD; + if (empty($this->type)) { + $this->type = self::TYPE_STANDARD; + } $this->ref_client = trim($this->ref_client); $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note_private)); $this->note_public = trim($this->note_public); - if (!$this->cond_reglement_id) $this->cond_reglement_id = 0; - if (!$this->mode_reglement_id) $this->mode_reglement_id = 0; + if (!$this->cond_reglement_id) { + $this->cond_reglement_id = 0; + } + if (!$this->mode_reglement_id) { + $this->mode_reglement_id = 0; + } $this->brouillon = 1; // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate) - if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); - else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); + } else { + $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; @@ -450,16 +462,14 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::create user=".$user->id." date=".$this->date); // Check parameters - if (empty($this->date)) - { + if (empty($this->date)) { $this->error = "Try to create an invoice with an empty parameter (date)"; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -3; } $soc = new Societe($this->db); $result = $soc->fetch($this->socid); - if ($result < 0) - { + if ($result < 0) { $this->error = "Failed to fetch company: ".$soc->error; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -2; @@ -474,8 +484,7 @@ class Facture extends CommonInvoice $previousdaynextdatewhen = null; // Create invoice from a template recurring invoice - if ($this->fac_rec > 0) - { + if ($this->fac_rec > 0) { $this->fk_fac_rec_source = $this->fac_rec; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture-rec.class.php'; @@ -488,8 +497,7 @@ class Facture extends CommonInvoice $nextdatewhen = dol_time_plus_duree($originaldatewhen, $_facrec->frequency, $_facrec->unit_frequency); $previousdaynextdatewhen = dol_time_plus_duree($nextdatewhen, -1, 'd'); - if (!empty($_facrec->frequency)) // Invoice are created on same thirdparty than template when there is a recurrence, but not necessarly when there is no recurrence. - { + if (!empty($_facrec->frequency)) { // Invoice are created on same thirdparty than template when there is a recurrence, but not necessarly when there is no recurrence. $this->socid = $_facrec->socid; } $this->entity = $_facrec->entity; // Invoice created in same entity than template @@ -514,7 +522,9 @@ class Facture extends CommonInvoice $this->location_incoterms = $_facrec->location_incoterms; // Clean parameters - if (!$this->type) $this->type = self::TYPE_STANDARD; + if (!$this->type) { + $this->type = self::TYPE_STANDARD; + } $this->ref_client = trim($this->ref_client); $this->note_public = trim($this->note_public); $this->note_private = trim($this->note_private); @@ -523,7 +533,9 @@ class Facture extends CommonInvoice $this->array_options = $_facrec->array_options; //if (! $this->remise) $this->remise = 0; - if (!$this->mode_reglement_id) $this->mode_reglement_id = 0; + if (!$this->mode_reglement_id) { + $this->mode_reglement_id = 0; + } $this->brouillon = 1; $this->linked_objects = $_facrec->linkedObjectsIds; @@ -533,10 +545,11 @@ class Facture extends CommonInvoice $forceduedate = $this->calculate_date_lim_reglement(); // For recurring invoices, update date and number of last generation of recurring template invoice, before inserting new invoice - if ($_facrec->frequency > 0) - { + if ($_facrec->frequency > 0) { dol_syslog("This is a recurring invoice so we set date_last_gen and next date_when"); - if (empty($_facrec->date_when)) $_facrec->date_when = $now; + if (empty($_facrec->date_when)) { + $_facrec->date_when = $now; + } $next_date = $_facrec->getNextDate(); // Calculate next date $result = $_facrec->setValueFrom('date_last_gen', $now, '', null, 'date', '', $user, ''); //$_facrec->setValueFrom('nb_gen_done', $_facrec->nb_gen_done + 1); // Not required, +1 already included into setNextDate when second param is 1. @@ -547,10 +560,13 @@ class Facture extends CommonInvoice $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ... - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) $newlang = $this->default_lang; // for thirdparty - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->thirdparty->default_lang)) { + $newlang = $this->thirdparty->default_lang; // for proposal, order, invoice, ... + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($this->default_lang)) { + $newlang = $this->default_lang; // for thirdparty + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -585,9 +601,9 @@ class Facture extends CommonInvoice if (empty($forceduedate)) { $duedate = $this->calculate_date_lim_reglement(); /*if ($duedate < 0) { Regression, a date can be negative if before 1970. - dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR); - return -1; - }*/ + dol_syslog(__METHOD__ . ' Error in calculate_date_lim_reglement. We got ' . $duedate, LOG_ERR); + return -1; + }*/ $this->date_lim_reglement = $duedate; } else { $this->date_lim_reglement = $forceduedate; @@ -662,8 +678,7 @@ class Facture extends CommonInvoice $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture'); // Update ref with new one @@ -671,25 +686,21 @@ class Facture extends CommonInvoice $sql = 'UPDATE '.MAIN_DB_PREFIX."facture SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -698,8 +709,7 @@ class Facture extends CommonInvoice { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -708,23 +718,22 @@ class Facture extends CommonInvoice } // Propagate contacts - if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) // Get contact from origin object - { + if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object $originforcontact = $this->origin; $originidforcontact = $this->origin_id; - if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order - { + if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; $exp = new Expedition($this->db); $exp->fetch($this->origin_id); $exp->fetchObjectLinked(null, '', null, '', 'OR', 1, 'sourcetype', 0); - if (count($exp->linkedObjectsIds['commande']) > 0) - { - foreach ($exp->linkedObjectsIds['commande'] as $key => $value) - { + if (count($exp->linkedObjectsIds['commande']) > 0) { + foreach ($exp->linkedObjectsIds['commande'] as $key => $value) { $originforcontact = 'commande'; - if (is_object($value)) $originidforcontact = $value->id; - else $originidforcontact = $value; + if (is_object($value)) { + $originidforcontact = $value->id; + } else { + $originidforcontact = $value; + } break; // We take first one } } @@ -734,26 +743,24 @@ class Facture extends CommonInvoice $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'"; $resqlcontact = $this->db->query($sqlcontact); - if ($resqlcontact) - { - while ($objcontact = $this->db->fetch_object($resqlcontact)) - { + if ($resqlcontact) { + while ($objcontact = $this->db->fetch_object($resqlcontact)) { //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n"; $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object } - } else dol_print_error($resqlcontact); + } else { + dol_print_error($resqlcontact); + } } /* * Insert lines of invoices, if not from template invoice, into database */ - if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode) - { + if (!$error && empty($this->fac_rec) && count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode) $fk_parent_line = 0; dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects"); - foreach ($this->lines as $i => $val) - { + foreach ($this->lines as $i => $val) { $newinvoiceline = $this->lines[$i]; $newinvoiceline->fk_facture = $this->id; @@ -761,17 +768,14 @@ class Facture extends CommonInvoice $newinvoiceline->origin_id = $this->lines[$i]->id; // Auto set date of service ? - if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) // $originaldatewhen is defined when generating from recurring invoice only - { + if ($this->lines[$i]->date_start_fill == 1 && $originaldatewhen) { // $originaldatewhen is defined when generating from recurring invoice only $newinvoiceline->date_start = $originaldatewhen; } - if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) // $previousdaynextdatewhen is defined when generating from recurring invoice only - { + if ($this->lines[$i]->date_end_fill == 1 && $previousdaynextdatewhen) { // $previousdaynextdatewhen is defined when generating from recurring invoice only $newinvoiceline->date_end = $previousdaynextdatewhen; } - if ($result >= 0) - { + if ($result >= 0) { // Reset fk_parent_line for no child products and special product if (($newinvoiceline->product_type != 9 && empty($newinvoiceline->fk_parent_line)) || $newinvoiceline->product_type == 9) { $fk_parent_line = 0; @@ -794,30 +798,28 @@ class Facture extends CommonInvoice $fk_parent_line = $result; } } - if ($result < 0) - { + if ($result < 0) { $this->error = $newinvoiceline->error; $this->errors = $newinvoiceline->errors; $error++; break; } } - } elseif (!$error && empty($this->fac_rec)) // If this->lines is an array of invoice line arrays - { + } elseif (!$error && empty($this->fac_rec)) { // If this->lines is an array of invoice line arrays $fk_parent_line = 0; dol_syslog("There is ".count($this->lines)." lines that are array lines"); - foreach ($this->lines as $i => $val) - { + foreach ($this->lines as $i => $val) { $line = $this->lines[$i]; // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. - if (!is_object($line)) $line = (object) $line; + if (!is_object($line)) { + $line = (object) $line; + } - if ($result >= 0) - { + if ($result >= 0) { // Reset fk_parent_line for no child products and special product if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { $fk_parent_line = 0; @@ -825,7 +827,9 @@ class Facture extends CommonInvoice // Complete vat rate with code $vatrate = $line->tva_tx; - if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) $vatrate .= ' ('.$line->vat_src_code.')'; + if ($line->vat_src_code && !preg_match('/\(.*\)/', $vatrate)) { + $vatrate .= ' ('.$line->vat_src_code.')'; + } if (!empty($conf->global->MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION)) { $originid = $line->origin_id; @@ -872,8 +876,7 @@ class Facture extends CommonInvoice $line->multicurrency_subprice, $line->ref_ext ); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); dol_print_error($this->db); $this->db->rollback(); @@ -891,12 +894,9 @@ class Facture extends CommonInvoice /* * Insert lines of template invoices */ - if (!$error && $this->fac_rec > 0) - { - foreach ($_facrec->lines as $i => $val) - { - if ($_facrec->lines[$i]->fk_product) - { + if (!$error && $this->fac_rec > 0) { + foreach ($_facrec->lines as $i => $val) { + if ($_facrec->lines[$i]->fk_product) { $prod = new Product($this->db); $res = $prod->fetch($_facrec->lines[$i]->fk_product); } @@ -911,15 +911,16 @@ class Facture extends CommonInvoice */ $tva_tx = $_facrec->lines[$i]->tva_tx.($_facrec->lines[$i]->vat_src_code ? '('.$_facrec->lines[$i]->vat_src_code.')' : ''); $tva_npr = $_facrec->lines[$i]->info_bits; - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $localtax1_tx = $_facrec->lines[$i]->localtax1_tx; $localtax2_tx = $_facrec->lines[$i]->localtax2_tx; $fk_product_fournisseur_price = empty($_facrec->lines[$i]->fk_product_fournisseur_price) ?null:$_facrec->lines[$i]->fk_product_fournisseur_price; $buyprice = empty($_facrec->lines[$i]->buyprice) ? 0 : $_facrec->lines[$i]->buyprice; // If buyprice not defined from template invoice, we try to guess the best value - if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) - { + if (!$buyprice && $_facrec->lines[$i]->fk_product > 0) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $producttmp = new ProductFournisseur($this->db); $producttmp->fetch($_facrec->lines[$i]->fk_product); @@ -927,13 +928,13 @@ class Facture extends CommonInvoice // If margin module defined on costprice, we try the costprice // If not defined or if module margin defined and pmp and stock module enabled, we try pmp price // else we get the best supplier price - if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) $buyprice = $producttmp->cost_price; - elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) $buyprice = $producttmp->pmp; - else { - if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) - { - if ($producttmp->product_fourn_price_id > 0) - { + if ($conf->global->MARGIN_TYPE == 'costprice' && !empty($producttmp->cost_price)) { + $buyprice = $producttmp->cost_price; + } elseif (!empty($conf->stock->enabled) && ($conf->global->MARGIN_TYPE == 'costprice' || $conf->global->MARGIN_TYPE == 'pmp') && !empty($producttmp->pmp)) { + $buyprice = $producttmp->pmp; + } else { + if ($producttmp->find_min_price_product_fournisseur($_facrec->lines[$i]->fk_product) > 0) { + if ($producttmp->product_fourn_price_id > 0) { $buyprice = price2num($producttmp->fourn_unitprice * (1 - $producttmp->fourn_remise_percent / 100) + $producttmp->fourn_remise, 'MU'); } } @@ -972,8 +973,7 @@ class Facture extends CommonInvoice $_facrec->lines[$i]->multicurrency_subprice ); - if ($result_insert < 0) - { + if ($result_insert < 0) { $error++; $this->error = $this->db->error(); break; @@ -981,30 +981,29 @@ class Facture extends CommonInvoice } } - if (!$error) - { + if (!$error) { $result = $this->update_price(1); - if ($result > 0) - { + if ($result > 0) { $action = 'create'; // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BILL_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1087,11 +1086,9 @@ class Facture extends CommonInvoice // Loop on each line of new invoice - foreach ($facture->lines as $i => $tmpline) - { + foreach ($facture->lines as $i => $tmpline) { $facture->lines[$i]->fk_prev_id = $this->lines[$i]->rowid; - if ($invertdetail) - { + if ($invertdetail) { $facture->lines[$i]->subprice = -$facture->lines[$i]->subprice; $facture->lines[$i]->total_ht = -$facture->lines[$i]->total_ht; $facture->lines[$i]->total_tva = -$facture->lines[$i]->total_tva; @@ -1105,18 +1102,14 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::createFromCurrent invertdetail=".$invertdetail." socid=".$this->socid." nboflines=".count($facture->lines)); $facid = $facture->create($user); - if ($facid <= 0) - { + if ($facid <= 0) { $this->error = $facture->error; $this->errors = $facture->errors; - } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) - { + } elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION)) { $this->fetchObjectLinked('', '', $this->id, 'facture'); - foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) - { - foreach ($Tfk_object as $fk_object) - { + foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) { + foreach ($Tfk_object as $fk_object) { $facture->add_object_linked($typeObject, $fk_object); } } @@ -1148,12 +1141,10 @@ class Facture extends CommonInvoice $object->fetch($fromid); // Change socid if needed - if (!empty($this->socid) && $this->socid != $object->socid) - { + if (!empty($this->socid) && $this->socid != $object->socid) { $objsoc = new Societe($this->db); - if ($objsoc->fetch($this->socid) > 0) - { + if ($objsoc->fetch($this->socid) > 0) { $object->socid = $objsoc->id; $object->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); $object->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); @@ -1187,10 +1178,8 @@ class Facture extends CommonInvoice } // Loop on each line of new invoice - foreach ($object->lines as $i => $line) - { - if (($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts - { + foreach ($object->lines as $i => $line) { + if (($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts unset($object->lines[$i]); } @@ -1224,37 +1213,36 @@ class Facture extends CommonInvoice // Create clone $object->context['createfromclone'] = 'createfromclone'; $result = $object->create($user); - if ($result < 0) $error++; - else { + if ($result < 0) { + $error++; + } else { // copy internal contacts - if ($object->copy_linked_contact($this, 'internal') < 0) + if ($object->copy_linked_contact($this, 'internal') < 0) { $error++; - - // copy external contacts if same company - elseif ($this->socid == $object->socid) - { - if ($object->copy_linked_contact($this, 'external') < 0) + } elseif ($this->socid == $object->socid) { + // copy external contacts if same company + if ($object->copy_linked_contact($this, 'external') < 0) { $error++; + } } } - if (!$error) - { + if (!$error) { // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$this); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -1281,8 +1269,7 @@ class Facture extends CommonInvoice $this->source = 0; $num = count($object->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $line = new FactureLigne($this->db); $line->libelle = $object->lines[$i]->libelle; // deprecated @@ -1345,8 +1332,7 @@ class Facture extends CommonInvoice $this->contact_id = $object->contact_id; $this->ref_client = $object->ref_client; - if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) - { + if (empty($conf->global->MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN)) { $this->note_private = $object->note_private; $this->note_public = $object->note_public; } @@ -1361,13 +1347,13 @@ class Facture extends CommonInvoice // get extrafields from original line $object->fetch_optionals(); - foreach ($object->array_options as $options_key => $value) + foreach ($object->array_options as $options_key => $value) { $this->array_options[$options_key] = $value; + } // Possibility to add external linked objects with hooks $this->linked_objects[$this->origin] = $this->origin_id; - if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) - { + if (!empty($object->other_linked_objects) && is_array($object->other_linked_objects)) { $this->linked_objects = array_merge($this->linked_objects, $object->other_linked_objects); } @@ -1380,13 +1366,18 @@ class Facture extends CommonInvoice $parameters = array('objFrom'=>$object); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } - if (!$error) - { + if (!$error) { return 1; - } else return -1; - } else return -1; + } else { + return -1; + } + } else { + return -1; + } } /** @@ -1407,65 +1398,98 @@ class Facture extends CommonInvoice { global $langs, $conf, $user, $mysoc; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; - if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id; - else $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id; - - if (!$user->rights->facture->lire) - $option = 'nolink'; - - if ($option !== 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($option == 'withdraw') { + $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id; + } else { + $url = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$this->id; } - if ($short) return $url; + if (!$user->rights->facture->lire) { + $option = 'nolink'; + } + + if ($option !== 'nolink') { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } + } + + if ($short) { + return $url; + } $picto = $this->picto; - if ($this->type == self::TYPE_REPLACEMENT) $picto .= 'r'; // Replacement invoice - if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note - if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice + if ($this->type == self::TYPE_REPLACEMENT) { + $picto .= 'r'; // Replacement invoice + } + if ($this->type == self::TYPE_CREDIT_NOTE) { + $picto .= 'a'; // Credit note + } + if ($this->type == self::TYPE_DEPOSIT) { + $picto .= 'd'; // Deposit invoice + } $label = ''; if ($user->rights->facture->lire) { $label = img_picto('', $picto).' '.$langs->trans("Invoice").''; - if ($this->type == self::TYPE_REPLACEMENT) $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("ReplacementInvoice").''; - if ($this->type == self::TYPE_CREDIT_NOTE) $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("CreditNote").''; - if ($this->type == self::TYPE_DEPOSIT) $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("Deposit").''; - if ($this->type == self::TYPE_SITUATION) $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("InvoiceSituation").''; + if ($this->type == self::TYPE_REPLACEMENT) { + $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("ReplacementInvoice").''; + } + if ($this->type == self::TYPE_CREDIT_NOTE) { + $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("CreditNote").''; + } + if ($this->type == self::TYPE_DEPOSIT) { + $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("Deposit").''; + } + if ($this->type == self::TYPE_SITUATION) { + $label = img_picto('', $picto).' '.$langs->transnoentitiesnoconv("InvoiceSituation").''; + } if (isset($this->statut) && isset($this->alreadypaid)) { $label .= ' '.$this->getLibStatut(5, $this->alreadypaid); } - if (!empty($this->ref)) + if (!empty($this->ref)) { $label .= '
'.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->ref_client)) + } + if (!empty($this->ref_client)) { $label .= '
'.$langs->trans('RefCustomer').': '.$this->ref_client; - if (!empty($this->date)) - $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); - if (!empty($this->total_ht)) + } + if (!empty($this->date)) { + $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->date, 'day'); + } + if (!empty($this->total_ht)) { $label .= '
'.$langs->trans('AmountHT').': '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_tva)) + } + if (!empty($this->total_tva)) { $label .= '
'.$langs->trans('AmountVAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) // We keep test != 0 because $this->total_localtax1 can be '0.00000000' + } + if (!empty($this->total_localtax1) && $this->total_localtax1 != 0) { // We keep test != 0 because $this->total_localtax1 can be '0.00000000' $label .= '
'.$langs->transcountry('AmountLT1', $mysoc->country_code).': '.price($this->total_localtax1, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) + } + if (!empty($this->total_localtax2) && $this->total_localtax2 != 0) { $label .= '
'.$langs->transcountry('AmountLT2', $mysoc->country_code).': '.price($this->total_localtax2, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_ttc)) + } + if (!empty($this->total_ttc)) { $label .= '
'.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($moretitle) $label .= ' - '.$moretitle; + } + if ($moretitle) { + $label .= ' - '.$moretitle; + } } $linkclose = ($target ? ' target="'.$target.'"' : ''); - if (empty($notooltip) && $user->rights->facture->lire) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip) && $user->rights->facture->lire) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("Invoice"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -1483,15 +1507,17 @@ class Facture extends CommonInvoice } $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($max ?dol_trunc($this->ref, $max) : $this->ref); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= ($max ?dol_trunc($this->ref, $max) : $this->ref); + } $result .= $linkend; - if ($addlinktonotes) - { + if ($addlinktonotes) { $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { + if ($txttoshow) { //$notetoshow = $langs->trans("ViewPrivateNote").':
'.dol_string_nohtmltag($txttoshow, 1); $notetoshow = $langs->trans("ViewPrivateNote").':
'.$txttoshow; $result .= ' '; @@ -1521,7 +1547,9 @@ class Facture extends CommonInvoice { global $conf; - if (empty($rowid) && empty($ref) && empty($ref_ext)) return -1; + if (empty($rowid) && empty($ref) && empty($ref_ext)) { + return -1; + } $sql = 'SELECT f.rowid,f.entity,f.ref,f.ref_client,f.ref_ext,f.ref_int,f.type,f.fk_soc'; $sql .= ', f.tva, f.localtax1, f.localtax2, f.total, f.total_ttc, f.revenuestamp'; @@ -1548,20 +1576,25 @@ class Facture extends CommonInvoice $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as p ON f.fk_mode_reglement = p.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON f.fk_incoterms = i.rowid'; - if ($rowid) $sql .= " WHERE f.rowid=".$rowid; - else { + if ($rowid) { + $sql .= " WHERE f.rowid=".$rowid; + } else { $sql .= ' WHERE f.entity IN ('.getEntity('invoice').')'; // Dont't use entity if you use rowid - if ($ref) $sql .= " AND f.ref='".$this->db->escape($ref)."'"; - if ($ref_ext) $sql .= " AND f.ref_ext='".$this->db->escape($ref_ext)."'"; - if ($notused) $sql .= " AND f.ref_int='".$this->db->escape($notused)."'"; // deprecated + if ($ref) { + $sql .= " AND f.ref='".$this->db->escape($ref)."'"; + } + if ($ref_ext) { + $sql .= " AND f.ref_ext='".$this->db->escape($ref_ext)."'"; + } + if ($notused) { + $sql .= " AND f.ref_int='".$this->db->escape($notused)."'"; // deprecated + } } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -1633,7 +1666,7 @@ class Facture extends CommonInvoice $this->location_incoterms = $obj->location_incoterms; $this->label_incoterms = $obj->label_incoterms; - $this->module_source = $obj->module_source; + $this->module_source = $obj->module_source; $this->pos_source = $obj->pos_source; // Multicurrency @@ -1644,12 +1677,13 @@ class Facture extends CommonInvoice $this->multicurrency_total_tva = $obj->multicurrency_total_tva; $this->multicurrency_total_ttc = $obj->multicurrency_total_ttc; - if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) - { + if (($this->type == self::TYPE_SITUATION || ($this->type == self::TYPE_CREDIT_NOTE && $this->situation_cycle_ref > 0)) && $fetch_situation) { $this->fetchPreviousNextSituationInvoice(); } - if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; + if ($this->statut == self::STATUS_DRAFT) { + $this->brouillon = 1; + } // Retrieve all extrafield // fetch optionals attributes and labels @@ -1659,8 +1693,7 @@ class Facture extends CommonInvoice $this->lines = array(); $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->error(); return -3; } @@ -1708,12 +1741,10 @@ class Facture extends CommonInvoice dol_syslog(get_class($this).'::fetch_lines', LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new FactureLigne($this->db); @@ -1819,17 +1850,13 @@ class Facture extends CommonInvoice dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG); $result = $this->db->query($sql); - if ($result && $this->db->num_rows($result) > 0) - { - while ($objp = $this->db->fetch_object($result)) - { + if ($result && $this->db->num_rows($result) > 0) { + while ($objp = $this->db->fetch_object($result)) { $invoice = new Facture($this->db); - if ($invoice->fetch($objp->rowid) > 0) - { + if ($invoice->fetch($objp->rowid) > 0) { if ($objp->situation_counter < $this->situation_counter || ($objp->situation_counter == $this->situation_counter && $objp->rowid < $this->id) // This case appear when there are credit notes - ) - { + ) { $this->tab_previous_situation_invoice[] = $invoice; } else { $this->tab_next_situation_invoice[] = $invoice; @@ -1853,19 +1880,45 @@ class Facture extends CommonInvoice $error = 0; // Clean parameters - if (empty($this->type)) $this->type = self::TYPE_STANDARD; - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->ref_ext)) $this->ref_ext = trim($this->ref_ext); - if (isset($this->ref_client)) $this->ref_client = trim($this->ref_client); - if (isset($this->increment)) $this->increment = trim($this->increment); - if (isset($this->close_code)) $this->close_code = trim($this->close_code); - if (isset($this->close_note)) $this->close_note = trim($this->close_note); - if (isset($this->note) || isset($this->note_private)) $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated - if (isset($this->note) || isset($this->note_private)) $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note)); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); - if (isset($this->retained_warranty)) $this->retained_warranty = floatval($this->retained_warranty); + if (empty($this->type)) { + $this->type = self::TYPE_STANDARD; + } + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->ref_ext)) { + $this->ref_ext = trim($this->ref_ext); + } + if (isset($this->ref_client)) { + $this->ref_client = trim($this->ref_client); + } + if (isset($this->increment)) { + $this->increment = trim($this->increment); + } + if (isset($this->close_code)) { + $this->close_code = trim($this->close_code); + } + if (isset($this->close_note)) { + $this->close_note = trim($this->close_note); + } + if (isset($this->note) || isset($this->note_private)) { + $this->note = (isset($this->note) ? trim($this->note) : trim($this->note_private)); // deprecated + } + if (isset($this->note) || isset($this->note_private)) { + $this->note_private = (isset($this->note_private) ? trim($this->note_private) : trim($this->note)); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->model_pdf)) { + $this->model_pdf = trim($this->model_pdf); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } + if (isset($this->retained_warranty)) { + $this->retained_warranty = floatval($this->retained_warranty); + } // Check parameters @@ -1922,28 +1975,25 @@ class Facture extends CommonInvoice $error++; $this->errors[] = "Error ".$this->db->lasterror(); } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BILL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1976,10 +2026,8 @@ class Facture extends CommonInvoice $remise = new DiscountAbsolute($this->db); $result = $remise->fetch($idremise); - if ($result > 0) - { - if ($remise->fk_facture) // Protection against multiple submission - { + if ($result > 0) { + if ($remise->fk_facture) { // Protection against multiple submission $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; @@ -1999,8 +2047,7 @@ class Facture extends CommonInvoice $facligne->info_bits = 2; // Get buy/cost price of invoice that is source of discount - if ($remise->fk_facture_source > 0) - { + if ($remise->fk_facture_source > 0) { $srcinvoice = new Facture($this->db); $srcinvoice->fetch($remise->fk_facture_source); include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmargin.class.php'; // TODO Move this into commonobject @@ -2019,15 +2066,12 @@ class Facture extends CommonInvoice $facligne->multicurrency_total_ttc = -$remise->multicurrency_amount_ttc; $lineid = $facligne->insert(); - if ($lineid > 0) - { + if ($lineid > 0) { $result = $this->update_price(1); - if ($result > 0) - { + if ($result > 0) { // Create link between discount and invoice line $result = $remise->link_to_invoice($lineid, 0); - if ($result < 0) - { + if ($result < 0) { $this->error = $remise->error; $this->db->rollback(); return -4; @@ -2069,41 +2113,40 @@ class Facture extends CommonInvoice $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture'; - if (empty($ref_client)) + if (empty($ref_client)) { $sql .= ' SET ref_client = NULL'; - else $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\''; + } else { + $sql .= ' SET ref_client = \''.$this->db->escape($ref_client).'\''; + } $sql .= ' WHERE rowid = '.$this->id; dol_syslog(__METHOD__.' this->id='.$this->id.', ref_client='.$ref_client, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->ref_client = $ref_client; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('BILL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->ref_client = $ref_client; $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2132,39 +2175,41 @@ class Facture extends CommonInvoice // Test to avoid invoice deletion (allowed if draft) $result = $this->is_erasable(); - if ($result <= 0) return 0; + if ($result <= 0) { + return 0; + } $error = 0; $this->db->begin(); - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BILL_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } // Removed extrafields if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR); } } - if (!$error) - { + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // If invoice was converted into a discount not yet consumed, we remove discount $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'societe_remise_except'; $sql .= ' WHERE fk_facture_source = '.$rowid; @@ -2174,21 +2219,18 @@ class Facture extends CommonInvoice // If invoice has consumned discounts $this->fetch_lines(); $list_rowid_det = array(); - foreach ($this->lines as $key => $invoiceline) - { + foreach ($this->lines as $key => $invoiceline) { $list_rowid_det[] = $invoiceline->id; } // Consumned discounts are freed - if (count($list_rowid_det)) - { + if (count($list_rowid_det)) { $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except'; $sql .= ' SET fk_facture = NULL, fk_facture_line = NULL'; $sql .= ' WHERE fk_facture_line IN ('.join(',', $list_rowid_det).')'; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->error = $this->db->error()." sql=".$sql; $this->errors[] = $this->error; $this->db->rollback(); @@ -2197,21 +2239,21 @@ class Facture extends CommonInvoice } // If we decrease stock on invoice validation, we increase back if a warehouse id was provided - if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) - { + if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse != -1) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $num; $i++) { + if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We decrease stock for product - if ($this->type == self::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref)); - else $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceDeleteDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value + if ($this->type == self::TYPE_CREDIT_NOTE) { + $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceDeleteDolibarr", $this->ref)); + } else { + $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceDeleteDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value + } } } } @@ -2225,30 +2267,25 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact()) - { + if ($this->db->query($sqlef) && $this->db->query($sql) && $this->delete_linked_contact()) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture WHERE rowid = '.$rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive $this->deleteEcmFiles(); // On efface le repertoire de pdf provisoire $ref = dol_sanitizeFileName($this->ref); - if ($conf->facture->dir_output && !empty($this->ref)) - { + if ($conf->facture->dir_output && !empty($this->ref)) { $dir = $conf->facture->dir_output."/".$ref; $file = $conf->facture->dir_output."/".$ref."/".$ref.".pdf"; - if (file_exists($file)) // We must delete all files before deleting directory - { + if (file_exists($file)) { // We must delete all files before deleting directory $ret = dol_delete_preview($this); - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { + if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers $langs->load("errors"); $this->error = $langs->trans("ErrorFailToDeleteFile", $file); $this->errors[] = $this->error; @@ -2256,10 +2293,8 @@ class Facture extends CommonInvoice return 0; } } - if (file_exists($dir)) - { - if (!dol_delete_dir_recursive($dir)) // For remove dir and meta - { + if (file_exists($dir)) { + if (!dol_delete_dir_recursive($dir)) { // For remove dir and meta $langs->load("errors"); $this->error = $langs->trans("ErrorFailToDeleteDir", $dir); $this->errors[] = $this->error; @@ -2321,8 +2356,7 @@ class Facture extends CommonInvoice { $error = 0; - if ($this->paye != 1) - { + if ($this->paye != 1) { $this->db->begin(); $now = dol_now(); @@ -2331,27 +2365,33 @@ class Facture extends CommonInvoice $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET'; $sql .= ' fk_statut='.self::STATUS_CLOSED; - if (!$close_code) $sql .= ', paye=1'; - if ($close_code) $sql .= ", close_code='".$this->db->escape($close_code)."'"; - if ($close_note) $sql .= ", close_note='".$this->db->escape($close_note)."'"; + if (!$close_code) { + $sql .= ', paye=1'; + } + if ($close_code) { + $sql .= ", close_code='".$this->db->escape($close_code)."'"; + } + if ($close_note) { + $sql .= ", close_note='".$this->db->escape($close_note)."'"; + } $sql .= ', fk_user_closing = '.$user->id; $sql .= ", date_closing = '".$this->db->idate($now)."'"; $sql .= ' WHERE rowid = '.$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('BILL_PAYED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; $this->error = $this->db->lasterror(); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -2404,11 +2444,12 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::set_unpaid", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('BILL_UNPAYED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -2416,8 +2457,7 @@ class Facture extends CommonInvoice dol_print_error($this->db); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -2465,13 +2505,16 @@ class Facture extends CommonInvoice $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture SET'; $sql .= ' fk_statut='.self::STATUS_ABANDONED; - if ($close_code) $sql .= ", close_code='".$this->db->escape($close_code)."'"; - if ($close_note) $sql .= ", close_note='".$this->db->escape($close_note)."'"; + if ($close_code) { + $sql .= ", close_code='".$this->db->escape($close_code)."'"; + } + if ($close_note) { + $sql .= ", close_note='".$this->db->escape($close_note)."'"; + } $sql .= ' WHERE rowid = '.$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // On desaffecte de la facture les remises liees // car elles n'ont pas ete utilisees vu que la facture est abandonnee. $sql = 'UPDATE '.MAIN_DB_PREFIX.'societe_remise_except'; @@ -2479,12 +2522,10 @@ class Facture extends CommonInvoice $sql .= ' WHERE fk_facture = '.$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('BILL_CANCEL', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -2540,20 +2581,17 @@ class Facture extends CommonInvoice $this->fetch_lines(); // Check parameters - if (!$this->brouillon) - { + if (!$this->brouillon) { dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING); return 0; } - if (count($this->lines) <= 0) - { + if (count($this->lines) <= 0) { $langs->load("errors"); $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); return -1; } if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->facture->invoice_advance->validate))) { $this->error = 'Permission denied'; dol_syslog(get_class($this)."::validate ".$this->error.' MAIN_USE_ADVANCED_PERMS='.$conf->global->MAIN_USE_ADVANCED_PERMS, LOG_ERR); return -1; @@ -2562,11 +2600,9 @@ class Facture extends CommonInvoice $this->db->begin(); // Check parameters - if ($this->type == self::TYPE_REPLACEMENT) // if this is a replacement invoice - { + if ($this->type == self::TYPE_REPLACEMENT) { // if this is a replacement invoice // Check that source invoice is known - if ($this->fk_facture_source <= 0) - { + if ($this->fk_facture_source <= 0) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("InvoiceReplacement")); $this->db->rollback(); return -10; @@ -2575,8 +2611,7 @@ class Facture extends CommonInvoice // Load source invoice that has been replaced $facreplaced = new Facture($this->db); $result = $facreplaced->fetch($this->fk_facture_source); - if ($result <= 0) - { + if ($result <= 0) { $this->error = $langs->trans("ErrorBadInvoice"); $this->db->rollback(); return -11; @@ -2584,8 +2619,7 @@ class Facture extends CommonInvoice // Check that source invoice not already replaced by another one. $idreplacement = $facreplaced->getIdReplacingInvoice('validated'); - if ($idreplacement && $idreplacement != $this->id) - { + if ($idreplacement && $idreplacement != $this->id) { $facreplacement = new Facture($this->db); $facreplacement->fetch($idreplacement); $this->error = $langs->trans("ErrorInvoiceAlreadyReplaced", $facreplaced->ref, $facreplacement->ref); @@ -2594,8 +2628,7 @@ class Facture extends CommonInvoice } $result = $facreplaced->setCanceled($user, self::CLOSECODE_REPLACED, ''); - if ($result < 0) - { + if ($result < 0) { $this->error = $facreplaced->error; $this->db->rollback(); return -13; @@ -2603,13 +2636,10 @@ class Facture extends CommonInvoice } // Define new ref - if ($force_number) - { + if ($force_number) { $num = $force_number; - } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life - { - if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date - { + } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life + if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date $this->date = dol_now(); $this->date_lim_reglement = $this->calculate_date_lim_reglement(); } @@ -2619,15 +2649,13 @@ class Facture extends CommonInvoice } $this->newref = dol_sanitizeFileName($num); - if ($num) - { + if ($num) { $this->update_price(1); // Validate $sql = 'UPDATE '.MAIN_DB_PREFIX.'facture'; $sql .= " SET ref='".$num."', fk_statut = ".self::STATUS_VALIDATED.", fk_user_valid = ".($user->id > 0 ? $user->id : "null").", date_valid = '".$this->db->idate($now)."'"; - if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) // If option enabled, we force invoice date - { + if (!empty($conf->global->FAC_FORCE_DATE_VALIDATION)) { // If option enabled, we force invoice date $sql .= ", datef='".$this->db->idate($this->date)."'"; $sql .= ", date_lim_reglement='".$this->db->idate($this->date_lim_reglement)."'"; } @@ -2635,35 +2663,29 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; } // On verifie si la facture etait une provisoire - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref))) - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref))) { // La verif qu'une remise n'est pas utilisee 2 fois est faite au moment de l'insertion de ligne } - if (!$error) - { + if (!$error) { // Define third party as a customer $result = $this->thirdparty->set_as_client(); // Si active on decremente le produit principal et ses composants a la validation de facture - if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) - { + if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); // Loop on each line $cpt = count($this->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We decrease stock for product @@ -2706,13 +2728,15 @@ class Facture extends CommonInvoice } foreach ($batchList as $batch) { - if ($batch->qty <= 0) continue; // try to decrement only batches have positive quantity first + if ($batch->qty <= 0) { + continue; // try to decrement only batches have positive quantity first + } // enough quantity in this batch if ($batch->qty >= $product_qty_remain) { $product_batch_qty = $product_qty_remain; - } // not enough (take all in batch) - else { + } else { + // not enough (take all in batch) $product_batch_qty = $batch->qty; } $result = $mouvP->livraison($user, $productStatic->id, $idwarehouse, $product_batch_qty, $this->lines[$i]->subprice, $langs->trans('InvoiceValidatedInDolibarr', $num), '', '', '', $batch->batch); @@ -2724,7 +2748,9 @@ class Facture extends CommonInvoice $product_qty_remain -= $product_batch_qty; // all product quantity was decremented - if ($product_qty_remain <= 0) break; + if ($product_qty_remain <= 0) { + break; + } } if (!$error && $product_qty_remain > 0) { @@ -2762,43 +2788,41 @@ class Facture extends CommonInvoice } // Trigger calls - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BILL_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'facture/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'facture/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->facture->dir_output.'/'.$oldref; $dirdest = $conf->facture->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->facture->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -2810,17 +2834,14 @@ class Facture extends CommonInvoice } } - if (!$error && !$this->is_last_in_cycle()) - { - if (!$this->updatePriceNextInvoice($langs)) - { + if (!$error && !$this->is_last_in_cycle()) { + if (!$this->updatePriceNextInvoice($langs)) { $error++; } } // Set new ref and define current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->ref = $num; $this->statut = self::STATUS_VALIDATED; @@ -2828,8 +2849,7 @@ class Facture extends CommonInvoice $this->date_validation = $now; $i = 0; - if (!empty($conf->global->INVOICE_USE_SITUATION)) - { + if (!empty($conf->global->INVOICE_USE_SITUATION)) { $final = true; $nboflines = count($this->lines); while (($i < $nboflines) && $final) { @@ -2837,8 +2857,11 @@ class Facture extends CommonInvoice $i++; } - if (empty($final)) $this->situation_final = 0; - else $this->situation_final = 1; + if (empty($final)) { + $this->situation_final = 0; + } else { + $this->situation_final = 1; + } $this->setFinal($user); } @@ -2847,8 +2870,7 @@ class Facture extends CommonInvoice $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -2865,28 +2887,42 @@ class Facture extends CommonInvoice */ public function updatePriceNextInvoice(&$langs) { - foreach ($this->tab_next_situation_invoice as $next_invoice) - { + foreach ($this->tab_next_situation_invoice as $next_invoice) { $is_last = $next_invoice->is_last_in_cycle(); - if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) - { + if ($next_invoice->statut == self::STATUS_DRAFT && $is_last != 1) { $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref); return false; } $next_invoice->brouillon = 1; - foreach ($next_invoice->lines as $line) - { + foreach ($next_invoice->lines as $line) { $result = $next_invoice->updateline( - $line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, - $line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type, - $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent, + $line->id, + $line->desc, + $line->subprice, + $line->qty, + $line->remise_percent, + $line->date_start, + $line->date_end, + $line->tva_tx, + $line->localtax1_tx, + $line->localtax2_tx, + 'HT', + $line->info_bits, + $line->product_type, + $line->fk_parent_line, + 0, + $line->fk_fournprice, + $line->pa_ht, + $line->label, + $line->special_code, + $line->array_options, + $line->situation_percent, $line->fk_unit ); - if ($result < 0) - { + if ($result < 0) { $this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref); return false; } @@ -2912,8 +2948,7 @@ class Facture extends CommonInvoice $error = 0; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { dol_syslog(__METHOD__." already draft status", LOG_WARNING); return 0; } @@ -2927,43 +2962,39 @@ class Facture extends CommonInvoice $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if ($result) - { - if (!$error) - { + if ($result) { + if (!$error) { $this->oldcopy = clone $this; } // If we decrease stock on invoice validation, we increase back - if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) - { + if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $num = count($this->lines); - for ($i = 0; $i < $num; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $num; $i++) { + if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We decrease stock for product - if ($this->type == self::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); - else $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value + if ($this->type == self::TYPE_CREDIT_NOTE) { + $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); + } else { + $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, 0, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); // we use 0 for price, to not change the weighted average value + } } } } - if ($error == 0) - { + if ($error == 0) { $old_statut = $this->statut; $this->brouillon = 1; $this->statut = self::STATUS_DRAFT; // Call trigger $result = $this->call_trigger('BILL_UNVALIDATE', $user); - if ($result < 0) - { + if ($result < 0) { $error++; $this->statut = $old_statut; $this->brouillon = 0; @@ -2974,8 +3005,7 @@ class Facture extends CommonInvoice return -1; } - if ($error == 0) - { + if ($error == 0) { $this->db->commit(); return 1; } else { @@ -3071,23 +3101,46 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::addline id=$this->id,desc=$desc,pu_ht=$pu_ht,qty=$qty,txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, fk_product=$fk_product,remise_percent=$remise_percent,date_start=$date_start,date_end=$date_end,ventil=$ventil,info_bits=$info_bits,fk_remise_except=$fk_remise_except,price_base_type=$price_base_type,pu_ttc=$pu_ttc,type=$type, fk_unit=$fk_unit", LOG_DEBUG); - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (empty($remise_percent)) $remise_percent = 0; - if (empty($qty)) $qty = 0; - if (empty($info_bits)) $info_bits = 0; - if (empty($rang)) $rang = 0; - if (empty($ventil)) $ventil = 0; - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; - if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; - if (empty($fk_prev_id)) $fk_prev_id = 'null'; - if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100; - if (empty($ref_ext)) $ref_ext = ''; + if (empty($remise_percent)) { + $remise_percent = 0; + } + if (empty($qty)) { + $qty = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($rang)) { + $rang = 0; + } + if (empty($ventil)) { + $ventil = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } + if (empty($fk_parent_line) || $fk_parent_line < 0) { + $fk_parent_line = 0; + } + if (empty($fk_prev_id)) { + $fk_prev_id = 'null'; + } + if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') { + $situation_percent = 100; + } + if (empty($ref_ext)) { + $ref_ext = ''; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -3101,15 +3154,16 @@ class Facture extends CommonInvoice $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; } // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); @@ -3120,8 +3174,7 @@ class Facture extends CommonInvoice $this->db->begin(); $product_type = $type; - if (!empty($fk_product)) - { + if (!empty($fk_product)) { $product = new Product($this->db); $result = $product->fetch($fk_product); $product_type = $product->type; @@ -3139,8 +3192,7 @@ class Facture extends CommonInvoice // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -3167,8 +3219,7 @@ class Facture extends CommonInvoice // Rank to use $ranktouse = $rang; - if ($ranktouse == -1) - { + if ($ranktouse == -1) { $rangmax = $this->line_max($fk_parent_line); $ranktouse = $rangmax + 1; } @@ -3234,16 +3285,16 @@ class Facture extends CommonInvoice } $result = $this->line->insert(); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour informations denormalisees au niveau de la facture meme $result = $this->update_price(1, 'auto', 0, $mysoc); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode. - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->line->id; } else { @@ -3307,13 +3358,12 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::updateline rowid=$rowid, desc=$desc, pu=$pu, qty=$qty, remise_percent=$remise_percent, date_start=$date_start, date_end=$date_end, txtva=$txtva, txlocaltax1=$txlocaltax1, txlocaltax2=$txlocaltax2, price_base_type=$price_base_type, info_bits=$info_bits, type=$type, fk_parent_line=$fk_parent_line pa_ht=$pa_ht, special_code=$special_code, fk_unit=$fk_unit, pu_ht_devise=$pu_ht_devise", LOG_DEBUG); - if ($this->brouillon) - { - if (!$this->is_last_in_cycle() && empty($this->error)) - { - if (!$this->checkProgressLine($rowid, $situation_percent)) - { - if (!$this->error) $this->error = $langs->trans('invoiceLineProgressError'); + if ($this->brouillon) { + if (!$this->is_last_in_cycle() && empty($this->error)) { + if (!$this->checkProgressLine($rowid, $situation_percent)) { + if (!$this->error) { + $this->error = $langs->trans('invoiceLineProgressError'); + } return -3; } } @@ -3327,11 +3377,21 @@ class Facture extends CommonInvoice $this->db->begin(); // Clean parameters - if (empty($qty)) $qty = 0; - if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line = 0; - if (empty($special_code) || $special_code == 3) $special_code = 0; - if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100; - if (empty($ref_ext)) $ref_ext = ''; + if (empty($qty)) { + $qty = 0; + } + if (empty($fk_parent_line) || $fk_parent_line < 0) { + $fk_parent_line = 0; + } + if (empty($special_code) || $special_code == 3) { + $special_code = 0; + } + if (!isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') { + $situation_percent = 100; + } + if (empty($ref_ext)) { + $ref_ext = ''; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -3345,7 +3405,9 @@ class Facture extends CommonInvoice $txlocaltax2 = price2num($txlocaltax2); // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } // Calculate total with, without tax and tax from qty, pu, remise_percent and txtva // TRES IMPORTANT: C'est au moment de l'insertion ligne qu'on doit stocker @@ -3356,8 +3418,7 @@ class Facture extends CommonInvoice // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -3382,8 +3443,7 @@ class Facture extends CommonInvoice // Old properties: $price, $remise (deprecated) $price = $pu; $remise = 0; - if ($remise_percent > 0) - { + if ($remise_percent > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = ($pu - $remise); } @@ -3394,8 +3454,7 @@ class Facture extends CommonInvoice $line->fetch($rowid); $line->fetch_optionals(); - if (!empty($line->fk_product)) - { + if (!empty($line->fk_product)) { $product = new Product($this->db); $result = $product->fetch($line->fk_product); $product_type = $product->type; @@ -3415,8 +3474,7 @@ class Facture extends CommonInvoice $this->line->context = $this->context; // Reorder if fk_parent_line change - if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) - { + if (!empty($fk_parent_line) && !empty($staticline->fk_parent_line) && $fk_parent_line != $staticline->fk_parent_line) { $rangmax = $this->line_max($fk_parent_line); $this->line->rang = $rangmax + 1; } @@ -3469,10 +3527,11 @@ class Facture extends CommonInvoice } $result = $this->line->update($user, $notrigger); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour info denormalisees au niveau facture $this->update_price(1); @@ -3504,16 +3563,18 @@ class Facture extends CommonInvoice AND f.fk_statut <> 0'; $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->error = $this->db->error(); return false; } $obj = $this->db->fetch_object($result); - if ($obj === null) return true; - else return $situation_percent < $obj->situation_percent; + if ($obj === null) { + return true; + } else { + return $situation_percent < $obj->situation_percent; + } } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -3530,15 +3591,16 @@ class Facture extends CommonInvoice global $mysoc, $user; // Progress should never be changed for discount lines - if (($line->info_bits & 2) == 2) - { + if (($line->info_bits & 2) == 2) { return; } include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Cap percentages to 100 - if ($percent > 100) $percent = 100; + if ($percent > 100) { + $percent = 100; + } $line->situation_percent = $percent; $tabprice = calcul_price_total($line->qty, $line->subprice, $line->remise_percent, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 0, 'HT', 0, $line->product_type, $mysoc, '', $percent); $line->total_ht = $tabprice[0]; @@ -3565,8 +3627,7 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::deleteline rowid=".$rowid, LOG_DEBUG); - if (!$this->brouillon) - { + if (!$this->brouillon) { $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus'; return -1; } @@ -3580,8 +3641,7 @@ class Facture extends CommonInvoice dol_syslog(get_class($this)."::deleteline", LOG_DEBUG); $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->error = $this->db->error(); $this->db->rollback(); return -1; @@ -3593,14 +3653,14 @@ class Facture extends CommonInvoice // For triggers $result = $line->fetch($rowid); - if (!($result > 0)) dol_print_error($this->db, $line->error, $line->errors); + if (!($result > 0)) { + dol_print_error($this->db, $line->error, $line->errors); + } - if ($line->delete($user) > 0) - { + if ($line->delete($user) > 0) { $result = $this->update_price(1); - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return 1; } else { @@ -3644,10 +3704,11 @@ class Facture extends CommonInvoice public function setDiscount($user, $remise, $notrigger = 0) { // Clean parameters - if (empty($remise)) $remise = 0; + if (empty($remise)) { + $remise = 0; + } - if ($user->rights->facture->creer) - { + if ($user->rights->facture->creer) { $remise = price2num($remise); $error = 0; @@ -3661,30 +3722,28 @@ class Facture extends CommonInvoice dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('BILL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->remise_percent = $remise; $this->update_price(1); $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -3707,10 +3766,11 @@ class Facture extends CommonInvoice public function set_remise_absolue($user, $remise, $notrigger = 0) { // phpcs:enable - if (empty($remise)) $remise = 0; + if (empty($remise)) { + $remise = 0; + } - if ($user->rights->facture->creer) - { + if ($user->rights->facture->creer) { $error = 0; $this->db->begin(); @@ -3724,34 +3784,31 @@ class Facture extends CommonInvoice dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->remise_absolue = $remise; $this->update_price(1); } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('BILL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -3781,7 +3838,9 @@ class Facture extends CommonInvoice $addonConstName = 'TAKEPOS_REF_ADDON'; // Clean parameters (if not defined or using deprecated value) - if (empty($conf->global->TAKEPOS_REF_ADDON)) $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple'; + if (empty($conf->global->TAKEPOS_REF_ADDON)) { + $conf->global->TAKEPOS_REF_ADDON = 'mod_takepos_ref_simple'; + } $addon = $conf->global->TAKEPOS_REF_ADDON; } else { @@ -3792,9 +3851,13 @@ class Facture extends CommonInvoice $addonConstName = 'FACTURE_ADDON'; // Clean parameters (if not defined or using deprecated value) - if (empty($conf->global->FACTURE_ADDON)) $conf->global->FACTURE_ADDON = 'mod_facture_terre'; - elseif ($conf->global->FACTURE_ADDON == 'terre') $conf->global->FACTURE_ADDON = 'mod_facture_terre'; - elseif ($conf->global->FACTURE_ADDON == 'mercure') $conf->global->FACTURE_ADDON = 'mod_facture_mercure'; + if (empty($conf->global->FACTURE_ADDON)) { + $conf->global->FACTURE_ADDON = 'mod_facture_terre'; + } elseif ($conf->global->FACTURE_ADDON == 'terre') { + $conf->global->FACTURE_ADDON = 'mod_facture_terre'; + } elseif ($conf->global->FACTURE_ADDON == 'mercure') { + $conf->global->FACTURE_ADDON = 'mod_facture_mercure'; + } $addon = $conf->global->FACTURE_ADDON; } @@ -3876,26 +3939,21 @@ class Facture extends CommonInvoice $sql .= ' WHERE c.rowid = '.$id; $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_closing) - { + if ($obj->fk_user_closing) { $cluser = new User($this->db); $cluser->fetch($obj->fk_user_closing); $this->user_closing = $cluser; @@ -3936,37 +3994,41 @@ class Facture extends CommonInvoice $sql = "SELECT s.rowid, s.nom as name, s.client,"; $sql .= " f.rowid as fid, f.ref as ref, f.datef as df"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user"; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture as f"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.entity IN (".getEntity('invoice').")"; $sql .= " AND f.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) //restriction - { + if (!$user->rights->societe->client->voir && !$socid) { //restriction $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($socid) $sql .= " AND s.rowid = ".$socid; - if ($draft) $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT; - if (is_object($excluser)) $sql .= " AND f.fk_user_author <> ".$excluser->id; + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } + if ($draft) { + $sql .= " AND f.fk_statut = ".self::STATUS_DRAFT; + } + if (is_object($excluser)) { + $sql .= " AND f.fk_user_author <> ".$excluser->id; + } $sql .= $this->db->order($sortfield, $sortorder); $sql .= $this->db->plimit($limit, $offset); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $numc = $this->db->num_rows($result); - if ($numc) - { + if ($numc) { $i = 0; - while ($i < $numc) - { + while ($i < $numc) { $obj = $this->db->fetch_object($result); - if ($shortlist == 1) - { + if ($shortlist == 1) { $ga[$obj->fid] = $obj->ref; - } elseif ($shortlist == 2) - { + } elseif ($shortlist == 2) { $ga[$obj->fid] = $obj->ref.' ('.$obj->name.')'; } else { $ga[$i]['id'] = $obj->fid; @@ -4010,15 +4072,15 @@ class Facture extends CommonInvoice $sql .= " AND f.paye = 0"; // Pas classee payee completement $sql .= " AND pf.fk_paiement IS NULL"; // Aucun paiement deja fait $sql .= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de remplacement - if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; + if ($socid > 0) { + $sql .= " AND f.fk_soc = ".$socid; + } $sql .= " ORDER BY f.ref"; dol_syslog(get_class($this)."::list_replacable_invoices", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $return[$obj->rowid] = array('id' => $obj->rowid, 'ref' => $obj->ref, 'status' => $obj->fk_statut); @@ -4075,20 +4137,23 @@ class Facture extends CommonInvoice $sql .= " AND f.type != ".self::TYPE_SITUATION; // Type non 5 si facture non avoir } - if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; + if ($socid > 0) { + $sql .= " AND f.fk_soc = ".$socid; + } $sql .= " ORDER BY f.ref"; dol_syslog(get_class($this)."::list_qualified_avoir_invoices", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $qualified = 0; - if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified = 1; - if ($obj->fk_statut == self::STATUS_CLOSED) $qualified = 1; - if ($qualified) - { + if ($obj->fk_statut == self::STATUS_VALIDATED) { + $qualified = 1; + } + if ($obj->fk_statut == self::STATUS_CLOSED) { + $qualified = 1; + } + if ($qualified) { //$ref=$obj->ref; $paymentornot = ($obj->fk_paiement ? 1 : 0); $return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot); @@ -4119,8 +4184,7 @@ class Facture extends CommonInvoice $sql = "SELECT f.rowid, f.date_lim_reglement as datefin,f.fk_statut, f.total"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON f.fk_soc = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = " AND"; @@ -4128,11 +4192,12 @@ class Facture extends CommonInvoice $sql .= $clause." f.paye=0"; $sql .= " AND f.entity IN (".getEntity('invoice').")"; $sql .= " AND f.fk_statut = ".self::STATUS_VALIDATED; - if ($user->socid) $sql .= " AND f.fk_soc = ".$user->socid; + if ($user->socid) { + $sql .= " AND f.fk_soc = ".$user->socid; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $langs->load("bills"); $now = dol_now(); @@ -4145,8 +4210,7 @@ class Facture extends CommonInvoice $generic_facture = new Facture($this->db); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $generic_facture->date_lim_reglement = $this->db->jdate($obj->datefin); $generic_facture->statut = $obj->fk_statut; @@ -4216,12 +4280,10 @@ class Facture extends CommonInvoice $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -4258,13 +4320,11 @@ class Facture extends CommonInvoice $this->fk_incoterms = 0; $this->location_incoterms = ''; - if (empty($option) || $option != 'nolines') - { + if (empty($option) || $option != 'nolines') { // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new FactureLigne($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->qty = 1; @@ -4273,8 +4333,7 @@ class Facture extends CommonInvoice $line->localtax1_tx = 0; $line->localtax2_tx = 0; $line->remise_percent = 0; - if ($xnbp == 1) // Qty is negative (product line) - { + if ($xnbp == 1) { // Qty is negative (product line) $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; $line->qty = -1; @@ -4284,8 +4343,7 @@ class Facture extends CommonInvoice $line->multicurrency_total_ht = -200; $line->multicurrency_total_ttc = -239.2; $line->multicurrency_total_tva = -39.2; - } elseif ($xnbp == 2) // UP is negative (free line) - { + } elseif ($xnbp == 2) { // UP is negative (free line) $line->subprice = -100; $line->total_ht = -100; $line->total_ttc = -119.6; @@ -4294,8 +4352,7 @@ class Facture extends CommonInvoice $line->multicurrency_total_ht = -200; $line->multicurrency_total_ttc = -239.2; $line->multicurrency_total_tva = -39.2; - } elseif ($xnbp == 3) // Discount is 50% (product line) - { + } elseif ($xnbp == 3) { // Discount is 50% (product line) $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; $line->total_ht = 50; @@ -4374,8 +4431,7 @@ class Facture extends CommonInvoice $sql = "SELECT count(f.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -4383,10 +4439,8 @@ class Facture extends CommonInvoice $sql .= " ".$clause." f.entity IN (".getEntity('invoice').")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["invoices"] = $obj->nb; } $this->db->free($resql); @@ -4425,8 +4479,7 @@ class Facture extends CommonInvoice $outputlangs->loadLangs(array("bills", "products")); - if (!dol_strlen($modele)) - { + if (!dol_strlen($modele)) { $modele = 'crabe'; $thisTypeConfName = 'FACTURE_ADDON_PDF_'.$this->type; @@ -4457,8 +4510,7 @@ class Facture extends CommonInvoice $sql .= " WHERE f.entity IN (".getEntity('invoice', 0).")"; $resql = $this->db->query($sql); if ($resql) { - if ($resql->num_rows > 0) - { + if ($resql->num_rows > 0) { $res = $this->db->fetch_array($resql); $ref = $res['max(situation_cycle_ref)']; $ref++; @@ -4536,27 +4588,25 @@ class Facture extends CommonInvoice dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('BILL_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -4626,21 +4676,19 @@ class Facture extends CommonInvoice $now = dol_now(); // Paid invoices have status STATUS_CLOSED - if ($this->statut != Facture::STATUS_VALIDATED) return false; + if ($this->statut != Facture::STATUS_VALIDATED) { + return false; + } $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay); - if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) - { + if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) { $totalpaye = $this->getSommePaiement(); $totalpaye = floatval($totalpaye); $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount(); - if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) - { - if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) - { + if ($totalpaye >= 0 && $RetainedWarrantyAmount >= 0) { + if (($totalpaye < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) { $hasDelay = 1; - } elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) - { + } elseif ($totalpaye < $this->total_ttc && $this->retained_warranty_date_limit < ($now - $conf->facture->client->warning_delay)) { $hasDelay = 1; } else { $hasDelay = 0; @@ -4703,8 +4751,7 @@ class Facture extends CommonInvoice $retainedWarrantyAmount = 0; // Billed - retained warranty - if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) - { + if ($this->type == Facture::TYPE_SITUATION && !empty($conf->global->INVOICE_RETAINED_WARRANTY_LIMITED_TO_FINAL_SITUATION)) { $displayWarranty = true; // Check if this situation invoice is 100% for real if (!empty($this->lines)) { @@ -4716,8 +4763,7 @@ class Facture extends CommonInvoice } } - if ($displayWarranty && !empty($this->situation_final)) - { + if ($displayWarranty && !empty($this->situation_final)) { $this->fetchPreviousNextSituationInvoice(); $TPreviousIncoice = $this->tab_previous_situation_invoice; @@ -4756,15 +4802,13 @@ class Facture extends CommonInvoice public function setRetainedWarranty($value) { dol_syslog(get_class($this).'::setRetainedWarranty('.$value.')'); - if ($this->statut >= 0) - { + if ($this->statut >= 0) { $fieldname = 'retained_warranty'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.floatval($value); $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->retained_warranty = floatval($value); return 1; } else { @@ -4795,15 +4839,13 @@ class Facture extends CommonInvoice dol_syslog(get_class($this).'::setRetainedWarrantyDateLimit('.$timestamp.')'); - if ($this->statut >= 0) - { + if ($this->statut >= 0) { $fieldname = 'retained_warranty_date_limit'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET '.$fieldname.' = '.(strval($timestamp) != '' ? '\''.$this->db->idate($timestamp).'\'' : 'null'); $sql .= ' WHERE rowid='.$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->retained_warranty_date_limit = $timestamp; return 1; } else { @@ -4917,8 +4959,7 @@ class FactureLigne extends CommonInvoiceLine $sql .= ' WHERE fd.rowid = '.$rowid; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); $this->rowid = $objp->rowid; @@ -5002,34 +5043,74 @@ class FactureLigne extends CommonInvoiceLine // Clean parameters $this->desc = trim($this->desc); - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = 0; - if (empty($this->localtax2_type)) $this->localtax2_type = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->rang)) $this->rang = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->subprice)) $this->subprice = 0; - if (empty($this->ref_ext)) $this->ref_ext = ''; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (empty($this->fk_prev_id)) $this->fk_prev_id = 0; - if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = 0; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->rang)) { + $this->rang = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->subprice)) { + $this->subprice = 0; + } + if (empty($this->ref_ext)) { + $this->ref_ext = ''; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (empty($this->fk_prev_id)) { + $this->fk_prev_id = 0; + } + if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') { + $this->situation_percent = 100; + } - if (empty($this->pa_ht)) $this->pa_ht = 0; - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } + if (empty($this->multicurrency_subprice)) { + $this->multicurrency_subprice = 0; + } + if (empty($this->multicurrency_total_ht)) { + $this->multicurrency_total_ht = 0; + } + if (empty($this->multicurrency_total_tva)) { + $this->multicurrency_total_tva = 0; + } + if (empty($this->multicurrency_total_ttc)) { + $this->multicurrency_total_ttc = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0 && $pa_ht_isemptystring) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0 && $pa_ht_isemptystring) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -5037,17 +5118,14 @@ class FactureLigne extends CommonInvoiceLine } // Check parameters - if ($this->product_type < 0) - { + if ($this->product_type < 0) { $this->error = 'ErrorProductTypeMustBe0orMore'; return -1; } - if (!empty($this->fk_product)) - { + if (!empty($this->fk_product)) { // Check product exists $result = Product::isExistingObject('product', $this->fk_product); - if ($result <= 0) - { + if ($result <= 0) { $this->error = 'ErrorProductIdDoesNotExists'; dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); return -1; @@ -5113,36 +5191,28 @@ class FactureLigne extends CommonInvoiceLine dol_syslog(get_class($this)."::insert", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facturedet'); $this->rowid = $this->id; // For backward compatibility - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } // Si fk_remise_except defini, on lie la remise a la facture // ce qui la flague comme "consommee". - if ($this->fk_remise_except) - { + if ($this->fk_remise_except) { $discount = new DiscountAbsolute($this->db); $result = $discount->fetch($this->fk_remise_except); - if ($result >= 0) - { + if ($result >= 0) { // Check if discount was found - if ($result > 0) - { + if ($result > 0) { // Check if discount not already affected to another invoice - if ($discount->fk_facture_line > 0) - { - if (empty($noerrorifdiscountalreadylinked)) - { + if ($discount->fk_facture_line > 0) { + if (empty($noerrorifdiscountalreadylinked)) { $this->error = $langs->trans("ErrorDiscountAlreadyUsed", $discount->id); dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); $this->db->rollback(); @@ -5150,8 +5220,7 @@ class FactureLigne extends CommonInvoiceLine } } else { $result = $discount->link_to_invoice($this->rowid, 0); - if ($result < 0) - { + if ($result < 0) { $this->error = $discount->error; dol_syslog(get_class($this)."::insert Error ".$this->error, LOG_ERR); $this->db->rollback(); @@ -5172,12 +5241,10 @@ class FactureLigne extends CommonInvoiceLine } } - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINEBILL_INSERT', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -2; } @@ -5210,35 +5277,73 @@ class FactureLigne extends CommonInvoiceLine // Clean parameters $this->desc = trim($this->desc); - if (empty($this->ref_ext)) $this->ref_ext = ''; - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = 0; - if (empty($this->localtax2_type)) $this->localtax2_type = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->product_type)) $this->product_type = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100; - if (empty($this->pa_ht)) $this->pa_ht = 0; + if (empty($this->ref_ext)) { + $this->ref_ext = ''; + } + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = 0; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->product_type)) { + $this->product_type = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') { + $this->situation_percent = 100; + } + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; + if (empty($this->multicurrency_subprice)) { + $this->multicurrency_subprice = 0; + } + if (empty($this->multicurrency_total_ht)) { + $this->multicurrency_total_ht = 0; + } + if (empty($this->multicurrency_total_tva)) { + $this->multicurrency_total_tva = 0; + } + if (empty($this->multicurrency_total_ttc)) { + $this->multicurrency_total_ttc = 0; + } // Check parameters - if ($this->product_type < 0) return -1; + if ($this->product_type < 0) { + return -1; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0 && $pa_ht_isemptystring) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0 && $pa_ht_isemptystring) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -5254,8 +5359,11 @@ class FactureLigne extends CommonInvoiceLine $sql .= ", label=".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null"); $sql .= ", subprice=".price2num($this->subprice).""; $sql .= ", remise_percent=".price2num($this->remise_percent).""; - if ($this->fk_remise_except) $sql .= ", fk_remise_except=".$this->fk_remise_except; - else $sql .= ", fk_remise_except=null"; + if ($this->fk_remise_except) { + $sql .= ", fk_remise_except=".$this->fk_remise_except; + } else { + $sql .= ", fk_remise_except=null"; + } $sql .= ", vat_src_code = '".(empty($this->vat_src_code) ? '' : $this->db->escape($this->vat_src_code))."'"; $sql .= ", tva_tx=".price2num($this->tva_tx).""; $sql .= ", localtax1_tx=".price2num($this->localtax1_tx).""; @@ -5268,8 +5376,7 @@ class FactureLigne extends CommonInvoiceLine $sql .= ", product_type=".$this->product_type; $sql .= ", info_bits='".$this->db->escape($this->info_bits)."'"; $sql .= ", special_code='".$this->db->escape($this->special_code)."'"; - if (empty($this->skip_update_total)) - { + if (empty($this->skip_update_total)) { $sql .= ", total_ht=".price2num($this->total_ht); $sql .= ", total_tva=".price2num($this->total_tva); $sql .= ", total_ttc=".price2num($this->total_ttc); @@ -5279,7 +5386,9 @@ class FactureLigne extends CommonInvoiceLine $sql .= ", fk_product_fournisseur_price=".(!empty($this->fk_fournprice) ? "'".$this->db->escape($this->fk_fournprice)."'" : "null"); $sql .= ", buy_price_ht='".price2num($this->pa_ht)."'"; $sql .= ", fk_parent_line=".($this->fk_parent_line > 0 ? $this->fk_parent_line : "null"); - if (!empty($this->rang)) $sql .= ", rang=".$this->rang; + if (!empty($this->rang)) { + $sql .= ", rang=".$this->rang; + } $sql .= ", situation_percent=".$this->situation_percent; $sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit); $sql .= ", fk_user_modif =".$user->id; @@ -5294,24 +5403,19 @@ class FactureLigne extends CommonInvoiceLine dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { + if ($resql) { + if (!$error) { $this->id = $this->rowid; $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEBILL_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -2; } @@ -5340,8 +5444,7 @@ class FactureLigne extends CommonInvoiceLine // Call trigger $result = $this->call_trigger('LINEBILL_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -5349,16 +5452,14 @@ class FactureLigne extends CommonInvoiceLine // extrafields $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } $sql = "DELETE FROM ".MAIN_DB_PREFIX."facturedet WHERE rowid = ".$this->rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->db->commit(); return 1; } else { @@ -5382,8 +5483,12 @@ class FactureLigne extends CommonInvoiceLine dol_syslog(get_class($this)."::update_total", LOG_DEBUG); // Clean parameters - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } // Mise a jour ligne en base $sql = "UPDATE ".MAIN_DB_PREFIX."facturedet SET"; @@ -5397,8 +5502,7 @@ class FactureLigne extends CommonInvoiceLine dol_syslog(get_class($this)."::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -5429,7 +5533,9 @@ class FactureLigne extends CommonInvoiceLine $invoicecache[$invoiceid] = new Facture($this->db); $invoicecache[$invoiceid]->fetch($invoiceid); } - if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) return 0; + if ($invoicecache[$invoiceid]->type != Facture::TYPE_SITUATION) { + return 0; + } $sql = 'SELECT situation_percent FROM '.MAIN_DB_PREFIX.'facturedet WHERE rowid='.$this->fk_prev_id; $resql = $this->db->query($sql); diff --git a/htdocs/compta/facture/class/facturestats.class.php b/htdocs/compta/facture/class/facturestats.class.php index e6c4a5a9c22..47644e4b13e 100644 --- a/htdocs/compta/facture/class/facturestats.class.php +++ b/htdocs/compta/facture/class/facturestats.class.php @@ -67,16 +67,14 @@ class FactureStats extends Stats $this->cachefilesuffix = $mode; $this->join = ''; - if ($mode == 'customer') - { + if ($mode == 'customer') { $object = new Facture($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as f"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; $this->field = 'total'; $this->field_line = 'total_ht'; } - if ($mode == 'supplier') - { + if ($mode == 'supplier') { $object = new FactureFournisseur($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as f"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; @@ -87,24 +85,30 @@ class FactureStats extends Stats $this->where = " f.fk_statut >= 0"; $this->where .= " AND f.entity IN (".getEntity('invoice').")"; - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($mode == 'customer') $this->where .= " AND (f.fk_statut <> 3 OR f.close_code <> 'replaced')"; // Exclude replaced invoices as they are duplicated (we count closed invoices for other reasons) - if ($this->socid) - { + if (!$user->rights->societe->client->voir && !$this->socid) { + $this->where .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($mode == 'customer') { + $this->where .= " AND (f.fk_statut <> 3 OR f.close_code <> 'replaced')"; // Exclude replaced invoices as they are duplicated (we count closed invoices for other reasons) + } + if ($this->socid) { $this->where .= " AND f.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where .= ' AND f.fk_user_author = '.$this->userid; - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $this->where .= " AND f.type IN (0,1,2,5)"; - else $this->where .= " AND f.type IN (0,1,2,3,5)"; + if ($this->userid > 0) { + $this->where .= ' AND f.fk_user_author = '.$this->userid; + } + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $this->where .= " AND f.type IN (0,1,2,5)"; + } else { + $this->where .= " AND f.type IN (0,1,2,3,5)"; + } - if ($typentid) - { + if ($typentid) { $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe as s ON s.rowid = f.fk_soc'; $this->where .= ' AND s.fk_typent = '.$typentid; } - if ($categid) - { + if ($categid) { $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_societe as cs ON cs.fk_soc = f.fk_soc'; $this->join .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie as c ON c.rowid = cs.fk_categorie'; $this->where .= ' AND c.rowid = '.$categid; @@ -125,7 +129,9 @@ class FactureStats extends Stats $sql = "SELECT date_format(f.datef,'%m') as dm, COUNT(*) as nb"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; @@ -149,7 +155,9 @@ class FactureStats extends Stats $sql = "SELECT date_format(f.datef,'%Y') as dm, COUNT(*), SUM(c.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " GROUP BY dm"; @@ -172,7 +180,9 @@ class FactureStats extends Stats $sql = "SELECT date_format(datef,'%m') as dm, SUM(f.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; @@ -196,7 +206,9 @@ class FactureStats extends Stats $sql = "SELECT date_format(datef,'%m') as dm, AVG(f.".$this->field.")"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE f.datef BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; @@ -217,7 +229,9 @@ class FactureStats extends Stats $sql = "SELECT date_format(datef,'%Y') as year, COUNT(*) as nb, SUM(f.".$this->field.") as total, AVG(f.".$this->field.") as avg"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " GROUP BY year"; @@ -239,7 +253,9 @@ class FactureStats extends Stats $sql = "SELECT product.ref, COUNT(product.ref) as nb, SUM(tl.".$this->field_line.") as total, AVG(tl.".$this->field_line.") as avg"; $sql .= " FROM ".$this->from.", ".$this->from_line.", ".MAIN_DB_PREFIX."product as product"; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= $this->join; $sql .= " WHERE ".$this->where; $sql .= " AND f.rowid = tl.fk_facture AND tl.fk_product = product.rowid"; diff --git a/htdocs/compta/facture/class/paymentterm.class.php b/htdocs/compta/facture/class/paymentterm.class.php index 97297582081..4795a9b2062 100644 --- a/htdocs/compta/facture/class/paymentterm.class.php +++ b/htdocs/compta/facture/class/paymentterm.class.php @@ -88,14 +88,30 @@ class PaymentTerm // extends CommonObject // Clean parameters - if (isset($this->code)) $this->code = trim($this->code); - if (isset($this->sortorder)) $this->sortorder = trim($this->sortorder); - if (isset($this->active)) $this->active = trim($this->active); - if (isset($this->libelle)) $this->libelle = trim($this->libelle); - if (isset($this->libelle_facture)) $this->libelle_facture = trim($this->libelle_facture); - if (isset($this->type_cdr)) $this->type_cdr = trim($this->type_cdr); - if (isset($this->nbjour)) $this->nbjour = trim($this->nbjour); - if (isset($this->decalage)) $this->decalage = trim($this->decalage); + if (isset($this->code)) { + $this->code = trim($this->code); + } + if (isset($this->sortorder)) { + $this->sortorder = trim($this->sortorder); + } + if (isset($this->active)) { + $this->active = trim($this->active); + } + if (isset($this->libelle)) { + $this->libelle = trim($this->libelle); + } + if (isset($this->libelle_facture)) { + $this->libelle_facture = trim($this->libelle_facture); + } + if (isset($this->type_cdr)) { + $this->type_cdr = trim($this->type_cdr); + } + if (isset($this->nbjour)) { + $this->nbjour = trim($this->nbjour); + } + if (isset($this->decalage)) { + $this->decalage = trim($this->decalage); + } // Check parameters @@ -126,20 +142,19 @@ class PaymentTerm // extends CommonObject $this->db->begin(); - dol_syslog(get_class($this)."::create", LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_payment_term"); } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -180,10 +195,8 @@ class PaymentTerm // extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -201,7 +214,7 @@ class PaymentTerm // extends CommonObject return 1; } else { - $this->error = "Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -226,12 +239,12 @@ class PaymentTerm // extends CommonObject dol_syslog(get_class($this)."::getDefaultId", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); - if ($obj) $ret = $obj->rowid; + if ($obj) { + $ret = $obj->rowid; + } } $this->db->free($resql); return $ret; @@ -257,14 +270,30 @@ class PaymentTerm // extends CommonObject // Clean parameters - if (isset($this->code)) $this->code = trim($this->code); - if (isset($this->sortorder)) $this->sortorder = trim($this->sortorder); - if (isset($this->active)) $this->active = trim($this->active); - if (isset($this->libelle)) $this->libelle = trim($this->libelle); - if (isset($this->libelle_facture)) $this->libelle_facture = trim($this->libelle_facture); - if (isset($this->type_cdr)) $this->type_cdr = trim($this->type_cdr); - if (isset($this->nbjour)) $this->nbjour = trim($this->nbjour); - if (isset($this->decalage)) $this->decalage = trim($this->decalage); + if (isset($this->code)) { + $this->code = trim($this->code); + } + if (isset($this->sortorder)) { + $this->sortorder = trim($this->sortorder); + } + if (isset($this->active)) { + $this->active = trim($this->active); + } + if (isset($this->libelle)) { + $this->libelle = trim($this->libelle); + } + if (isset($this->libelle_facture)) { + $this->libelle_facture = trim($this->libelle_facture); + } + if (isset($this->type_cdr)) { + $this->type_cdr = trim($this->type_cdr); + } + if (isset($this->nbjour)) { + $this->nbjour = trim($this->nbjour); + } + if (isset($this->decalage)) { + $this->decalage = trim($this->decalage); + } @@ -287,13 +316,13 @@ class PaymentTerm // extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -325,13 +354,13 @@ class PaymentTerm // extends CommonObject dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -373,8 +402,7 @@ class PaymentTerm // extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $error++; } @@ -382,8 +410,7 @@ class PaymentTerm // extends CommonObject unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php index 6b8758bc472..dc1fe1e7c45 100644 --- a/htdocs/compta/facture/contact.php +++ b/htdocs/compta/facture/contact.php @@ -45,7 +45,9 @@ $socid = GETPOST('socid', 'int'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'facture', $id); $object = new Facture($db); @@ -55,47 +57,39 @@ $object = new Facture($db); * Add a new contact */ -if ($action == 'addcontact' && $user->rights->facture->creer) -{ +if ($action == 'addcontact' && $user->rights->facture->creer) { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} // Toggle the status of a contact -elseif ($action == 'swapstatut' && $user->rights->facture->creer) -{ - if ($object->fetch($id)) - { +} elseif ($action == 'swapstatut' && $user->rights->facture->creer) { + // Toggle the status of a contact + if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } -} // Deletes a contact -elseif ($action == 'deletecontact' && $user->rights->facture->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->facture->creer) { + // Deletes a contact $object->fetch($id); $result = $object->delete_contact($lineid); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -124,10 +118,8 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $head = facture_prepare_head($object); @@ -147,12 +139,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { + if ($user->rights->facture->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; $morehtmlref .= ' : '; @@ -192,10 +182,11 @@ if ($id > 0 || !empty($ref)) // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + if ($res) { + break; + } } } else { // Record not found diff --git a/htdocs/compta/facture/document.php b/htdocs/compta/facture/document.php index cbf6b045e85..c44aeae67ca 100644 --- a/htdocs/compta/facture/document.php +++ b/htdocs/compta/facture/document.php @@ -49,8 +49,7 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) -{ +if ($user->socid) { $socid = $user->socid; } $result = restrictedArea($user, 'facture', $id, ''); @@ -60,16 +59,21 @@ $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 +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 = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} $object = new Facture($db); -if ($object->fetch($id)) -{ +if ($object->fetch($id)) { $object->fetch_thirdparty(); $upload_dir = $conf->facture->dir_output."/".dol_sanitizeFileName($object->ref); } @@ -92,10 +96,8 @@ llxHeader('', $title, $helpurl); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $upload_dir = $conf->facture->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); @@ -108,8 +110,7 @@ if ($id > 0 || !empty($ref)) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -125,15 +126,14 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') + 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 .= ''; diff --git a/htdocs/compta/facture/index.php b/htdocs/compta/facture/index.php index e96371ad4f4..4939fbb6a95 100644 --- a/htdocs/compta/facture/index.php +++ b/htdocs/compta/facture/index.php @@ -34,8 +34,7 @@ $langs->load('bills'); // Filter to show only result of one customer $socid = GETPOST('socid', 'int'); -if (isset($user->socid) && $user->socid > 0) -{ +if (isset($user->socid) && $user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -58,8 +57,7 @@ print '
'; print '
'; // This is useless due to the global search combo -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { print getAreaSearchFrom(); print '
'; } @@ -129,16 +127,21 @@ function getPieChart($socid = 0) $sql = "SELECT count(f.rowid), f.fk_statut"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."facture as f"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture').")"; - if ($user->socid) $sql .= ' AND f.fk_soc = '.$user->socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) { + $sql .= ' AND f.fk_soc = '.$user->socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " GROUP BY f.fk_statut"; $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -149,11 +152,9 @@ function getPieChart($socid = 0) $total = 0; $vals = []; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); - if ($row) - { + if ($row) { $vals[$row[1]] = $row[0]; $total += $row[0]; } @@ -173,14 +174,12 @@ function getPieChart($socid = 0) $array = [Facture::STATUS_DRAFT, Facture::STATUS_VALIDATED, Facture::STATUS_CLOSED, Facture::STATUS_ABANDONED]; $dataseries = []; - foreach ($array as $status) - { + foreach ($array as $status) { $objectstatic->statut = $status; $objectstatic->paye = $status == Facture::STATUS_CLOSED ? -1 : 0; $dataseries[] = [$objectstatic->getLibStatut(1), (isset($vals[$status]) ? (int) $vals[$status] : 0)]; - if (!$conf->use_javascript_ajax) - { + if (!$conf->use_javascript_ajax) { $result .= '
'; $result .= ''; $result .= ''; @@ -188,8 +187,7 @@ function getPieChart($socid = 0) } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); $dolgraph->setShowLegend(2); @@ -227,17 +225,22 @@ function getDraftTable($maxCount = 500, $socid = 0) $sql = "SELECT f.rowid, f.ref, s.nom as socname, s.rowid as socid, s.canvas, s.client, f.total as total_ttc"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture').")"; $sql .= " AND f.fk_statut = ".Facture::STATUS_DRAFT; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= $db->plimit($maxCount, 0); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -256,8 +259,7 @@ function getDraftTable($maxCount = 500, $socid = 0) $result .= ''; $result .= ''; - if ($num < 1) - { + if ($num < 1) { $result .= '
'.$langs->trans("Ref").'
'; @@ -863,8 +829,7 @@ if ($type == Categorie::TYPE_ACCOUNT) print ''.$account->number."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -882,15 +847,13 @@ if ($type == Categorie::TYPE_ACCOUNT) } // List of Project -if ($type == Categorie::TYPE_PROJECT) -{ +if ($type == Categorie::TYPE_PROJECT) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $permission = $user->rights->projet->creer; $objects = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($objects < 0) - { + if ($objects < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -908,13 +871,13 @@ if ($type == Categorie::TYPE_PROJECT) print "\n"; print ''."\n"; - if (count($objects) > 0) - { + if (count($objects) > 0) { $i = 0; - foreach ($objects as $key => $project) - { + foreach ($objects as $key => $project) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; // Multicurrency rate - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { print ''; print ''; print '
'.$langs->trans("Ref").'
'; @@ -924,8 +887,7 @@ if ($type == Categorie::TYPE_PROJECT) print ''.$project->title."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -943,13 +905,11 @@ if ($type == Categorie::TYPE_PROJECT) } // List of users -if ($type == Categorie::TYPE_USER) -{ +if ($type == Categorie::TYPE_USER) { require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; $users = $object->getObjectsInCateg($type); - if ($users < 0) - { + if ($users < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -969,11 +929,9 @@ if ($type == Categorie::TYPE_USER) print "\n"; print ''."\n"; - if (count($users) > 0) - { + if (count($users) > 0) { // Use "$userentry" here, because "$user" is the current user - foreach ($users as $key => $userentry) - { + foreach ($users as $key => $userentry) { print "\t".''."\n"; print ''; // Status - Percent $withstatus = 0; - if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') - { + if ($event->type_code != 'BIRTHDAY' && $event->type_code != 'ICALEVENT') { $withstatus = 1; - if ($event->percentage >= 0) $withstatus = 2; + if ($event->percentage >= 0) { + $withstatus = 2; + } } print '
'.$langs->trans("Users").' '.$num.'
'; print $userentry->getNomUrl(1); @@ -982,8 +940,7 @@ if ($type == Categorie::TYPE_USER) // Link to delete from category print ''; - if ($user->rights->user->user->creer) - { + if ($user->rights->user->user->creer) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); @@ -1002,15 +959,13 @@ if ($type == Categorie::TYPE_USER) // List of warehouses -if ($type == Categorie::TYPE_WAREHOUSE) -{ +if ($type == Categorie::TYPE_WAREHOUSE) { $permission = $user->rights->stock->creer; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; $objects = $object->getObjectsInCateg($type, 0, $limit, $offset); - if ($objects < 0) - { + if ($objects < 0) { dol_print_error($db, $object->error, $object->errors); } else { print ''; @@ -1028,13 +983,13 @@ if ($type == Categorie::TYPE_WAREHOUSE) print "\n"; print ''."\n"; - if (count($objects) > 0) - { + if (count($objects) > 0) { $i = 0; - foreach ($objects as $key => $project) - { + foreach ($objects as $key => $project) { $i++; - if ($i > $limit) break; + if ($i > $limit) { + break; + } print "\t".''."\n"; print '\n"; // Link to delete from category print ''; $i = 0; - while ($i < 7) - { + while ($i < 7) { print ' '."\n"; $i++; } @@ -1283,15 +1365,11 @@ if (empty($action) || $action == 'show_month') // View by month for ($iter_week = 0; $iter_week < 6; $iter_week++) { echo " \n"; // Get date of the current day, format 'yyyy-mm-dd' - if ($tmpday <= 0) // If number of the current day is in previous month - { + if ($tmpday <= 0) { // If number of the current day is in previous month $currdate0 = sprintf("%04d", $prev_year).sprintf("%02d", $prev_month).sprintf("%02d", $max_day_in_prev_month + $tmpday); - } - elseif ($tmpday <= $max_day_in_month) // If number of the current day is in current month - { + } elseif ($tmpday <= $max_day_in_month) { // If number of the current day is in current month $currdate0 = sprintf("%04d", $year).sprintf("%02d", $month).sprintf("%02d", $tmpday); - } - else // If number of the current day is in next month + } else // If number of the current day is in next month { $currdate0 = sprintf("%04d", $next_year).sprintf("%02d", $next_month).sprintf("%02d", $tmpday - $max_day_in_month); } @@ -1304,7 +1382,9 @@ if (empty($action) || $action == 'show_month') // View by month if ($tmpday <= 0) { /* Show days before the beginning of the current month (previous month) */ $style = 'cal_other_month cal_past'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; + if ($iter_day == 6) { + $style .= ' cal_other_month_right'; + } echo ' \n"; @@ -1312,11 +1392,19 @@ if (empty($action) || $action == 'show_month') // View by month /* Show days of the current month */ $curtime = dol_mktime(0, 0, 0, $month, $tmpday, $year); $style = 'cal_current_month'; - if ($iter_day == 6) $style .= ' cal_current_month_right'; + if ($iter_day == 6) { + $style .= ' cal_current_month_right'; + } $today = 0; - if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; - if ($today) $style = 'cal_today'; - if ($curtime < $todaytms) $style .= ' cal_past'; + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $month && $todayarray['year'] == $year) { + $today = 1; + } + if ($today) { + $style = 'cal_today'; + } + if ($curtime < $todaytms) { + $style .= ' cal_past'; + } //var_dump($todayarray['mday']."==".$tmpday." && ".$todayarray['mon']."==".$month." && ".$todayarray['year']."==".$year.' -> '.$style); echo ' \n"; @@ -1376,12 +1466,18 @@ if (empty($action) || $action == 'show_month') // View by month $tmpyear = dol_print_date($curtime, '%Y', 'tzuserrel'); $style = 'cal_current_month'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; + if ($iter_day == 6) { + $style .= ' cal_other_month_right'; + } $today = 0; $todayarray = dol_getdate($now, 'fast'); - if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) $today = 1; - if ($today) $style = 'cal_today'; + if ($todayarray['mday'] == $tmpday && $todayarray['mon'] == $tmpmonth && $todayarray['year'] == $tmpyear) { + $today = 1; + } + if ($today) { + $style = 'cal_today'; + } echo ' \n"; /* - echo '
'; - echo '
'; - echo '
'; - echo show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, -1); - echo '
'."\n"; - echo "
\n"; + echo '
'; + echo '
'; + echo '
'; + echo show_day_events($db, $day, $month, $year, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300, -1); + echo '
'."\n"; + echo "
\n"; */ echo '
'.$langs->trans("Ref").'
'; @@ -1044,8 +999,7 @@ if ($type == Categorie::TYPE_WAREHOUSE) print ''.$project->title."'; - if ($permission) - { + if ($permission) { print ""; print $langs->trans("DeleteFromCat"); print img_picto($langs->trans("DeleteFromCat"), 'unlink', '', false, 0, 0, '', 'paddingleft'); diff --git a/htdocs/collab/index.php b/htdocs/collab/index.php index e5fe22c9168..296e0f3852f 100644 --- a/htdocs/collab/index.php +++ b/htdocs/collab/index.php @@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Load translation files required by the page $langs->loadLangs(array("admin", "other", "website")); -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} $conf->dol_hide_leftmenu = 1; // Force hide of left menu. @@ -41,17 +43,37 @@ $page = GETPOST('page', 'alpha'); $pageid = GETPOST('pageid', 'int'); $action = GETPOST('action', 'aZ09'); -if (GETPOST('delete')) { $action = 'delete'; } -if (GETPOST('preview')) $action = 'preview'; -if (GETPOST('create')) { $action = 'create'; } -if (GETPOST('editmedia')) { $action = 'editmedia'; } -if (GETPOST('editcss')) { $action = 'editcss'; } -if (GETPOST('editmenu')) { $action = 'editmenu'; } -if (GETPOST('setashome')) { $action = 'setashome'; } -if (GETPOST('editmeta')) { $action = 'editmeta'; } -if (GETPOST('editcontent')) { $action = 'editcontent'; } +if (GETPOST('delete')) { + $action = 'delete'; +} +if (GETPOST('preview')) { + $action = 'preview'; +} +if (GETPOST('create')) { + $action = 'create'; +} +if (GETPOST('editmedia')) { + $action = 'editmedia'; +} +if (GETPOST('editcss')) { + $action = 'editcss'; +} +if (GETPOST('editmenu')) { + $action = 'editmenu'; +} +if (GETPOST('setashome')) { + $action = 'setashome'; +} +if (GETPOST('editmeta')) { + $action = 'editmeta'; +} +if (GETPOST('editcontent')) { + $action = 'editcontent'; +} -if (empty($action)) $action = 'preview'; +if (empty($action)) { + $action = 'preview'; +} @@ -60,13 +82,16 @@ if (empty($action)) $action = 'preview'; * Actions */ -if (GETPOST('refreshsite')) $pageid = 0; // If we change the site, we reset the pageid. -if (GETPOST('refreshpage')) $action = 'preview'; +if (GETPOST('refreshsite')) { + $pageid = 0; // If we change the site, we reset the pageid. +} +if (GETPOST('refreshpage')) { + $action = 'preview'; +} // Add a collab page -if ($action == 'add') -{ +if ($action == 'add') { $db->begin(); $objectpage->title = GETPOST('WEBSITE_TITLE'); @@ -74,23 +99,19 @@ if ($action == 'add') $objectpage->description = GETPOST('WEBSITE_DESCRIPTION'); $objectpage->keywords = GETPOST('WEBSITE_KEYWORD'); - if (empty($objectpage->title)) - { + if (empty($objectpage->title)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $res = $objectpage->create($user); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); $action = ''; @@ -103,25 +124,21 @@ if ($action == 'add') } // Update page -if ($action == 'delete') -{ +if ($action == 'delete') { $db->begin(); $res = $object->fetch(0, $website); $res = $objectpage->fetch($pageid, $object->fk_website); - if ($res > 0) - { + if ($res > 0) { $res = $objectpage->delete($user); - if (!($res > 0)) - { + if (!($res > 0)) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $website), null, 'mesgs'); @@ -149,15 +166,16 @@ llxHeader('', $langs->trans("WebsiteSetup"), $help_url, '', 0, '', '', '', '', ' print "\n".'
'; print ''; -if ($action == 'create') -{ +if ($action == 'create') { print ''; } // Add a margin under toolbar ? $style = ''; -if ($action != 'preview' && $action != 'editcontent') $style = ' margin-bottom: 5px;'; +if ($action != 'preview' && $action != 'editcontent') { + $style = ' margin-bottom: 5px;'; +} //var_dump($objectpage);exit; print '
'; From 464e4442b1a7856880f50ebce440c3eeea0fad09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 18:23:14 +0100 Subject: [PATCH 11/64] fix fourn card --- htdocs/fourn/card.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 9794ea3cc11..418773daec5 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -7,6 +7,7 @@ * Copyright (C) 2014 Jean Heimburger * Copyright (C) 2015 Marcos García * Copyright (C) 2015 Raphaël Doursenaud + * Copyright (C) 2021 Frédéric France * * 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 @@ -657,7 +658,7 @@ if ($object->id > 0) $num = $object_count->total; } - $sql = "SELECT p.rowid,p.ref, p.date_commande as dc, p.fk_statut, p.total_ht, p.tva as total_tva, p.total_ttc"; + $sql = "SELECT p.rowid,p.ref, p.date_commande as dc, p.fk_statut, p.total_ht, p.total_tva, p.total_ttc"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as p"; $sql .= " WHERE p.fk_soc =".$object->id; $sql .= " AND p.entity IN (".getEntity('commande_fournisseur').")"; From 5931051c88a6329086861e66201b708eddeebafa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 18:59:19 +0100 Subject: [PATCH 12/64] code syntax comm directory --- htdocs/comm/action/card.php | 689 +++++----- htdocs/comm/action/class/actioncomm.class.php | 806 +++++++----- .../action/class/actioncommreminder.class.php | 29 +- .../action/class/api_agendaevents.class.php | 81 +- .../comm/action/class/cactioncomm.class.php | 99 +- htdocs/comm/action/class/ical.class.php | 96 +- htdocs/comm/action/document.php | 98 +- htdocs/comm/action/index.php | 887 +++++++------ htdocs/comm/action/info.php | 10 +- htdocs/comm/action/list.php | 566 +++++--- htdocs/comm/action/pertype.php | 590 +++++---- htdocs/comm/action/peruser.php | 719 ++++++---- htdocs/comm/action/rapport/index.php | 56 +- htdocs/comm/admin/propal_extrafields.php | 17 +- htdocs/comm/admin/propaldet_extrafields.php | 20 +- htdocs/comm/card.php | 1 - htdocs/comm/contact.php | 67 +- htdocs/comm/index.php | 3 +- htdocs/comm/mailing/advtargetemailing.php | 24 +- htdocs/comm/mailing/card.php | 2 +- htdocs/comm/mailing/cibles.php | 254 ++-- .../mailing/class/advtargetemailing.class.php | 2 +- .../html.formadvtargetemailing.class.php | 33 +- htdocs/comm/mailing/class/mailing.class.php | 2 +- htdocs/comm/mailing/index.php | 37 +- htdocs/comm/mailing/info.php | 1 - htdocs/comm/mailing/list.php | 125 +- htdocs/comm/multiprix.php | 35 +- htdocs/comm/propal/card.php | 690 +++++----- .../comm/propal/class/api_proposals.class.php | 141 +- htdocs/comm/propal/class/propal.class.php | 1164 +++++++++-------- .../comm/propal/class/propalestats.class.php | 47 +- htdocs/comm/propal/contact.php | 60 +- htdocs/comm/propal/document.php | 46 +- htdocs/comm/propal/index.php | 2 +- htdocs/comm/propal/info.php | 19 +- htdocs/comm/propal/list.php | 1076 +++++++++------ htdocs/comm/propal/note.php | 23 +- htdocs/comm/propal/stats/index.php | 90 +- .../comm/propal/tpl/linkedobjectblock.tpl.php | 13 +- htdocs/comm/prospect/index.php | 1 - htdocs/comm/prospect/recap-prospect.php | 20 +- htdocs/comm/recap-client.php | 19 +- htdocs/comm/remise.php | 54 +- htdocs/comm/remx.php | 277 ++-- 45 files changed, 5038 insertions(+), 4053 deletions(-) diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index fba2cf10cbc..3b539895348 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -77,9 +77,13 @@ $datef = dol_mktime($fulldayevent ? '23' : $p2hour, $fulldayevent ? '59' : $p2mi // Security check $socid = GETPOST('socid', 'int'); $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'agenda', $id, 'actioncomm&societe', 'myactions|allactions', 'fk_soc', 'id'); -if ($user->socid && $socid) $result = restrictedArea($user, 'societe', $socid); +if ($user->socid && $socid) { + $result = restrictedArea($user, 'societe', $socid); +} $error = GETPOST("error"); $donotclearsession = GETPOST('donotclearsession') ?GETPOST('donotclearsession') : 0; @@ -114,11 +118,17 @@ $hookmanager->initHooks(array('actioncard', 'globalcard')); $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} $TRemindTypes = array(); -if (!empty($conf->global->AGENDA_REMINDER_BROWSER)) $TRemindTypes['browser'] = array('label'=>$langs->trans('BrowserPush'), 'disabled'=>(empty($conf->global->AGENDA_REMINDER_BROWSER) ? 1 : 0)); -if (!empty($conf->global->AGENDA_REMINDER_EMAIL)) $TRemindTypes['email'] = array('label'=>$langs->trans('EMail'), 'disabled'=>(empty($conf->global->AGENDA_REMINDER_EMAIL) ? 1 : 0)); +if (!empty($conf->global->AGENDA_REMINDER_BROWSER)) { + $TRemindTypes['browser'] = array('label'=>$langs->trans('BrowserPush'), 'disabled'=>(empty($conf->global->AGENDA_REMINDER_BROWSER) ? 1 : 0)); +} +if (!empty($conf->global->AGENDA_REMINDER_EMAIL)) { + $TRemindTypes['email'] = array('label'=>$langs->trans('EMail'), 'disabled'=>(empty($conf->global->AGENDA_REMINDER_EMAIL) ? 1 : 0)); +} $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month'), 'w'=>$langs->trans('Weeks'), 'd'=>$langs->trans('Days'), 'h'=>$langs->trans('Hours'), 'i'=>$langs->trans('Minutes')); @@ -129,60 +139,65 @@ $TDurationTypes = array('y'=>$langs->trans('Years'), 'm'=>$langs->trans('Month') $listUserAssignedUpdated = false; // Remove user to assigned list -if (empty($reshook) && (GETPOST('removedassigned') || GETPOST('removedassigned') == '0')) -{ +if (empty($reshook) && (GETPOST('removedassigned') || GETPOST('removedassigned') == '0')) { $idtoremove = GETPOST('removedassigned'); - if (!empty($_SESSION['assignedtouser'])) $tmpassigneduserids = json_decode($_SESSION['assignedtouser'], 1); - else $tmpassigneduserids = array(); + if (!empty($_SESSION['assignedtouser'])) { + $tmpassigneduserids = json_decode($_SESSION['assignedtouser'], 1); + } else { + $tmpassigneduserids = array(); + } - foreach ($tmpassigneduserids as $key => $val) - { - if ($val['id'] == $idtoremove || $val['id'] == -1) unset($tmpassigneduserids[$key]); + foreach ($tmpassigneduserids as $key => $val) { + if ($val['id'] == $idtoremove || $val['id'] == -1) { + unset($tmpassigneduserids[$key]); + } } $_SESSION['assignedtouser'] = json_encode($tmpassigneduserids); $donotclearsession = 1; - if ($action == 'add') $action = 'create'; - if ($action == 'update') $action = 'edit'; + if ($action == 'add') { + $action = 'create'; + } + if ($action == 'update') { + $action = 'edit'; + } $listUserAssignedUpdated = true; } // Add user to assigned list -if (empty($reshook) && (GETPOST('addassignedtouser') || GETPOST('updateassignedtouser'))) -{ +if (empty($reshook) && (GETPOST('addassignedtouser') || GETPOST('updateassignedtouser'))) { // Add a new user - if (GETPOST('assignedtouser') > 0) - { + if (GETPOST('assignedtouser') > 0) { $assignedtouser = array(); - if (!empty($_SESSION['assignedtouser'])) - { + if (!empty($_SESSION['assignedtouser'])) { $assignedtouser = json_decode($_SESSION['assignedtouser'], true); } $assignedtouser[GETPOST('assignedtouser')] = array('id'=>GETPOST('assignedtouser'), 'transparency'=>GETPOST('transparency'), 'mandatory'=>1); $_SESSION['assignedtouser'] = json_encode($assignedtouser); } $donotclearsession = 1; - if ($action == 'add') $action = 'create'; - if ($action == 'update') $action = 'edit'; + if ($action == 'add') { + $action = 'create'; + } + if ($action == 'update') { + $action = 'edit'; + } $listUserAssignedUpdated = true; } // Link to a project if (empty($reshook) && $action == 'classin' && ($user->rights->agenda->allactions->create || - (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->create))) -{ + (($object->authorid == $user->id || $object->userownerid == $user->id) && $user->rights->agenda->myactions->create))) { //$object->fetch($id); $object->setProject(GETPOST('projectid', 'int')); } // Action clone object -if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes') -{ - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { +if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes') { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { if ($id > 0) { @@ -204,23 +219,22 @@ if (empty($reshook) && $action == 'confirm_clone' && $confirm == 'yes') } // Add event -if (empty($reshook) && $action == 'add') -{ +if (empty($reshook) && $action == 'add') { $error = 0; - if (empty($backtopage)) - { - if ($socid > 0) $backtopage = DOL_URL_ROOT.'/societe/agenda.php?socid='.$socid; - else $backtopage = DOL_URL_ROOT.'/comm/action/index.php'; + if (empty($backtopage)) { + if ($socid > 0) { + $backtopage = DOL_URL_ROOT.'/societe/agenda.php?socid='.$socid; + } else { + $backtopage = DOL_URL_ROOT.'/comm/action/index.php'; + } } - if (!empty($socpeopleassigned[0])) - { + if (!empty($socpeopleassigned[0])) { $result = $contact->fetch($socpeopleassigned[0]); } - if ($cancel) - { + if ($cancel) { header("Location: ".$backtopage); exit; } @@ -232,23 +246,20 @@ if (empty($reshook) && $action == 'add') $datef = dol_mktime($fulldayevent ? '23' : GETPOST("p2hour", 'int'), $fulldayevent ? '59' : GETPOST("p2min", 'int'), $fulldayevent ? '59' : GETPOST("apsec", 'int'), GETPOST("p2month", 'int'), GETPOST("p2day", 'int'), GETPOST("p2year", 'int'), 'tzuser'); // Check parameters - if (!$datef && $percentage == 100) - { + if (!$datef && $percentage == 100) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors'); } - if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && !GETPOST('label')) - { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && !GETPOST('label')) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Title")), null, 'errors'); } // Initialisation objet cactioncomm - if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) // actioncode is '0' - { + if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) { // actioncode is '0' $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); @@ -256,8 +267,7 @@ if (empty($reshook) && $action == 'add') $object->type_code = GETPOST('actioncode', 'aZ09'); } - if (!$error) - { + if (!$error) { // Initialisation objet actioncomm $object->priority = GETPOSTISSET("priority") ? GETPOST("priority", "int") : 0; $object->fulldayevent = (!empty($fulldayevent) ? 1 : 0); @@ -265,14 +275,11 @@ if (empty($reshook) && $action == 'add') $object->label = GETPOST('label', 'alphanohtml'); $object->fk_element = GETPOST("fk_element", 'int'); $object->elementtype = GETPOST("elementtype", 'alpha'); - if (!GETPOST('label')) - { - if (GETPOST('actioncode', 'aZ09') == 'AC_RDV' && $contact->getFullName($langs)) - { + if (!GETPOST('label')) { + if (GETPOST('actioncode', 'aZ09') == 'AC_RDV' && $contact->getFullName($langs)) { $object->label = $langs->transnoentitiesnoconv("TaskRDVWith", $contact->getFullName($langs)); } else { - if ($langs->trans("Action".$object->type_code) != "Action".$object->type_code) - { + if ($langs->trans("Action".$object->type_code) != "Action".$object->type_code) { $object->label = $langs->transnoentitiesnoconv("Action".$object->type_code)."\n"; } else { $cactioncomm->fetch($object->type_code); @@ -301,13 +308,15 @@ if (empty($reshook) && $action == 'add') $transparency = (GETPOST("transparency") == 'on' ? 1 : 0); $listofuserid = array(); - if (!empty($_SESSION['assignedtouser'])) $listofuserid = json_decode($_SESSION['assignedtouser'], true); + if (!empty($_SESSION['assignedtouser'])) { + $listofuserid = json_decode($_SESSION['assignedtouser'], true); + } $i = 0; - foreach ($listofuserid as $key => $value) - { - if ($i == 0) // First entry - { - if ($value['id'] > 0) $object->userownerid = $value['id']; + foreach ($listofuserid as $key => $value) { + if ($i == 0) { // First entry + if ($value['id'] > 0) { + $object->userownerid = $value['id']; + } $object->transparency = $transparency; } @@ -317,17 +326,19 @@ if (empty($reshook) && $action == 'add') } } - if (!$error && !empty($conf->global->AGENDA_ENABLE_DONEBY)) - { - if (GETPOST("doneby") > 0) $object->userdoneid = GETPOST("doneby", "int"); + if (!$error && !empty($conf->global->AGENDA_ENABLE_DONEBY)) { + if (GETPOST("doneby") > 0) { + $object->userdoneid = GETPOST("doneby", "int"); + } } $object->note_private = trim(GETPOST("note", "restricthtml")); - if (GETPOSTISSET("contactid")) $object->contact = $contact; + if (GETPOSTISSET("contactid")) { + $object->contact = $contact; + } - if (GETPOST('socid', 'int') > 0) - { + if (GETPOST('socid', 'int') > 0) { $object->socid = GETPOST('socid', 'int'); $object->fetch_thirdparty(); @@ -335,51 +346,45 @@ if (empty($reshook) && $action == 'add') } // Check parameters - if (empty($object->userownerid) && empty($_SESSION['assignedtouser'])) - { + if (empty($object->userownerid) && empty($_SESSION['assignedtouser'])) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ActionsOwnedBy")), null, 'errors'); } - if ($object->type_code == 'AC_RDV' && ($datep == '' || ($datef == '' && empty($fulldayevent)))) - { + if ($object->type_code == 'AC_RDV' && ($datep == '' || ($datef == '' && empty($fulldayevent)))) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors'); } - if (!GETPOST('apyear') && !GETPOST('adyear')) - { + if (!GETPOST('apyear') && !GETPOST('adyear')) { $error++; $donotclearsession = 1; $action = 'create'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); } - foreach ($socpeopleassigned as $cid) - { + foreach ($socpeopleassigned as $cid) { $object->socpeopleassigned[$cid] = array('id' => $cid); } - if (!empty($object->socpeopleassigned)) - { + if (!empty($object->socpeopleassigned)) { reset($object->socpeopleassigned); $object->contact_id = key($object->socpeopleassigned); } // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $db->begin(); // Creation of action/event $idaction = $object->create($user); - if ($idaction > 0) - { - if (!$object->error) - { + if ($idaction > 0) { + if (!$object->error) { // Category association $categories = GETPOST('categories', 'array'); $object->setCategories($categories); @@ -387,7 +392,9 @@ if (empty($reshook) && $action == 'add') unset($_SESSION['assignedtouser']); $moreparam = ''; - if ($user->id != $object->userownerid) $moreparam = "filtert=-1"; // We force to remove filter so created record is visible when going back to per user view. + if ($user->id != $object->userownerid) { + $moreparam = "filtert=-1"; // We force to remove filter so created record is visible when going back to per user view. + } // Create reminders if ($addreminder == 'on') { @@ -401,11 +408,12 @@ if (empty($reshook) && $action == 'add') $actionCommReminder->offsetvalue = $offsetvalue; $actionCommReminder->status = $actionCommReminder::STATUS_TODO; $actionCommReminder->fk_actioncomm = $object->id; - if ($remindertype == 'email') $actionCommReminder->fk_email_template = $modelmail; + if ($remindertype == 'email') { + $actionCommReminder->fk_email_template = $modelmail; + } // the notification must be created for every user assigned to the event - foreach ($object->userassigned as $userassigned) - { + foreach ($object->userassigned as $userassigned) { $actionCommReminder->fk_user = $userassigned['id']; $res = $actionCommReminder->create($user); @@ -427,12 +435,10 @@ if (empty($reshook) && $action == 'add') $db->commit(); } - if (!empty($backtopage)) - { + if (!empty($backtopage)) { dol_syslog("Back to ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : '')); header("Location: ".$backtopage.($moreparam ? (preg_match('/\?/', $backtopage) ? '&'.$moreparam : '?'.$moreparam) : '')); - } elseif ($idaction) - { + } elseif ($idaction) { header("Location: ".DOL_URL_ROOT.'/comm/action/card.php?id='.$idaction.($moreparam ? '&'.$moreparam : '')); } else { header("Location: ".DOL_URL_ROOT.'/comm/action/index.php'.($moreparam ? '?'.$moreparam : '')); @@ -457,10 +463,8 @@ if (empty($reshook) && $action == 'add') /* * Action update event */ -if (empty($reshook) && $action == 'update') -{ - if (empty($cancel)) - { +if (empty($reshook) && $action == 'update') { + if (empty($cancel)) { $fulldayevent = GETPOST('fullday'); $aphour = GETPOST('aphour', 'int'); $apmin = GETPOST('apmin', 'int'); @@ -469,10 +473,18 @@ if (empty($reshook) && $action == 'update') $percentage = in_array(GETPOST('status'), array(-1, 100)) ?GETPOST('status') : (in_array(GETPOST('complete'), array(-1, 100)) ?GETPOST('complete') : GETPOST("percentage")); // If status is -1 or 100, percentage is not defined and we must use status // Clean parameters - if ($aphour == -1) $aphour = '0'; - if ($apmin == -1) $apmin = '0'; - if ($p2hour == -1) $p2hour = '0'; - if ($p2min == -1) $p2min = '0'; + if ($aphour == -1) { + $aphour = '0'; + } + if ($apmin == -1) { + $apmin = '0'; + } + if ($p2hour == -1) { + $p2hour = '0'; + } + if ($p2min == -1) { + $p2min = '0'; + } $object->fetch($id); $object->fetch_optionals(); @@ -493,7 +505,9 @@ if (empty($reshook) && $action == 'update') $object->socid = GETPOST("socid", "int"); $socpeopleassigned = GETPOST("socpeopleassigned", 'array'); $object->socpeopleassigned = array(); - foreach ($socpeopleassigned as $cid) $object->socpeopleassigned[$cid] = array('id' => $cid); + foreach ($socpeopleassigned as $cid) { + $object->socpeopleassigned[$cid] = array('id' => $cid); + } $object->contact_id = GETPOST("contactid", 'int'); if (empty($object->contact_id) && !empty($object->socpeopleassigned)) { reset($object->socpeopleassigned); @@ -503,8 +517,7 @@ if (empty($reshook) && $action == 'update') $object->note_private = trim(GETPOST("note", "restricthtml")); $object->fk_element = GETPOST("fk_element", "int"); $object->elementtype = GETPOST("elementtype", "alphanohtml"); - if (!$datef && $percentage == 100) - { + if (!$datef && $percentage == 100) { $error++; $donotclearsession = 1; setEventMessages($langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), $object->errors, 'errors'); $action = 'edit'; @@ -514,23 +527,26 @@ if (empty($reshook) && $action == 'update') // Users $listofuserid = array(); - if (!empty($_SESSION['assignedtouser'])) // Now concat assigned users - { + if (!empty($_SESSION['assignedtouser'])) { // Now concat assigned users // Restore array with key with same value than param 'id' $tmplist1 = json_decode($_SESSION['assignedtouser'], true); - foreach ($tmplist1 as $key => $val) - { - if ($val['id'] > 0 && $val['id'] != $assignedtouser) $listofuserid[$val['id']] = $val; + foreach ($tmplist1 as $key => $val) { + if ($val['id'] > 0 && $val['id'] != $assignedtouser) { + $listofuserid[$val['id']] = $val; + } } } else { $assignedtouser = (!empty($object->userownerid) && $object->userownerid > 0 ? $object->userownerid : 0); - if ($assignedtouser) $listofuserid[$assignedtouser] = array('id'=>$assignedtouser, 'mandatory'=>0, 'transparency'=>($user->id == $assignedtouser ? $transparency : '')); // Owner first + if ($assignedtouser) { + $listofuserid[$assignedtouser] = array('id'=>$assignedtouser, 'mandatory'=>0, 'transparency'=>($user->id == $assignedtouser ? $transparency : '')); // Owner first + } } $object->userassigned = array(); $object->userownerid = 0; // Clear old content $i = 0; - foreach ($listofuserid as $key => $val) - { - if ($i == 0) $object->userownerid = $val['id']; + foreach ($listofuserid as $key => $val) { + if ($i == 0) { + $object->userownerid = $val['id']; + } $object->userassigned[$val['id']] = array('id'=>$val['id'], 'mandatory'=>0, 'transparency'=>($user->id == $val['id'] ? $transparency : '')); $i++; } @@ -538,22 +554,21 @@ if (empty($reshook) && $action == 'update') $object->transparency = $transparency; // We set transparency on event (even if we can also store it on each user, standard says this property is for event) // TODO store also transparency on owner user - if (!empty($conf->global->AGENDA_ENABLE_DONEBY)) - { - if (GETPOST("doneby")) $object->userdoneid = GETPOST("doneby", "int"); + if (!empty($conf->global->AGENDA_ENABLE_DONEBY)) { + if (GETPOST("doneby")) { + $object->userdoneid = GETPOST("doneby", "int"); + } } // Check parameters - if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) // actioncode is '0' - { + if (GETPOSTISSET('actioncode') && !GETPOST('actioncode', 'aZ09')) { // actioncode is '0' $error++; $donotclearsession = 1; $action = 'edit'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")), null, 'errors'); } else { $result = $cactioncomm->fetch(GETPOST('actioncode', 'aZ09')); } - if (empty($object->userownerid)) - { + if (empty($object->userownerid)) { $error++; $donotclearsession = 1; $action = 'edit'; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ActionsOwnedBy")), null, 'errors'); @@ -561,7 +576,9 @@ if (empty($reshook) && $action == 'update') // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } if (!$error) { // check if an event resource is already in use @@ -622,23 +639,19 @@ if (empty($reshook) && $action == 'update') } } - if (!$error) - { + if (!$error) { $db->begin(); $result = $object->update($user); - if ($result > 0) - { + if ($result > 0) { // Category association $categories = GETPOST('categories', 'array'); $object->setCategories($categories); $object->loadReminders(); - if (!empty($object->reminders) && $object->datep > dol_now()) - { - foreach ($object->reminders as $reminder) - { + if (!empty($object->reminders) && $object->datep > dol_now()) { + foreach ($object->reminders as $reminder) { $reminder->delete($user); } $object->reminders = array(); @@ -656,11 +669,12 @@ if (empty($reshook) && $action == 'update') $actionCommReminder->offsetvalue = $offsetvalue; $actionCommReminder->status = $actionCommReminder::STATUS_TODO; $actionCommReminder->fk_actioncomm = $object->id; - if ($remindertype == 'email') $actionCommReminder->fk_email_template = $modelmail; + if ($remindertype == 'email') { + $actionCommReminder->fk_email_template = $modelmail; + } // the notification must be created for every user assigned to the event - foreach ($object->userassigned as $userassigned) - { + foreach ($object->userassigned as $userassigned) { $actionCommReminder->fk_user = $userassigned['id']; $res = $actionCommReminder->create($user); @@ -677,8 +691,11 @@ if (empty($reshook) && $action == 'update') unset($_SESSION['assignedtouser']); - if (!$error) $db->commit(); - else $db->rollback(); + if (!$error) { + $db->commit(); + } else { + $db->rollback(); + } } else { setEventMessages($object->error, $object->errors, 'errors'); $db->rollback(); @@ -686,10 +703,8 @@ if (empty($reshook) && $action == 'update') } } - if (!$error) - { - if (!empty($backtopage)) - { + if (!$error) { + if (!empty($backtopage)) { unset($_SESSION['assignedtouser']); header("Location: ".$backtopage); exit; @@ -700,20 +715,17 @@ if (empty($reshook) && $action == 'update') /* * delete event */ -if (empty($reshook) && $action == 'confirm_delete' && GETPOST("confirm") == 'yes') -{ +if (empty($reshook) && $action == 'confirm_delete' && GETPOST("confirm") == 'yes') { $object->fetch($id); $object->fetch_optionals(); $object->fetch_userassigned(); $object->oldcopy = clone $object; if ($user->rights->agenda->myactions->delete - || $user->rights->agenda->allactions->delete) - { + || $user->rights->agenda->allactions->delete) { $result = $object->delete(); - if ($result >= 0) - { + if ($result >= 0) { header("Location: index.php"); exit; } else { @@ -726,16 +738,14 @@ if (empty($reshook) && $action == 'confirm_delete' && GETPOST("confirm") == 'yes * Action move update, used when user move an event in calendar by drag'n drop * TODO Move this into page comm/action/index that trigger this call by the drag and drop of event. */ -if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') -{ +if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') { $error = 0; $shour = dol_print_date($object->datep, "%H", 'tzuserrel'); // We take the date visible by user $newdate is also date visible by user. $smin = dol_print_date($object->datep, "%M", 'tzuserrel'); $newdate = GETPOST('newdate', 'alpha'); - if (empty($newdate) || strpos($newdate, 'dayevent_') != 0) - { + if (empty($newdate) || strpos($newdate, 'dayevent_') != 0) { header("Location: ".$backtopage); exit; } @@ -743,10 +753,8 @@ if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') $datep = dol_mktime($shour, $smin, 0, substr($newdate, 13, 2), substr($newdate, 15, 2), substr($newdate, 9, 4), 'tzuserrel'); //print dol_print_date($datep, 'dayhour');exit; - if ($datep != $object->datep) - { - if (!empty($object->datef)) - { + if ($datep != $object->datep) { + if (!empty($object->datef)) { $object->datef += $datep - $object->datep; } $object->datep = $datep; @@ -822,8 +830,7 @@ if (empty($reshook) && GETPOST('actionmove', 'alpha') == 'mupdate') } } } - if (!empty($backtopage)) - { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } else { @@ -857,21 +864,20 @@ $arrayrecurrulefreq = array( $help_url = 'EN:Module_Agenda_En|FR:Module_Agenda|ES:M&omodulodulo_Agenda'; llxHeader('', $langs->trans("Agenda"), $help_url); -if ($action == 'create') -{ +if ($action == 'create') { $contact = new Contact($db); $socpeopleassigned = GETPOST("socpeopleassigned", 'array'); - if (!empty($socpeopleassigned[0])) - { + if (!empty($socpeopleassigned[0])) { $result = $contact->fetch($socpeopleassigned[0]); - if ($result < 0) dol_print_error($db, $contact->error); + if ($result < 0) { + dol_print_error($db, $contact->error); + } } dol_set_focus("#label"); - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print "\n".''."\n"; - foreach ($showextcals as $val) - { + foreach ($showextcals as $val) { $htmlname = md5($val['name']); $s .= '
 
'; } @@ -538,11 +574,9 @@ if (!empty($conf->use_javascript_ajax)) // If javascript on // Calendars from hooks $parameters = array(); $object = null; $reshook = $hookmanager->executeHooks('addCalendarChoice', $parameters, $object, $action); - if (empty($reshook)) - { + if (empty($reshook)) { $s .= $hookmanager->resPrint; - } elseif ($reshook > 1) - { + } elseif ($reshook > 1) { $s = $hookmanager->resPrint; } @@ -551,12 +585,17 @@ if (!empty($conf->use_javascript_ajax)) // If javascript on { $newparam = $param; // newparam is for birthday links $newparam = preg_replace('/showbirthday=[0-1]/i', 'showbirthday='.(empty($showbirthday) ? 1 : 0), $newparam); - if (!preg_match('/showbirthday=/i', $newparam)) $newparam .= '&showbirthday=1'; + if (!preg_match('/showbirthday=/i', $newparam)) { + $newparam .= '&showbirthday=1'; + } $link = '
'; - if (empty($showbirthday)) $link .= $langs->trans("AgendaShowBirthdayEvents"); - else $link .= $langs->trans("AgendaHideBirthdayEvents"); + if (empty($showbirthday)) { + $link .= $langs->trans("AgendaShowBirthdayEvents"); + } else { + $link .= $langs->trans("AgendaHideBirthdayEvents"); + } $link .= ''; } @@ -567,7 +606,9 @@ $eventarray = array(); // DEFAULT CALENDAR + AUTOEVENT CALENDAR + CONFERENCEBOOTH CALENDAR $sql = 'SELECT '; -if ($usergroup > 0) $sql .= " DISTINCT"; +if ($usergroup > 0) { + $sql .= " DISTINCT"; +} $sql .= ' a.id, a.label,'; $sql .= ' a.datep,'; $sql .= ' a.datep2,'; @@ -578,31 +619,44 @@ $sql .= ' a.fk_soc, a.fk_contact, a.fk_project,'; $sql .= ' a.fk_element, a.elementtype,'; $sql .= ' ca.code as type_code, ca.libelle as type_label, ca.color as type_color, ca.type as type_type, ca.picto as type_picto'; $sql .= ' FROM '.MAIN_DB_PREFIX.'c_actioncomm as ca, '.MAIN_DB_PREFIX."actioncomm as a"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +} // We must filter on resource table -if ($resourceid > 0) $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; +if ($resourceid > 0) { + $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; -if ($usergroup > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; +if ($filtert > 0 || $usergroup > 0) { + $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; +} +if ($usergroup > 0) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; +} $sql .= ' WHERE a.fk_action = ca.id'; $sql .= ' AND a.entity IN ('.getEntity('agenda').')'; // Condition on actioncode -if (!empty($actioncode)) -{ - if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND ca.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND ca.type = 'systemauto'"; - else { - if ($actioncode == 'AC_OTH') $sql .= " AND ca.type != 'systemauto'"; - if ($actioncode == 'AC_OTH_AUTO') $sql .= " AND ca.type = 'systemauto'"; +if (!empty($actioncode)) { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND ca.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND ca.type = 'systemauto'"; + } else { + if ($actioncode == 'AC_OTH') { + $sql .= " AND ca.type != 'systemauto'"; + } + if ($actioncode == 'AC_OTH_AUTO') { + $sql .= " AND ca.type = 'systemauto'"; + } } } else { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND ca.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND ca.type = 'systemauto'"; - else { - if (is_array($actioncode)) - { + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND ca.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND ca.type = 'systemauto'"; + } else { + if (is_array($actioncode)) { $sql .= " AND ca.code IN ('".implode("','", $actioncode)."')"; } else { $sql .= " AND ca.code IN ('".implode("','", explode(',', $actioncode))."')"; @@ -610,15 +664,24 @@ if (!empty($actioncode)) } } } -if ($resourceid > 0) $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); -if ($pid) $sql .= " AND a.fk_project=".$db->escape($pid); -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; -if ($socid > 0) $sql .= ' AND a.fk_soc = '.$socid; +if ($resourceid > 0) { + $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); +} +if ($pid) { + $sql .= " AND a.fk_project=".$db->escape($pid); +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; +} +if ($socid > 0) { + $sql .= ' AND a.fk_soc = '.$socid; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; +if ($filtert > 0 || $usergroup > 0) { + $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; +} //var_dump($day.' '.$month.' '.$year); -if ($action == 'show_day') -{ +if ($action == 'show_day') { $sql .= " AND ("; $sql .= " (a.datep BETWEEN '".$db->idate(dol_mktime(0, 0, 0, $month, $day, $year, 'tzuserrel'))."'"; $sql .= " AND '".$db->idate(dol_mktime(23, 59, 59, $month, $day, $year, 'tzuserrel'))."')"; @@ -642,18 +705,33 @@ if ($action == 'show_day') $sql .= " AND a.datep2 > '".$db->idate(dol_mktime(23, 59, 59, $month, 28, $year) + (60 * 60 * 24 * 10))."')"; $sql .= ')'; } -if ($type) $sql .= " AND ca.id = ".$type; -if ($status == '0') { $sql .= " AND a.percent = 0"; } -if ($status == '-1') { $sql .= " AND a.percent = -1"; } // Not applicable -if ($status == '50') { $sql .= " AND (a.percent > 0 AND a.percent < 100)"; } // Running already started -if ($status == 'done' || $status == '100') { $sql .= " AND (a.percent = 100)"; } -if ($status == 'todo') { $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; } +if ($type) { + $sql .= " AND ca.id = ".$type; +} +if ($status == '0') { + $sql .= " AND a.percent = 0"; +} +if ($status == '-1') { + $sql .= " AND a.percent = -1"; +} // Not applicable +if ($status == '50') { + $sql .= " AND (a.percent > 0 AND a.percent < 100)"; +} // Running already started +if ($status == 'done' || $status == '100') { + $sql .= " AND (a.percent = 100)"; +} +if ($status == 'todo') { + $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) -{ +if ($filtert > 0 || $usergroup > 0) { $sql .= " AND ("; - if ($filtert > 0) $sql .= "ar.fk_element = ".$filtert; - if ($usergroup > 0) $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + if ($filtert > 0) { + $sql .= "ar.fk_element = ".$filtert; + } + if ($usergroup > 0) { + $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + } $sql .= ")"; } // Sort on date @@ -663,19 +741,16 @@ $sql .= ' ORDER BY datep'; dol_syslog("comm/action/index.php", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $MAXONSAMEPAGE = 10000; // Useless to have more. Protection to avoid memory overload when high number of event (for example after a mass import) $i = 0; - while ($i < $num && $i < $MAXONSAMEPAGE) - { + while ($i < $num && $i < $MAXONSAMEPAGE) { $obj = $db->fetch_object($resql); // Discard auto action if option is on - if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') - { + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') { $i++; continue; } @@ -720,11 +795,13 @@ if ($resql) // Defined date_start_in_calendar and date_end_in_calendar property // They are date start and end of action but modified to not be outside calendar view. $event->date_start_in_calendar = $event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; - else $event->date_end_in_calendar = $event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) { + $event->date_end_in_calendar = $event->datef; + } else { + $event->date_end_in_calendar = $event->datep; + } // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { + if ($event->date_start_in_calendar == $event->date_end_in_calendar) { $event->ponctuel = 1; } @@ -732,8 +809,12 @@ if ($resql) if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) { // This record is out of visible range } else { - if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; - if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); + if ($event->date_start_in_calendar < $firstdaytoshow) { + $event->date_start_in_calendar = $firstdaytoshow; + } + if ($event->date_end_in_calendar >= $lastdaytoshow) { + $event->date_end_in_calendar = ($lastdaytoshow - 1); + } // Add an entry in actionarray for each day $daycursor = $event->date_start_in_calendar; @@ -753,7 +834,9 @@ if ($resql) $j++; $daykey += 60 * 60 * 24; - if ($daykey > $event->date_end_in_calendar) $loop = false; + if ($daykey > $event->date_end_in_calendar) { + $loop = false; + } } while ($loop); //print 'Event '.$i.' id='.$event->id.' (start='.dol_print_date($event->datep).'-end='.dol_print_date($event->datef); @@ -767,15 +850,13 @@ if ($resql) // BIRTHDATES CALENDAR // Complete $eventarray with birthdates -if ($showbirthday) -{ +if ($showbirthday) { // Add events in array $sql = 'SELECT sp.rowid, sp.lastname, sp.firstname, sp.birthday'; $sql .= ' FROM '.MAIN_DB_PREFIX.'socpeople as sp'; $sql .= ' WHERE (priv=0 OR (priv=1 AND fk_user_creat='.$user->id.'))'; $sql .= " AND sp.entity IN (".getEntity('socpeople').")"; - if ($action == 'show_day') - { + if ($action == 'show_day') { $sql .= ' AND MONTH(birthday) = '.$month; $sql .= ' AND DAY(birthday) = '.$day; } else { @@ -785,12 +866,10 @@ if ($showbirthday) dol_syslog("comm/action/index.php", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $event = new ActionComm($db); @@ -859,13 +938,11 @@ if ($action == 'show_day') { } $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $event = new ActionComm($db); @@ -885,21 +962,17 @@ if ($resql) $event->date_start_in_calendar = $event->datep; $event->date_end_in_calendar = $event->datef; - if ($obj->status == 3) - { + if ($obj->status == 3) { // Show no symbol for leave with state "leave approved" $event->percentage = -1; - } elseif ($obj->status == 2) - { + } elseif ($obj->status == 2) { // Show TO-DO symbol for leave with state "leave wait for approval" $event->percentage = 0; } - if ($obj->halfday == 1) - { + if ($obj->halfday == 1) { $event->label = $obj->lastname.' ('.$langs->trans("Morning").')'; - } elseif ($obj->halfday == -1) - { + } elseif ($obj->halfday == -1) { $event->label = $obj->lastname.' ('.$langs->trans("Afternoon").')'; } else { $event->label = $obj->lastname; @@ -923,11 +996,9 @@ if ($resql) // EXTERNAL CALENDAR // Complete $eventarray with external import Ical -if (count($listofextcals)) -{ +if (count($listofextcals)) { require_once DOL_DOCUMENT_ROOT.'/comm/action/class/ical.class.php'; - foreach ($listofextcals as $extcal) - { + foreach ($listofextcals as $extcal) { $url = $extcal['src']; // Example: https://www.google.com/calendar/ical/eldy10%40gmail.com/private-cde92aa7d7e0ef6110010a821a2aaeb/basic.ics $namecal = $extcal['name']; $offsettz = $extcal['offsettz']; @@ -940,29 +1011,27 @@ if (count($listofextcals)) // After this $ical->cal['VEVENT'] contains array of events, $ical->cal['DAYLIGHT'] contains daylight info, $ical->cal['STANDARD'] contains non daylight info, ... //var_dump($ical->cal); exit; $icalevents = array(); - if (is_array($ical->get_event_list())) $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] - if (is_array($ical->get_freebusy_list())) $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] + if (is_array($ical->get_event_list())) { + $icalevents = array_merge($icalevents, $ical->get_event_list()); // Add $ical->cal['VEVENT'] + } + if (is_array($ical->get_freebusy_list())) { + $icalevents = array_merge($icalevents, $ical->get_freebusy_list()); // Add $ical->cal['VFREEBUSY'] + } - if (count($icalevents) > 0) - { + if (count($icalevents) > 0) { // Duplicate all repeatable events into new entries $moreicalevents = array(); - foreach ($icalevents as $icalevent) - { - if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) //repeatable event - { + foreach ($icalevents as $icalevent) { + if (isset($icalevent['RRULE']) && is_array($icalevent['RRULE'])) { //repeatable event //if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar=$firstdaytoshow; //if ($event->date_end_in_calendar > $lastdaytoshow) $event->date_end_in_calendar=($lastdaytoshow-1); - if ($icalevent['DTSTART;VALUE=DATE']) //fullday event - { + if ($icalevent['DTSTART;VALUE=DATE']) { //fullday event $datecurstart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); $datecurend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day - } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime'])) - { + } elseif (is_array($icalevent['DTSTART']) && !empty($icalevent['DTSTART']['unixtime'])) { $datecurstart = $icalevent['DTSTART']['unixtime']; $datecurend = $icalevent['DTEND']['unixtime']; - if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) - { + if (!empty($ical->cal['DAYLIGHT']['DTSTART']) && $datecurstart) { //var_dump($ical->cal); $tmpcurstart = $datecurstart; $tmpcurend = $datecurend; @@ -970,10 +1039,16 @@ if (count($listofextcals)) $tmpdaylightend = dol_mktime(0, 0, 0, 1, 1, 1970, 1) + (int) $ical->cal['STANDARD']['DTSTART']; //var_dump($tmpcurstart);var_dump($tmpcurend); var_dump($ical->cal['DAYLIGHT']['DTSTART']);var_dump($ical->cal['STANDARD']['DTSTART']); // Edit datecurstart and datecurend - if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; - else $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; - if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; - else $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + if ($tmpcurstart >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) { + $datecurstart -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; + } else { + $datecurstart -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + } + if ($tmpcurend >= $tmpdaylightstart && $tmpcurstart < $tmpdaylightend) { + $datecurend -= ((int) $ical->cal['DAYLIGHT']['TZOFFSETTO']) * 36; + } else { + $datecurend -= ((int) $ical->cal['STANDARD']['TZOFFSETTO']) * 36; + } } // datecurstart and datecurend are now GMT date //var_dump($datecurstart); var_dump($datecurend); exit; @@ -987,18 +1062,19 @@ if (count($listofextcals)) $interval = (empty($icalevent['RRULE']['INTERVAL']) ? 1 : $icalevent['RRULE']['INTERVAL']); $until = empty($icalevent['RRULE']['UNTIL']) ? 0 : dol_stringtotime($icalevent['RRULE']['UNTIL'], 1); $maxrepeat = empty($icalevent['RRULE']['COUNT']) ? 0 : $icalevent['RRULE']['COUNT']; - if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) continue; // We discard repeatable event that end before start date to show - if ($datecurstart >= $lastdaytoshow) continue; // We discard repeatable event that start after end date to show + if ($until && ($until + ($datecurend - $datecurstart)) < $firstdaytoshow) { + continue; // We discard repeatable event that end before start date to show + } + if ($datecurstart >= $lastdaytoshow) { + continue; // We discard repeatable event that start after end date to show + } $numofevent = 0; - while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) - { - if ($datecurend >= $firstdaytoshow) // We add event - { + while (($datecurstart < $lastdaytoshow) && (empty($maxrepeat) || ($numofevent < $maxrepeat))) { + if ($datecurend >= $firstdaytoshow) { // We add event $newevent = $icalevent; unset($newevent['RRULE']); - if ($icalevent['DTSTART;VALUE=DATE']) - { + if ($icalevent['DTSTART;VALUE=DATE']) { $newevent['DTSTART;VALUE=DATE'] = dol_print_date($datecurstart, '%Y%m%d'); $newevent['DTEND;VALUE=DATE'] = dol_print_date($datecurend + 1, '%Y%m%d'); } else { @@ -1010,27 +1086,22 @@ if (count($listofextcals)) // Jump on next occurence $numofevent++; $savdatecurstart = $datecurstart; - if ($icalevent['RRULE']['FREQ'] == 'DAILY') - { + if ($icalevent['RRULE']['FREQ'] == 'DAILY') { $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'd'); $datecurend = dol_time_plus_duree($datecurend, $interval, 'd'); } - if ($icalevent['RRULE']['FREQ'] == 'WEEKLY') - { + if ($icalevent['RRULE']['FREQ'] == 'WEEKLY') { $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'w'); $datecurend = dol_time_plus_duree($datecurend, $interval, 'w'); - } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY') - { + } elseif ($icalevent['RRULE']['FREQ'] == 'MONTHLY') { $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'm'); $datecurend = dol_time_plus_duree($datecurend, $interval, 'm'); - } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY') - { + } elseif ($icalevent['RRULE']['FREQ'] == 'YEARLY') { $datecurstart = dol_time_plus_duree($datecurstart, $interval, 'y'); $datecurend = dol_time_plus_duree($datecurend, $interval, 'y'); } // Test to avoid infinite loop ($datecurstart must increase) - if ($savdatecurstart >= $datecurstart) - { + if ($savdatecurstart >= $datecurstart) { dol_syslog("Found a rule freq ".$icalevent['RRULE']['FREQ']." not managed by dolibarr code. Assume 1 week frequency.", LOG_ERR); $datecurstart += 3600 * 24 * 7; $datecurend += 3600 * 24 * 7; @@ -1041,18 +1112,18 @@ if (count($listofextcals)) $icalevents = array_merge($icalevents, $moreicalevents); // Loop on each entry into cal file to know if entry is qualified and add an ActionComm into $eventarray - foreach ($icalevents as $icalevent) - { + foreach ($icalevents as $icalevent) { //var_dump($icalevent); //print $icalevent['SUMMARY'].'->'.var_dump($icalevent).'
';exit; - if (!empty($icalevent['RRULE'])) continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule. + if (!empty($icalevent['RRULE'])) { + continue; // We found a repeatable event. It was already split into unitary events, so we discard general rule. + } // Create a new object action $event = new ActionComm($db); $addevent = false; - if (isset($icalevent['DTSTART;VALUE=DATE'])) // fullday event - { + if (isset($icalevent['DTSTART;VALUE=DATE'])) { // fullday event // For full day events, date are also GMT but they wont but converted using tz during output $datestart = dol_stringtotime($icalevent['DTSTART;VALUE=DATE'], 1); $dateend = dol_stringtotime($icalevent['DTEND;VALUE=DATE'], 1) - 1; // We remove one second to get last second of day @@ -1060,8 +1131,7 @@ if (count($listofextcals)) //print dol_print_date($dateend,'dayhour','gmt'); $event->fulldayevent = 1; $addevent = true; - } elseif (!is_array($icalevent['DTSTART'])) // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch) - { + } elseif (!is_array($icalevent['DTSTART'])) { // not fullday event (DTSTART is not array. It is a value like '19700101T000000Z' for 00:00 in greenwitch) $datestart = $icalevent['DTSTART']; $dateend = $icalevent['DTEND']; @@ -1071,8 +1141,7 @@ if (count($listofextcals)) $addevent = true; //var_dump($offsettz); //var_dump(dol_print_date($datestart, 'dayhour', 'gmt')); - } elseif (isset($icalevent['DTSTART']['unixtime'])) // File contains a local timezone + a TZ (for example when using bluemind) - { + } elseif (isset($icalevent['DTSTART']['unixtime'])) { // File contains a local timezone + a TZ (for example when using bluemind) $datestart = $icalevent['DTSTART']['unixtime']; $dateend = $icalevent['DTEND']['unixtime']; @@ -1080,13 +1149,11 @@ if (count($listofextcals)) $dateend += +($offsettz * 3600); // $buggedfile is set to uselocalandtznodaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtznodaylight' - if ($buggedfile === 'uselocalandtznodaylight') // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2 - { + if ($buggedfile === 'uselocalandtznodaylight') { // unixtime is a local date that does not take daylight into account, TZID is +1 for example for 'Europe/Paris' in summer instead of 2 // TODO } // $buggedfile is set to uselocalandtzdaylight if conf->global->AGENDA_EXT_BUGGEDFILEx = 'uselocalandtzdaylight' (for example with bluemind) - if ($buggedfile === 'uselocalandtzdaylight') // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer - { + if ($buggedfile === 'uselocalandtzdaylight') { // unixtime is a local date that does take daylight into account, TZID is +2 for example for 'Europe/Paris' in summer $localtzs = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTSTART']['TZID'])); $localtze = new DateTimeZone(preg_replace('/"/', '', $icalevent['DTEND']['TZID'])); $localdts = new DateTime(dol_print_date($datestart, 'dayrfc', 'gmt'), $localtzs); @@ -1100,13 +1167,11 @@ if (count($listofextcals)) $addevent = true; } - if ($addevent) - { + if ($addevent) { $event->id = $icalevent['UID']; $event->ref = $event->id; $userId = $userstatic->findUserIdByEmail($namecal); - if (!empty($userId) && $userId > 0) - { + if (!empty($userId) && $userId > 0) { $event->userassigned[$userId] = $userId; $event->percentage = -1; } @@ -1123,21 +1188,30 @@ if (count($listofextcals)) $event->datep = $datestart + $usertime; $event->datef = $dateend + $usertime; - if ($icalevent['SUMMARY']) $event->label = $icalevent['SUMMARY']; - elseif ($icalevent['DESCRIPTION']) $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); - else $event->label = $langs->trans("ExtSiteNoLabel"); + if ($icalevent['SUMMARY']) { + $event->label = $icalevent['SUMMARY']; + } elseif ($icalevent['DESCRIPTION']) { + $event->label = dol_nl2br($icalevent['DESCRIPTION'], 1); + } else { + $event->label = $langs->trans("ExtSiteNoLabel"); + } // Priority (see https://www.kanzaki.com/docs/ical/priority.html) // LOW = 0 to 4 // MEDIUM = 5 // HIGH = 6 to 9 - if ($icalevent['PRIORITY']) $event->priority = $icalevent['PRIORITY']; + if ($icalevent['PRIORITY']) { + $event->priority = $icalevent['PRIORITY']; + } // Transparency (see https://www.kanzaki.com/docs/ical/transp.html) - if ($icalevent['TRANSP']) - { - if ($icalevent['TRANSP'] == "TRANSPARENT") $event->transparency = 0; // 0 = available / free - if ($icalevent['TRANSP'] == "OPAQUE") $event->transparency = 1; // 1 = busy + if ($icalevent['TRANSP']) { + if ($icalevent['TRANSP'] == "TRANSPARENT") { + $event->transparency = 0; // 0 = available / free + } + if ($icalevent['TRANSP'] == "OPAQUE") { + $event->transparency = 1; // 1 = busy + } // TODO: MS outlook states // X-MICROSOFT-CDO-BUSYSTATUS:FREE + TRANSP:TRANSPARENT => Available / Free @@ -1147,30 +1221,37 @@ if (count($listofextcals)) // X-MICROSOFT-CDO-BUSYSTATUS:OOF + TRANSP:OPAQUE => Away from the office / off-site } - if ($icalevent['LOCATION']) $event->location = $icalevent['LOCATION']; + if ($icalevent['LOCATION']) { + $event->location = $icalevent['LOCATION']; + } $event->date_start_in_calendar = $event->datep; - if ($event->datef != '' && $event->datef >= $event->datep) $event->date_end_in_calendar = $event->datef; - else $event->date_end_in_calendar = $event->datep; + if ($event->datef != '' && $event->datef >= $event->datep) { + $event->date_end_in_calendar = $event->datef; + } else { + $event->date_end_in_calendar = $event->datep; + } // Define ponctual property - if ($event->date_start_in_calendar == $event->date_end_in_calendar) - { + if ($event->date_start_in_calendar == $event->date_end_in_calendar) { $event->ponctuel = 1; //print 'x'.$datestart.'-'.$dateend;exit; } // Add event into $eventarray if date range are ok. - if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) - { + if ($event->date_end_in_calendar < $firstdaytoshow || $event->date_start_in_calendar >= $lastdaytoshow) { //print 'x'.$datestart.'-'.$dateend;exit; //print 'x'.$datestart.'-'.$dateend;exit; //print 'x'.$datestart.'-'.$dateend;exit; // This record is out of visible range } else { - if ($event->date_start_in_calendar < $firstdaytoshow) $event->date_start_in_calendar = $firstdaytoshow; - if ($event->date_end_in_calendar >= $lastdaytoshow) $event->date_end_in_calendar = ($lastdaytoshow - 1); + if ($event->date_start_in_calendar < $firstdaytoshow) { + $event->date_start_in_calendar = $firstdaytoshow; + } + if ($event->date_end_in_calendar >= $lastdaytoshow) { + $event->date_end_in_calendar = ($lastdaytoshow - 1); + } // Add an entry in actionarray for each day $daycursor = $event->date_start_in_calendar; @@ -1187,7 +1268,9 @@ if (count($listofextcals)) //if ($event->fulldayevent) print dol_print_date($daykeygmt,'dayhour','gmt').'-'.dol_print_date($daykey,'dayhour','gmt').'-'.dol_print_date($event->date_end_in_calendar,'dayhour','gmt').' '; $eventarray[$daykey][] = $event; $daykey += 60 * 60 * 24; $daykeygmt += 60 * 60 * 24; // Add one day - if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) $loop = false; + if (($event->fulldayevent ? $daykeygmt : $daykey) > $event->date_end_in_calendar) { + $loop = false; + } } while ($loop); } } @@ -1211,8 +1294,7 @@ if (!empty($hookmanager->resArray['eventarray'])) { } // Sort events -foreach ($eventarray as $keyDate => &$dateeventarray) -{ +foreach ($eventarray as $keyDate => &$dateeventarray) { usort($dateeventarray, 'sort_events_by_date'); } @@ -1224,11 +1306,12 @@ $cacheusers = array(); // Define theme_datacolor array $color_file = DOL_DOCUMENT_ROOT."/theme/".$conf->theme."/theme_vars.inc.php"; -if (is_readable($color_file)) -{ +if (is_readable($color_file)) { include_once $color_file; } -if (!is_array($theme_datacolor)) $theme_datacolor = array(array(120, 130, 150), array(200, 160, 180), array(190, 190, 220)); +if (!is_array($theme_datacolor)) { + $theme_datacolor = array(array(120, 130, 150), array(200, 160, 180), array(190, 190, 220)); +} $massactionbutton =''; @@ -1238,8 +1321,7 @@ print_barre_liste($langs->trans("Agenda"), $page, $_SERVER["PHP_SELF"], $param, print $s; -if (empty($action) || $action == 'show_month') // View by month -{ +if (empty($action) || $action == 'show_month') { // View by month $newparam = $param; // newparam is for birthday links $newparam = preg_replace('/showbirthday=/i', 'showbirthday_=', $newparam); // To avoid replacement when replace day= is done $newparam = preg_replace('/action=show_month&?/i', '', $newparam); @@ -1261,15 +1343,15 @@ if (empty($action) || $action == 'show_month') // View by month // Column title of weeks numbers echo '
#'; $numdayinweek = (($i + (isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1)) % 7); - if (!empty($conf->dol_optimize_smallscreen)) - { + if (!empty($conf->dol_optimize_smallscreen)) { $labelshort = array(0=>'SundayMin', 1=>'MondayMin', 2=>'TuesdayMin', 3=>'WednesdayMin', 4=>'ThursdayMin', 5=>'FridayMin', 6=>'SaturdayMin'); print $langs->trans($labelshort[$numdayinweek]); - } else print $langs->trans("Day".$numdayinweek); + } else { + print $langs->trans("Day".$numdayinweek); + } print '
'; show_day_events($db, $max_day_in_prev_month + $tmpday, $prev_month, $prev_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); echo " '; show_day_events($db, $tmpday, $month, $year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); @@ -1324,7 +1412,9 @@ if (empty($action) || $action == 'show_month') // View by month } else { /* Show days after the current month (next month) */ $style = 'cal_other_month'; - if ($iter_day == 6) $style .= ' cal_other_month_right'; + if ($iter_day == 6) { + $style .= ' cal_other_month_right'; + } echo ' '; show_day_events($db, $tmpday - $max_day_in_month, $next_month, $next_year, $month, $style, $eventarray, $maxprint, $maxnbofchar, $newparam); echo "'; show_day_events($db, $tmpday, $tmpmonth, $tmpyear, $month, $style, $eventarray, 0, $maxnbofchar, $newparam, 1, 300); @@ -1406,7 +1502,9 @@ if (empty($action) || $action == 'show_month') // View by month $style = 'cal_current_month cal_current_month_oneday'; $today = 0; $todayarray = dol_getdate($now, 'fast'); - if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) $today = 1; + if ($todayarray['mday'] == $day && $todayarray['mon'] == $month && $todayarray['year'] == $year) { + $today = 1; + } //if ($today) $style='cal_today'; $timestamp = dol_mktime(12, 0, 0, $month, $day, $year); @@ -1424,12 +1522,12 @@ if (empty($action) || $action == 'show_month') // View by month echo "
'; @@ -1437,8 +1535,7 @@ if (empty($action) || $action == 'show_month') // View by month /* WIP View per hour */ $useviewhour = 0; - if ($useviewhour) - { + if ($useviewhour) { print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table $maxheightwin = (isset($_SESSION["dol_screenheight"]) && $_SESSION["dol_screenheight"] > 500) ? ($_SESSION["dol_screenheight"] - 200) : 660; // Also into index.php file @@ -1451,14 +1548,19 @@ if (empty($action) || $action == 'show_month') // View by month $tmp = explode('-', $conf->global->MAIN_DEFAULT_WORKING_HOURS); $minhour = round($tmp[0], 0); $maxhour = round($tmp[1], 0); - if ($minhour > 23) $minhour = 23; - if ($maxhour < 1) $maxhour = 1; - if ($maxhour <= $minhour) { $maxhour = $minhour + 1; } + if ($minhour > 23) { + $minhour = 23; + } + if ($maxhour < 1) { + $maxhour = 1; + } + if ($maxhour <= $minhour) { + $maxhour = $minhour + 1; + } $i = 0; $j = 0; - while ($i < 24) - { + while ($i < 24) { echo '
'."\n"; echo '
'.dol_print_date($i * 3600, 'hour', 'gmt').'
'; echo '
'."\n"; @@ -1524,8 +1626,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $curtime = dol_mktime(0, 0, 0, $month, $day, $year); $urltoshow = DOL_URL_ROOT.'/comm/action/index.php?action=show_day&day='.str_pad($day, 2, "0", STR_PAD_LEFT).'&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year.$newparam; $urltocreate = ''; - if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) - { + if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) { $newparam .= '&month='.str_pad($month, 2, "0", STR_PAD_LEFT).'&year='.$year; $hourminsec = '100000'; $urltocreate = DOL_URL_ROOT.'/comm/action/card.php?action=create&datep='.sprintf("%04d%02d%02d", $year, $month, $day).$hourminsec.'&backtopage='.urlencode($_SERVER["PHP_SELF"].($newparam ? '?'.$newparam : '')); @@ -1534,16 +1635,17 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa // Line with title of day print '
'."\n"; - if ($nonew <= 0) - { + if ($nonew <= 0) { print '
'; - if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) - { + if ($user->rights->agenda->myactions->create || $user->rights->agenda->allactions->create) { print ''; // Explicit link, usefull for nojs interfaces print img_picto($langs->trans("NewAction"), 'edit_add.png'); print ''; @@ -1551,8 +1653,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '
'."\n"; } - if ($nonew < 0) - { + if ($nonew < 0) { print '
'; return; } @@ -1572,29 +1673,23 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa include_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php'; $tmpholiday = new Holiday($db); - foreach ($eventarray as $daykey => $notused) - { + foreach ($eventarray as $daykey => $notused) { $annee = dol_print_date($daykey, '%Y'); $mois = dol_print_date($daykey, '%m'); $jour = dol_print_date($daykey, '%d'); - if ($day == $jour && $month == $mois && $year == $annee) - { - foreach ($eventarray[$daykey] as $index => $event) - { - if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA)) - { + if ($day == $jour && $month == $mois && $year == $annee) { + foreach ($eventarray[$daykey] as $index => $event) { + if ($i < $maxprint || $maxprint == 0 || !empty($conf->global->MAIN_JS_SWITCH_AGENDA)) { $keysofuserassigned = array_keys($event->userassigned); $ponct = ($event->date_start_in_calendar == $event->date_end_in_calendar); // Define $color (Hex string like '0088FF') and $cssclass of event $color = -1; $cssclass = ''; $colorindex = -1; - if (in_array($user->id, $keysofuserassigned)) - { + if (in_array($user->id, $keysofuserassigned)) { $cssclass = 'family_mytasks'; - if (empty($cacheusers[$event->userownerid])) - { + if (empty($cacheusers[$event->userownerid])) { $newuser = new User($db); $newuser->fetch($event->userownerid); $cacheusers[$event->userownerid] = $newuser; @@ -1602,9 +1697,10 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa //var_dump($cacheusers[$event->userownerid]->color); // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) - if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; - } elseif ($event->type_code == 'ICALEVENT') // Event come from external ical file - { + if (!empty($cacheusers[$event->userownerid]->color)) { + $color = $cacheusers[$event->userownerid]->color; + } + } elseif ($event->type_code == 'ICALEVENT') { // Event come from external ical file $numical++; if (!empty($event->icalname)) { if (!isset($numicals[dol_string_nospecial($event->icalname)])) { @@ -1615,37 +1711,37 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $color = ($event->icalcolor ? $event->icalcolor : -1); $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); - } elseif ($event->type_code == 'BIRTHDAY') - { + } elseif ($event->type_code == 'BIRTHDAY') { $numbirthday++; $colorindex = 2; $cssclass = 'family_birthday '; $color = sprintf("%02x%02x%02x", $theme_datacolor[$colorindex][0], $theme_datacolor[$colorindex][1], $theme_datacolor[$colorindex][2]); } else { $numother++; $color = ($event->icalcolor ? $event->icalcolor : -1); $cssclass = (!empty($event->icalname) ? 'family_ext'.md5($event->icalname) : 'family_other'); - if (empty($cacheusers[$event->userownerid])) - { + if (empty($cacheusers[$event->userownerid])) { $newuser = new User($db); $newuser->fetch($event->userownerid); $cacheusers[$event->userownerid] = $newuser; } //var_dump($cacheusers[$event->userownerid]->color); - // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) - if (!empty($cacheusers[$event->userownerid]->color)) $color = $cacheusers[$event->userownerid]->color; + // We decide to choose color of owner of event (event->userownerid is user id of owner, event->userassigned contains all users assigned to event) + if (!empty($cacheusers[$event->userownerid]->color)) { + $color = $cacheusers[$event->userownerid]->color; + } } - if ($color < 0) // Color was not set on user card. Set color according to color index. - { + if ($color < 0) { // Color was not set on user card. Set color according to color index. // Define color index if not yet defined $idusertouse = ($event->userownerid ? $event->userownerid : 0); - if (isset($colorindexused[$idusertouse])) - { + if (isset($colorindexused[$idusertouse])) { $colorindex = $colorindexused[$idusertouse]; // Color already assigned to this user } else { - $colorindex = $nextindextouse; - $colorindexused[$idusertouse] = $colorindex; - if (!empty($theme_datacolor[$nextindextouse + 1])) $nextindextouse++; // Prepare to use next color + $colorindex = $nextindextouse; + $colorindexused[$idusertouse] = $colorindex; + if (!empty($theme_datacolor[$nextindextouse + 1])) { + $nextindextouse++; // Prepare to use next color + } } //print '|'.($color).'='.($idusertouse?$idusertouse:0).'='.$colorindex.'
'; // Define color @@ -1666,14 +1762,12 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $tmpyearend = date('Y', $event->date_end_in_calendar); $tmpmonthend = date('m', $event->date_end_in_calendar); $tmpdayend = date('d', $event->date_end_in_calendar); - if ($tmpyearend != $annee || $tmpmonthend != $mois || $tmpdayend != $jour) - { + if ($tmpyearend != $annee || $tmpmonthend != $mois || $tmpdayend != $jour) { $cssclass .= " unmovable"; } } else { if ($user->rights->agenda->allactions->create || - (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) - { + (($event->authorid == $user->id || $event->userownerid == $user->id) && $user->rights->agenda->myactions->create)) { $cssclass .= " movable cursormove"; } else { $cssclass .= " unmovable"; @@ -1681,8 +1775,12 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa } $h = ''; $nowrapontd = 1; - if ($action == 'show_day') { $h = 'height: 100%; '; $nowrapontd = 0; } - if ($action == 'show_week') { $h = 'height: 100%; '; $nowrapontd = 0; } + if ($action == 'show_day') { + $h = 'height: 100%; '; $nowrapontd = 0; + } + if ($action == 'show_week') { + $h = 'height: 100%; '; $nowrapontd = 0; + } // Show event box print "\n"; @@ -1720,8 +1818,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '" style="'.$h; $colortouse = $color; // If colortouse is similar than background, we force to change it. - if (empty($event->transparency) && empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) - { + if (empty($event->transparency) && empty($conf->global->AGENDA_NO_TRANSPARENT_ON_NOT_BUSY)) { print 'background: #f0f0f0;'; print 'border-left: 5px solid #'.$colortouse.';'; } else { @@ -1729,8 +1826,8 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print 'border-left: 5px solid #'.dol_color_minus($colortouse, -3).';'; //print 'background: -webkit-gradient(linear, left top, left bottom, from(#'.dol_color_minus($colortouse, -3).'), to(#'.dol_color_minus($colortouse, -1).'));'; } - //print 'background: #'.$colortouse.';'; - //print 'background: -webkit-gradient(linear, left top, left bottom, from(#'.dol_color_minus($color, -3).'), to(#'.dol_color_minus($color, -1).'));'; + //print 'background: #'.$colortouse.';'; + //print 'background: -webkit-gradient(linear, left top, left bottom, from(#'.dol_color_minus($color, -3).'), to(#'.dol_color_minus($color, -1).'));'; //if (! empty($event->transparency)) print 'background: #'.$color.'; background: -webkit-gradient(linear, left top, left bottom, from(#'.$color.'), to(#'.dol_color_minus($color,1).'));'; //else print 'background-color: transparent !important; background: none; border: 1px solid #bbb;'; //print ' -moz-border-radius:4px;"'; @@ -1759,14 +1856,12 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print $listofusertoshow; } else { // Other calendar // Picto - if (empty($event->fulldayevent)) - { + if (empty($event->fulldayevent)) { //print $event->getNomUrl(2).' '; } // Date - if (empty($event->fulldayevent)) - { + if (empty($event->fulldayevent)) { // Show hours (start ... end) $tmpyearstart = dol_print_date($event->date_start_in_calendar, '%Y', 'tzuserrel'); $tmpmonthstart = dol_print_date($event->date_start_in_calendar, '%m', 'tzuserrel'); @@ -1776,29 +1871,26 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa $tmpdayend = dol_print_date($event->date_end_in_calendar, '%d', 'tzuserrel'); // Hour start - if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) - { + if ($tmpyearstart == $annee && $tmpmonthstart == $mois && $tmpdaystart == $jour) { $daterange .= dol_print_date($event->date_start_in_calendar, 'hour', 'tzuserrel'); - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend) - $daterange .= '-'; + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) { + if ($tmpyearstart == $tmpyearend && $tmpmonthstart == $tmpmonthend && $tmpdaystart == $tmpdayend) { + $daterange .= '-'; + } //else //print '...'; } } - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend) - { + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) { + if ($tmpyearstart != $tmpyearend || $tmpmonthstart != $tmpmonthend || $tmpdaystart != $tmpdayend) { $daterange .= '...'; } } // Hour end - if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) - { - if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) - $daterange .= dol_print_date($event->date_end_in_calendar, 'hour', 'tzuserrel'); + if ($event->date_end_in_calendar && $event->date_start_in_calendar != $event->date_end_in_calendar) { + if ($tmpyearend == $annee && $tmpmonthend == $mois && $tmpdayend == $jour) { + $daterange .= dol_print_date($event->date_end_in_calendar, 'hour', 'tzuserrel'); + } } } else { if ($showinfo) { @@ -1824,9 +1916,10 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa // Loop on each assigned user $listofusertoshow = ''; $posuserassigned = 0; - foreach ($event->userassigned as $tmpid => $tmpdata) - { - if (!$posuserassigned && $titletoshow) $listofusertoshow .= '
'; + foreach ($event->userassigned as $tmpid => $tmpdata) { + if (!$posuserassigned && $titletoshow) { + $listofusertoshow .= '
'; + } $posuserassigned++; if (empty($cacheusers[$tmpid])) { $newuser = new User($db); @@ -1840,48 +1933,57 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print $titletoshow; print $listofusertoshow; - if ($event->type_code == 'ICALEVENT') print '
('.dol_trunc($event->icalname, $maxnbofchar).')'; + if ($event->type_code == 'ICALEVENT') { + print '
('.dol_trunc($event->icalname, $maxnbofchar).')'; + } $thirdparty_id = ($event->thirdparty_id > 0 ? $event->thirdparty_id : ((is_object($event->societe) && $event->societe->id > 0) ? $event->societe->id : 0)); $contact_id = ($event->contact_id > 0 ? $event->contact_id : ((is_object($event->contact) && $event->contact->id > 0) ? $event->contact->id : 0)); // If action related to company / contact $linerelatedto = ''; - if ($thirdparty_id > 0) - { - if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id])) - { + if ($thirdparty_id > 0) { + if (!isset($cachethirdparties[$thirdparty_id]) || !is_object($cachethirdparties[$thirdparty_id])) { $thirdparty = new Societe($db); $thirdparty->fetch($thirdparty_id); $cachethirdparties[$thirdparty_id] = $thirdparty; - } else $thirdparty = $cachethirdparties[$thirdparty_id]; - if (!empty($thirdparty->id)) $linerelatedto .= $thirdparty->getNomUrl(1, '', 0); + } else { + $thirdparty = $cachethirdparties[$thirdparty_id]; + } + if (!empty($thirdparty->id)) { + $linerelatedto .= $thirdparty->getNomUrl(1, '', 0); + } } - if (!empty($contact_id) && $contact_id > 0) - { - if (!is_object($cachecontacts[$contact_id])) - { + if (!empty($contact_id) && $contact_id > 0) { + if (!is_object($cachecontacts[$contact_id])) { $contact = new Contact($db); $contact->fetch($contact_id); $cachecontacts[$contact_id] = $contact; - } else $contact = $cachecontacts[$contact_id]; - if ($linerelatedto) $linerelatedto .= ' '; - if (!empty($contact->id)) $linerelatedto .= $contact->getNomUrl(1, '', 0); + } else { + $contact = $cachecontacts[$contact_id]; + } + if ($linerelatedto) { + $linerelatedto .= ' '; + } + if (!empty($contact->id)) { + $linerelatedto .= $contact->getNomUrl(1, '', 0); + } } - if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) - { + if (!empty($event->fk_element) && $event->fk_element > 0 && !empty($event->elementtype) && !empty($conf->global->AGENDA_SHOW_LINKED_OBJECT)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; - if ($linerelatedto) $linerelatedto .= '
'; + if ($linerelatedto) { + $linerelatedto .= '
'; + } $linerelatedto .= dolGetElementUrl($event->fk_element, $event->elementtype, 1); } - if ($linerelatedto) print '
'.$linerelatedto; + if ($linerelatedto) { + print '
'.$linerelatedto; + } } // Show location - if ($showinfo) - { - if ($event->location) - { + if ($showinfo) { + if ($event->location) { print '
'; print $langs->trans("Location").': '.$event->location; } @@ -1890,14 +1992,18 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print '
'; - if ($withstatus) print $event->getLibStatut(3, 1); - else print ' '; + if ($withstatus) { + print $event->getLibStatut(3, 1); + } else { + print ' '; + } print '
'; print ''."\n"; @@ -1923,8 +2029,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa print ' '; } - if (!empty($conf->global->MAIN_JS_SWITCH_AGENDA) && $itoshow > $ireallyshown && $maxprint) - { + if (!empty($conf->global->MAIN_JS_SWITCH_AGENDA) && $itoshow > $ireallyshown && $maxprint) { print '
'.img_picto("All", "angle-double-down", 'class="warning"').' +'.($itoshow - $ireallyshown).'
'; //print ' +'.(count($eventarray[$daykey])-$maxprint); @@ -1963,8 +2068,7 @@ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventa function dol_color_minus($color, $minus, $minusunit = 16) { $newcolor = $color; - if ($minusunit == 16) - { + if ($minusunit == 16) { $newcolor[0] = dechex(max(min(hexdec($newcolor[0]) - $minus, 15), 0)); $newcolor[2] = dechex(max(min(hexdec($newcolor[2]) - $minus, 15), 0)); $newcolor[4] = dechex(max(min(hexdec($newcolor[4]) - $minus, 15), 0)); @@ -1984,12 +2088,10 @@ function dol_color_minus($color, $minus, $minusunit = 16) function sort_events_by_date($a, $b) { // Sort holidays at first - if ($a->type_code === 'HOLIDAY') - { + if ($a->type_code === 'HOLIDAY') { return -1; } - if ($b->type_code === 'HOLIDAY') - { + if ($b->type_code === 'HOLIDAY') { return 1; } @@ -1997,20 +2099,17 @@ function sort_events_by_date($a, $b) // datef => Event end time // Events have different start time - if ($a->datep !== $b->datep) - { + if ($a->datep !== $b->datep) { return $a->datep - $b->datep; } // Events have same start time and no end time - if ((!is_numeric($b->datef)) || (!is_numeric($a->datef))) - { + if ((!is_numeric($b->datef)) || (!is_numeric($a->datef))) { return sort_events_by_percentage($a, $b); } // Events have the same start time and same end time - if ($b->datef === $a->datef) - { + if ($b->datef === $a->datef) { return sort_events_by_percentage($a, $b); } @@ -2030,13 +2129,11 @@ function sort_events_by_percentage($a, $b) // Sort events with no percentage before each other // (usefull to sort holidays, sick days or similar on the top) - if ($a->percentage < 0) - { + if ($a->percentage < 0) { return -1; } - if ($b->percentage < 0) - { + if ($b->percentage < 0) { return 1; } diff --git a/htdocs/comm/action/info.php b/htdocs/comm/action/info.php index 40787abb8c3..2360f2925d9 100644 --- a/htdocs/comm/action/info.php +++ b/htdocs/comm/action/info.php @@ -39,8 +39,7 @@ $langs->load("commercial"); $id = GETPOST('id', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -84,8 +83,7 @@ $morehtmlref = '
'; // Thirdparty //$morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); //$morehtmlref.='
'.$langs->trans('Project') . ' '; $morehtmlref .= $langs->trans('Project').': '; @@ -95,7 +93,9 @@ if (!empty($conf->projet->enabled)) $morehtmlref .= '
'; $morehtmlref .= $proj->ref; $morehtmlref .= ''; - if ($proj->title) $morehtmlref .= ' - '.$proj->title; + if ($proj->title) { + $morehtmlref .= ' - '.$proj->title; + } } else { $morehtmlref .= ''; } diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php index 68925c57bfa..64ed79d87ca 100644 --- a/htdocs/comm/action/list.php +++ b/htdocs/comm/action/list.php @@ -27,7 +27,9 @@ * \brief Page to list actions */ -if (!defined("NOREDIRECTBYMAINTOLOGIN")) define('NOREDIRECTBYMAINTOLOGIN', 1); +if (!defined("NOREDIRECTBYMAINTOLOGIN")) { + define('NOREDIRECTBYMAINTOLOGIN', 1); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; @@ -55,14 +57,17 @@ $toselect = GETPOST('toselect', 'array'); $confirm = GETPOST('confirm', 'alpha'); // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) -if (GETPOST('search_actioncode', 'array')) -{ +if (GETPOST('search_actioncode', 'array')) { $actioncode = GETPOST('search_actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + if (!count($actioncode)) { + $actioncode = '0'; + } } else { $actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE)); } -if ($actioncode == '' && empty($actioncodearray)) $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); +if ($actioncode == '' && empty($actioncodearray)) { + $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); +} $search_id = GETPOST('search_id', 'alpha'); $search_title = GETPOST('search_title', 'alpha'); $search_note = GETPOST('search_note', 'alpha'); @@ -70,8 +75,12 @@ $search_note = GETPOST('search_note', 'alpha'); $dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int'), 'tzuserrel'); $datestart = dol_mktime(0, 0, 0, GETPOST('datestartmonth', 'int'), GETPOST('datestartday', 'int'), GETPOST('datestartyear', 'int'), 'tzuserrel'); $dateend = dol_mktime(0, 0, 0, GETPOST('dateendmonth', 'int'), GETPOST('dateendday', 'int'), GETPOST('dateendyear', 'int'), 'tzuserrel'); -if ($search_status == '' && !GETPOSTISSET('search_status')) $search_status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); -if (empty($action) && !GETPOSTISSET('action')) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); +if ($search_status == '' && !GETPOSTISSET('search_status')) { + $search_status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); +} +if (empty($action) && !GETPOSTISSET('action')) { + $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); +} $filter = GETPOST("search_filter", 'alpha', 3) ?GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3); $filtert = GETPOST("search_filtert", "int", 3) ?GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3); @@ -89,8 +98,7 @@ $extrafields->fetch_name_optionals_label($object->table_element); $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); // If not choice done on calendar owner, we filter on user. -if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) -{ +if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) { $filtert = $user->id; } @@ -98,30 +106,41 @@ $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 ($page == -1 || $page == null) { $page = 0; } -$offset = $limit * $page; -if (!$sortorder) -{ - $sortorder = "DESC,DESC"; - if ($search_status == 'todo') $sortorder = "DESC,DESC"; +if ($page == -1 || $page == null) { + $page = 0; } -if (!$sortfield) -{ +$offset = $limit * $page; +if (!$sortorder) { + $sortorder = "DESC,DESC"; + if ($search_status == 'todo') { + $sortorder = "DESC,DESC"; + } +} +if (!$sortfield) { $sortfield = "a.datep,a.id"; - if ($search_status == 'todo') $sortfield = "a.datep,a.id"; + if ($search_status == 'todo') { + $sortfield = "a.datep,a.id"; + } } // Security check $socid = GETPOST("search_socid", 'int') ?GETPOST("search_socid", 'int') : GETPOST("socid", 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'agenda', 0, '', 'myactions'); -if ($socid < 0) $socid = ''; +if ($socid < 0) { + $socid = ''; +} $canedit = 1; -if (!$user->rights->agenda->myactions->read) accessforbidden(); -if (!$user->rights->agenda->allactions->read) $canedit = 0; -if (!$user->rights->agenda->allactions->read || $filter == 'mine') // If no permission to see all, we show only affected to me -{ +if (!$user->rights->agenda->myactions->read) { + accessforbidden(); +} +if (!$user->rights->agenda->allactions->read) { + $canedit = 0; +} +if (!$user->rights->agenda->allactions->read || $filter == 'mine') { // If no permission to see all, we show only affected to me $filtert = $user->id; } @@ -152,18 +171,14 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) -{ +if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) -{ +if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) { $param = ''; - if (is_array($_POST)) - { - foreach ($_POST as $key => $val) - { + if (is_array($_POST)) { + foreach ($_POST as $key => $val) { $param .= '&'.$key.'='.urlencode($val); } } @@ -174,13 +189,14 @@ if (GETPOST("viewcal") || GETPOST("viewweek") || GETPOST("viewday")) $parameters = array('id'=>$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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers //$actioncode=''; $search_id = ''; $search_title = ''; @@ -192,12 +208,10 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_array_options = array(); } -if (empty($reshook) && !empty($massaction)) -{ +if (empty($reshook) && !empty($massaction)) { unset($percent); - switch ($massaction) - { + switch ($massaction) { case 'set_all_events_to_todo': $percent = ActionComm::EVENT_TODO; break; @@ -211,13 +225,10 @@ if (empty($reshook) && !empty($massaction)) break; } - if (isset($percent)) - { - foreach ($toselect as $toselectid) - { + if (isset($percent)) { + foreach ($toselect as $toselectid) { $result = $object->updatePercent($toselectid, $percent); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db); break; } @@ -226,8 +237,7 @@ if (empty($reshook) && !empty($massaction)) } // As mass deletion happens with a confirm step, $massaction is not use for the final step (deletion). -if (empty($reshook)) -{ +if (empty($reshook)) { $objectclass = 'ActionComm'; $objectlabel = 'Events'; $uploaddir = true; @@ -258,32 +268,78 @@ llxHeader('', $langs->trans("Agenda"), $help_url); $listofextcals = array(); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} if ($actioncode != '') { if (is_array($actioncode)) { - foreach ($actioncode as $str_action) $param .= "&search_actioncode[]=".urlencode($str_action); - } else $param .= "&search_actioncode=".urlencode($actioncode); + foreach ($actioncode as $str_action) { + $param .= "&search_actioncode[]=".urlencode($str_action); + } + } else { + $param .= "&search_actioncode=".urlencode($actioncode); + } +} +if ($resourceid > 0) { + $param .= "&search_resourceid=".urlencode($resourceid); +} +if ($search_status != '' && $search_status > -1) { + $param .= "&search_status=".urlencode($search_status); +} +if ($filter) { + $param .= "&search_filter=".urlencode($filter); +} +if ($filtert) { + $param .= "&search_filtert=".urlencode($filtert); +} +if ($usergroup > 0) { + $param .= "&search_usergroup=".urlencode($usergroup); +} +if ($socid > 0) { + $param .= "&search_socid=".urlencode($socid); +} +if ($showbirthday) { + $param .= "&search_showbirthday=1"; +} +if ($pid) { + $param .= "&search_projectid=".urlencode($pid); +} +if ($type) { + $param .= "&search_type=".urlencode($type); +} +if ($search_id != '') { + $param .= '&search_title='.urlencode($search_id); +} +if ($search_title != '') { + $param .= '&search_title='.urlencode($search_title); +} +if ($search_note != '') { + $param .= '&search_note='.$search_note; +} +if (GETPOST('datestartday', 'int')) { + $param .= '&datestartday='.GETPOST('datestartday', 'int'); +} +if (GETPOST('datestartmonth', 'int')) { + $param .= '&datestartmonth='.GETPOST('datestartmonth', 'int'); +} +if (GETPOST('datestartyear', 'int')) { + $param .= '&datestartyear='.GETPOST('datestartyear', 'int'); +} +if (GETPOST('dateendday', 'int')) { + $param .= '&dateendday='.GETPOST('dateendday', 'int'); +} +if (GETPOST('dateendmonth', 'int')) { + $param .= '&dateendmonth='.GETPOST('dateendmonth', 'int'); +} +if (GETPOST('dateendyear', 'int')) { + $param .= '&dateendyear='.GETPOST('dateendyear', 'int'); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); } -if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid); -if ($search_status != '' && $search_status > -1) $param .= "&search_status=".urlencode($search_status); -if ($filter) $param .= "&search_filter=".urlencode($filter); -if ($filtert) $param .= "&search_filtert=".urlencode($filtert); -if ($usergroup > 0) $param .= "&search_usergroup=".urlencode($usergroup); -if ($socid > 0) $param .= "&search_socid=".urlencode($socid); -if ($showbirthday) $param .= "&search_showbirthday=1"; -if ($pid) $param .= "&search_projectid=".urlencode($pid); -if ($type) $param .= "&search_type=".urlencode($type); -if ($search_id != '') $param .= '&search_title='.urlencode($search_id); -if ($search_title != '') $param .= '&search_title='.urlencode($search_title); -if ($search_note != '') $param .= '&search_note='.$search_note; -if (GETPOST('datestartday', 'int')) $param .= '&datestartday='.GETPOST('datestartday', 'int'); -if (GETPOST('datestartmonth', 'int')) $param .= '&datestartmonth='.GETPOST('datestartmonth', 'int'); -if (GETPOST('datestartyear', 'int')) $param .= '&datestartyear='.GETPOST('datestartyear', 'int'); -if (GETPOST('dateendday', 'int')) $param .= '&dateendday='.GETPOST('dateendday', 'int'); -if (GETPOST('dateendmonth', 'int')) $param .= '&dateendmonth='.GETPOST('dateendmonth', 'int'); -if (GETPOST('dateendyear', 'int')) $param .= '&dateendyear='.GETPOST('dateendyear', 'int'); -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -295,16 +351,21 @@ $arrayofmassactions = array( 'set_all_events_to_in_progress' => $langs->trans("SetAllEventsToInProgress"), 'set_all_events_to_finished' => $langs->trans("SetAllEventsToFinished"), ); -if ($user->rights->agenda->allactions->delete) -{ +if ($user->rights->agenda->allactions->delete) { $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); } -if ($user->rights->agenda->myactions->create) $arrayofmassactions['preaffecttag'] = ''.$langs->trans("AffectTag"); -if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) $arrayofmassactions = array(); +if ($user->rights->agenda->myactions->create) { + $arrayofmassactions['preaffecttag'] = ''.$langs->trans("AffectTag"); +} +if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete','preaffecttag'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $sql = "SELECT"; -if ($usergroup > 0) $sql .= " DISTINCT"; +if ($usergroup > 0) { + $sql .= " DISTINCT"; +} $sql .= " s.nom as societe, s.rowid as socid, s.client, s.email as socemail,"; $sql .= " a.id, a.code, a.label, a.note, a.datep as dp, a.datep2 as dp2, a.fulldayevent, a.location,"; $sql .= ' a.fk_user_author,a.fk_user_action,'; @@ -315,7 +376,9 @@ $sql .= " sp.lastname, sp.firstname, sp.email, sp.phone, sp.address, sp.phone as // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks @@ -325,34 +388,47 @@ $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm as a"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."actioncomm_extrafields as ef ON (a.id = ef.fk_object) "; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON a.fk_soc = sc.fk_soc"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON a.fk_soc = s.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."socpeople as sp ON a.fk_contact = sp.rowid"; $sql .= " ,".MAIN_DB_PREFIX."c_actioncomm as c"; // We must filter on resource table -if ($resourceid > 0) $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; +if ($resourceid > 0) { + $sql .= ", ".MAIN_DB_PREFIX."element_resources as r"; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; -if ($usergroup > 0) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; +if ($filtert > 0 || $usergroup > 0) { + $sql .= ", ".MAIN_DB_PREFIX."actioncomm_resources as ar"; +} +if ($usergroup > 0) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."usergroup_user as ugu ON ugu.fk_user = ar.fk_element"; +} $sql .= " WHERE c.id = a.fk_action"; $sql .= ' AND a.entity IN ('.getEntity('agenda').')'; // Condition on actioncode -if (!empty($actioncode)) -{ - if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) - { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; - else { - if ($actioncode == 'AC_OTH') $sql .= " AND c.type != 'systemauto'"; - if ($actioncode == 'AC_OTH_AUTO') $sql .= " AND c.type = 'systemauto'"; +if (!empty($actioncode)) { + if (empty($conf->global->AGENDA_USE_EVENT_TYPE)) { + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND c.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } else { + if ($actioncode == 'AC_OTH') { + $sql .= " AND c.type != 'systemauto'"; + } + if ($actioncode == 'AC_OTH_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } } } else { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; - else { - if (is_array($actioncode)) - { + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND c.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } else { + if (is_array($actioncode)) { $sql .= " AND c.code IN ('".implode("','", $actioncode)."')"; } else { $sql .= " AND c.code IN ('".implode("','", explode(',', $actioncode))."')"; @@ -360,35 +436,74 @@ if (!empty($actioncode)) } } } -if ($resourceid > 0) $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); -if ($pid) $sql .= " AND a.fk_project=".$db->escape($pid); -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; -if ($socid > 0) $sql .= " AND s.rowid = ".$socid; +if ($resourceid > 0) { + $sql .= " AND r.element_type = 'action' AND r.element_id = a.id AND r.resource_id = ".$db->escape($resourceid); +} +if ($pid) { + $sql .= " AND a.fk_project=".$db->escape($pid); +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND (a.fk_soc IS NULL OR sc.fk_user = ".$user->id.")"; +} +if ($socid > 0) { + $sql .= " AND s.rowid = ".$socid; +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; -if ($type) $sql .= " AND c.id = ".(int) $type; -if ($search_status == '0') { $sql .= " AND a.percent = 0"; } -if ($search_status == 'na') { $sql .= " AND a.percent = -1"; } // Not applicable -if ($search_status == '50') { $sql .= " AND (a.percent > 0 AND a.percent < 100)"; } // Running already started -if ($search_status == '100') { $sql .= " AND a.percent = 100"; } -if ($search_status == 'done') { $sql .= " AND (a.percent = 100)"; } -if ($search_status == 'todo') { $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; } -if ($search_id) $sql .= natural_search("a.id", $search_id, 1); -if ($search_title) $sql .= natural_search("a.label", $search_title); -if ($search_note) $sql .= natural_search('a.note', $search_note); +if ($filtert > 0 || $usergroup > 0) { + $sql .= " AND ar.fk_actioncomm = a.id AND ar.element_type='user'"; +} +if ($type) { + $sql .= " AND c.id = ".(int) $type; +} +if ($search_status == '0') { + $sql .= " AND a.percent = 0"; +} +if ($search_status == 'na') { + $sql .= " AND a.percent = -1"; +} // Not applicable +if ($search_status == '50') { + $sql .= " AND (a.percent > 0 AND a.percent < 100)"; +} // Running already started +if ($search_status == '100') { + $sql .= " AND a.percent = 100"; +} +if ($search_status == 'done') { + $sql .= " AND (a.percent = 100)"; +} +if ($search_status == 'todo') { + $sql .= " AND (a.percent >= 0 AND a.percent < 100)"; +} +if ($search_id) { + $sql .= natural_search("a.id", $search_id, 1); +} +if ($search_title) { + $sql .= natural_search("a.label", $search_title); +} +if ($search_note) { + $sql .= natural_search('a.note', $search_note); +} // We must filter on assignement table -if ($filtert > 0 || $usergroup > 0) -{ +if ($filtert > 0 || $usergroup > 0) { $sql .= " AND ("; - if ($filtert > 0) $sql .= "(ar.fk_element = ".$filtert." OR (ar.fk_element IS NULL AND a.fk_user_action=".$filtert."))"; // The OR is for backward compatibility - if ($usergroup > 0) $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + if ($filtert > 0) { + $sql .= "(ar.fk_element = ".$filtert." OR (ar.fk_element IS NULL AND a.fk_user_action=".$filtert."))"; // The OR is for backward compatibility + } + if ($usergroup > 0) { + $sql .= ($filtert > 0 ? " OR " : "")." ugu.fk_usergroup = ".$usergroup; + } $sql .= ")"; } // The second or of next test is to take event with no end date (we suppose duration is 1 hour in such case) -if ($dateselect > 0) $sql .= " AND ((a.datep2 >= '".$db->idate($dateselect)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."') OR (a.datep2 IS NULL AND a.datep > '".$db->idate($dateselect - 3600)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."'))"; -if ($datestart > 0) $sql .= " AND a.datep BETWEEN '".$db->idate($datestart)."' AND '".$db->idate($datestart + 3600 * 24 - 1)."'"; -if ($dateend > 0) $sql .= " AND a.datep2 BETWEEN '".$db->idate($dateend)."' AND '".$db->idate($dateend + 3600 * 24 - 1)."'"; +if ($dateselect > 0) { + $sql .= " AND ((a.datep2 >= '".$db->idate($dateselect)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."') OR (a.datep2 IS NULL AND a.datep > '".$db->idate($dateselect - 3600)."' AND a.datep <= '".$db->idate($dateselect + 3600 * 24 - 1)."'))"; +} +if ($datestart > 0) { + $sql .= " AND a.datep BETWEEN '".$db->idate($datestart)."' AND '".$db->idate($datestart + 3600 * 24 - 1)."'"; +} +if ($dateend > 0) { + $sql .= " AND a.datep2 BETWEEN '".$db->idate($dateend)."' AND '".$db->idate($dateend + 3600 * 24 - 1)."'"; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; @@ -401,12 +516,10 @@ $sql .= $hookmanager->resPrint; $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -417,8 +530,7 @@ $sql .= $db->plimit($limit + 1, $offset); dol_syslog("comm/action/list.php", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $actionstatic = new ActionComm($db); $societestatic = new Societe($db); @@ -438,7 +550,9 @@ if ($resql) print ''."\n"; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; @@ -446,8 +560,12 @@ if ($resql) print ''; $nav = ''; - if ($filter) $nav .= ''; - if ($showbirthday) $nav .= ''; + if ($filter) { + $nav .= ''; + } + if ($showbirthday) { + $nav .= ''; + } print $nav; //print dol_get_fiche_head($head, $tabactive, $langs->trans('Agenda'), 0, 'action'); @@ -457,19 +575,19 @@ if ($resql) // Add link to show birthdays $link = ''; /* - if (empty($conf->use_javascript_ajax)) - { - $newparam=$param; // newparam is for birthday links - $newparam=preg_replace('/showbirthday=[0-1]/i','showbirthday='.(empty($showbirthday)?1:0),$newparam); - if (! preg_match('/showbirthday=/i',$newparam)) $newparam.='&showbirthday=1'; - $link=''; - if (empty($showbirthday)) $link.=$langs->trans("AgendaShowBirthdayEvents"); - else $link.=$langs->trans("AgendaHideBirthdayEvents"); - $link.=''; - } - */ + if (empty($conf->use_javascript_ajax)) + { + $newparam=$param; // newparam is for birthday links + $newparam=preg_replace('/showbirthday=[0-1]/i','showbirthday='.(empty($showbirthday)?1:0),$newparam); + if (! preg_match('/showbirthday=/i',$newparam)) $newparam.='&showbirthday=1'; + $link=''; + if (empty($showbirthday)) $link.=$langs->trans("AgendaShowBirthdayEvents"); + else $link.=$langs->trans("AgendaHideBirthdayEvents"); + $link.=''; + } + */ $s = $newtitle; @@ -550,7 +668,9 @@ if ($resql) $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); + if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + } $i = 0; print '
'; @@ -561,11 +681,21 @@ if ($resql) print ''."\n"; print ''; - if (!empty($arrayfields['a.id']['checked'])) print ''; - if (!empty($arrayfields['owner']['checked'])) print ''; - if (!empty($arrayfields['c.libelle']['checked'])) print ''; - if (!empty($arrayfields['a.label']['checked'])) print ''; - if (!empty($arrayfields['a.note']['checked'])) print ''; + if (!empty($arrayfields['a.id']['checked'])) { + print ''; + } + if (!empty($arrayfields['owner']['checked'])) { + print ''; + } + if (!empty($arrayfields['c.libelle']['checked'])) { + print ''; + } + if (!empty($arrayfields['a.label']['checked'])) { + print ''; + } + if (!empty($arrayfields['a.note']['checked'])) { + print ''; + } if (!empty($arrayfields['a.datep']['checked'])) { print ''; } - if (!empty($arrayfields['a.fk_contact']['checked'])) print ''; - if (!empty($arrayfields['a.fk_element']['checked'])) print ''; + if (!empty($arrayfields['a.fk_contact']['checked'])) { + print ''; + } + if (!empty($arrayfields['a.fk_element']['checked'])) { + print ''; + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; @@ -590,8 +724,12 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['a.datec']['checked'])) print ''; - if (!empty($arrayfields['a.tms']['checked'])) print ''; + if (!empty($arrayfields['a.datec']['checked'])) { + print ''; + } + if (!empty($arrayfields['a.tms']['checked'])) { + print ''; + } if (!empty($arrayfields['a.percent']['checked'])) { print '\n"; print ''; - if (!empty($arrayfields['a.id']['checked'])) print_liste_field_titre($arrayfields['a.id']['label'], $_SERVER["PHP_SELF"], "a.id", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['owner']['checked'])) print_liste_field_titre($arrayfields['owner']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['c.libelle']['checked'])) print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], "c.libelle", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['a.label']['checked'])) print_liste_field_titre($arrayfields['a.label']['label'], $_SERVER["PHP_SELF"], "a.label", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['a.note']['checked'])) print_liste_field_titre($arrayfields['a.note']['label'], $_SERVER["PHP_SELF"], "a.note", $param, "", "", $sortfield, $sortorder); + if (!empty($arrayfields['a.id']['checked'])) { + print_liste_field_titre($arrayfields['a.id']['label'], $_SERVER["PHP_SELF"], "a.id", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['owner']['checked'])) { + print_liste_field_titre($arrayfields['owner']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['c.libelle']['checked'])) { + print_liste_field_titre($arrayfields['c.libelle']['label'], $_SERVER["PHP_SELF"], "c.libelle", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['a.label']['checked'])) { + print_liste_field_titre($arrayfields['a.label']['label'], $_SERVER["PHP_SELF"], "a.label", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['a.note']['checked'])) { + print_liste_field_titre($arrayfields['a.note']['label'], $_SERVER["PHP_SELF"], "a.note", $param, "", "", $sortfield, $sortorder); + } //if (! empty($conf->global->AGENDA_USE_EVENT_TYPE)) - if (!empty($arrayfields['a.datep']['checked'])) print_liste_field_titre($arrayfields['a.datep']['label'], $_SERVER["PHP_SELF"], "a.datep,a.id", $param, '', 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['a.datep2']['checked'])) print_liste_field_titre($arrayfields['a.datep2']['label'], $_SERVER["PHP_SELF"], "a.datep2", $param, '', 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['a.fk_contact']['checked'])) print_liste_field_titre($arrayfields['a.fk_contact']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); - if (!empty($arrayfields['a.fk_element']['checked'])) print_liste_field_titre($arrayfields['a.fk_element']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); + if (!empty($arrayfields['a.datep']['checked'])) { + print_liste_field_titre($arrayfields['a.datep']['label'], $_SERVER["PHP_SELF"], "a.datep,a.id", $param, '', 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['a.datep2']['checked'])) { + print_liste_field_titre($arrayfields['a.datep2']['label'], $_SERVER["PHP_SELF"], "a.datep2", $param, '', 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['a.fk_contact']['checked'])) { + print_liste_field_titre($arrayfields['a.fk_contact']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); + } + if (!empty($arrayfields['a.fk_element']['checked'])) { + print_liste_field_titre($arrayfields['a.fk_element']['label'], $_SERVER["PHP_SELF"], "", $param, "", "", $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; @@ -626,10 +784,16 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['a.datec']['checked'])) print_liste_field_titre($arrayfields['a.datec']['label'], $_SERVER["PHP_SELF"], "a.datec,a.id", $param, "", 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['a.tms']['checked'])) print_liste_field_titre($arrayfields['a.tms']['label'], $_SERVER["PHP_SELF"], "a.tms,a.id", $param, "", 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['a.datec']['checked'])) { + print_liste_field_titre($arrayfields['a.datec']['label'], $_SERVER["PHP_SELF"], "a.datec,a.id", $param, "", 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['a.tms']['checked'])) { + print_liste_field_titre($arrayfields['a.tms']['label'], $_SERVER["PHP_SELF"], "a.tms,a.id", $param, "", 'align="center"', $sortfield, $sortorder); + } - if (!empty($arrayfields['a.percent']['checked']))print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "a.percent", $param, "", 'align="center"', $sortfield, $sortorder); + if (!empty($arrayfields['a.percent']['checked'])) { + print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "a.percent", $param, "", 'align="center"', $sortfield, $sortorder); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; @@ -642,13 +806,11 @@ if ($resql) $arraylist = $caction->liste_array(1, 'code', '', (empty($conf->global->AGENDA_USE_EVENT_TYPE) ? 1 : 0), '', 1); $contactListCache = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); // Discard auto action if option is on - if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') - { + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO) && $obj->type_code == 'AC_OTH_AUTO') { $i++; continue; } @@ -676,29 +838,34 @@ if ($resql) } // User owner - if (!empty($arrayfields['owner']['checked'])) - { + if (!empty($arrayfields['owner']['checked'])) { print ''; } // Type - if (!empty($arrayfields['c.libelle']['checked'])) - { + if (!empty($arrayfields['c.libelle']['checked'])) { print ''; @@ -726,11 +893,21 @@ if ($resql) print ''; } @@ -744,15 +921,16 @@ if ($resql) // Third party if (!empty($arrayfields['s.nom']['checked'])) { print ''; } @@ -760,17 +938,13 @@ if ($resql) if (!empty($arrayfields['a.fk_contact']['checked'])) { print ''; diff --git a/htdocs/comm/action/pertype.php b/htdocs/comm/action/pertype.php index 613ffee7be7..dc70fb30743 100644 --- a/htdocs/comm/action/pertype.php +++ b/htdocs/comm/action/pertype.php @@ -39,7 +39,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -if (!isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW = 3; +if (!isset($conf->global->AGENDA_MAX_EVENTS_DAY_VIEW)) { + $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW = 3; +} $filter = GETPOST("search_filter", 'alpha', 3) ? GETPOST("search_filter", 'alpha', 3) : GETPOST("filter", 'alpha', 3); $filtert = GETPOST("search_filtert", "int", 3) ? GETPOST("search_filtert", "int", 3) : GETPOST("filtert", "int", 3); @@ -49,31 +51,43 @@ $usergroup = GETPOST("search_usergroup", "int", 3) ? GETPOST("search_usergroup", $showbirthday = 0; // If not choice done on calendar owner, we filter on user. -if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) -{ +if (empty($filtert) && empty($conf->global->AGENDA_ALL_CALENDARS)) { $filtert = $user->id; } $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 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "a.datec"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "a.datec"; +} // Security check $socid = GETPOST("search_socid", "int") ?GETPOST("search_socid", "int") : GETPOST("socid", "int"); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'agenda', 0, '', 'myactions'); -if ($socid < 0) $socid = ''; +if ($socid < 0) { + $socid = ''; +} $canedit = 1; -if (!$user->rights->agenda->myactions->read) accessforbidden(); -if (!$user->rights->agenda->allactions->read) $canedit = 0; -if (!$user->rights->agenda->allactions->read || $filter == 'mine') // If no permission to see all, we show only affected to me -{ +if (!$user->rights->agenda->myactions->read) { + accessforbidden(); +} +if (!$user->rights->agenda->allactions->read) { + $canedit = 0; +} +if (!$user->rights->agenda->allactions->read || $filter == 'mine') { // If no permission to see all, we show only affected to me $filtert = $user->id; } @@ -90,18 +104,20 @@ $type = GETPOST("search_type", 'alpha') ?GETPOST("search_type", 'alpha') : GETPO $maxprint = ((GETPOST("maxprint", 'int') != '') ?GETPOST("maxprint", 'int') : $conf->global->AGENDA_MAX_EVENTS_DAY_VIEW); $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') // Set actioncode (this code must be same for setting actioncode into peruser, listacton and index) -if (GETPOST('search_actioncode', 'array')) -{ +if (GETPOST('search_actioncode', 'array')) { $actioncode = GETPOST('search_actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + if (!count($actioncode)) { + $actioncode = '0'; + } } else { $actioncode = GETPOST("search_actioncode", "alpha", 3) ?GETPOST("search_actioncode", "alpha", 3) : (GETPOST("search_actioncode", "alpha") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE)); } -if ($actioncode == '' && empty($actioncodearray)) $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); +if ($actioncode == '' && empty($actioncodearray)) { + $actioncode = (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE); +} $dateselect = dol_mktime(0, 0, 0, GETPOST('dateselectmonth', 'int'), GETPOST('dateselectday', 'int'), GETPOST('dateselectyear', 'int')); -if ($dateselect > 0) -{ +if ($dateselect > 0) { $day = GETPOST('dateselectday', 'int'); $month = GETPOST('dateselectmonth', 'int'); $year = GETPOST('dateselectyear', 'int'); @@ -112,9 +128,15 @@ $tmp = str_replace(' ', '', $tmp); // FIX 7533 $tmparray = explode('-', $tmp); $begin_h = GETPOST('begin_h', 'int') != '' ?GETPOST('begin_h', 'int') : ($tmparray[0] != '' ? $tmparray[0] : 9); $end_h = GETPOST('end_h', 'int') ?GETPOST('end_h', 'int') : ($tmparray[1] != '' ? $tmparray[1] : 18); -if ($begin_h < 0 || $begin_h > 23) $begin_h = 9; -if ($end_h < 1 || $end_h > 24) $end_h = 18; -if ($end_h <= $begin_h) $end_h = $begin_h + 1; +if ($begin_h < 0 || $begin_h > 23) { + $begin_h = 9; +} +if ($end_h < 1 || $end_h > 24) { + $end_h = 18; +} +if ($end_h <= $begin_h) { + $end_h = $begin_h + 1; +} $tmp = empty($conf->global->MAIN_DEFAULT_WORKING_DAYS) ? '1-5' : $conf->global->MAIN_DEFAULT_WORKING_DAYS; $tmp = str_replace(' ', '', $tmp); // FIX 7533 @@ -122,8 +144,12 @@ $tmparray = explode('-', $tmp); $begin_d = 1; $end_d = 53; -if ($status == '' && !GETPOSTISSET('status')) $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); -if (empty($action) && !GETPOSTISSET('action')) $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); +if ($status == '' && !GETPOSTISSET('status')) { + $status = (empty($conf->global->AGENDA_DEFAULT_FILTER_STATUS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_STATUS); +} +if (empty($action) && !GETPOSTISSET('action')) { + $action = (empty($conf->global->AGENDA_DEFAULT_VIEW) ? 'show_month' : $conf->global->AGENDA_DEFAULT_VIEW); +} if (GETPOST('viewcal', 'alpha') && $action != 'show_day' && $action != 'show_week' && $action != 'show_peruser') { $action = 'show_month'; $day = ''; @@ -149,8 +175,7 @@ $hookmanager->initHooks(array('agenda')); * Actions */ -if ($action == 'delete_action') -{ +if ($action == 'delete_action') { $event = new ActionComm($db); $event->fetch($actionid); $event->fetch_optionals(); @@ -185,7 +210,9 @@ $parameters = array( 'usergroup' => $usergroup, ); $reshook = $hookmanager->executeHooks('beforeAgendaPerType', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} $form = new Form($db); $companystatic = new Societe($db); @@ -223,29 +250,65 @@ $tmpday = $first_day; //print 'xx'.$next_year.'-'.$next_month.'-'.$next_day; $title = $langs->trans("DoneAndToDoActions"); -if ($status == 'done') $title = $langs->trans("DoneActions"); -if ($status == 'todo') $title = $langs->trans("ToDoActions"); +if ($status == 'done') { + $title = $langs->trans("DoneActions"); +} +if ($status == 'todo') { + $title = $langs->trans("ToDoActions"); +} $param = ''; if ($actioncode || GETPOSTISSET('search_actioncode')) { if (is_array($actioncode)) { - foreach ($actioncode as $str_action) $param .= "&search_actioncode[]=".urlencode($str_action); - } else $param .= "&search_actioncode=".urlencode($actioncode); + foreach ($actioncode as $str_action) { + $param .= "&search_actioncode[]=".urlencode($str_action); + } + } else { + $param .= "&search_actioncode=".urlencode($actioncode); + } +} +if ($resourceid > 0) { + $param .= "&search_resourceid=".urlencode($resourceid); +} +if ($status || GETPOSTISSET('status')) { + $param .= "&search_status=".urlencode($status); +} +if ($filter) { + $param .= "&search_filter=".urlencode($filter); +} +if ($filtert) { + $param .= "&search_filtert=".urlencode($filtert); +} +if ($usergroup > 0) { + $param .= "&search_usergroup=".urlencode($usergroup); +} +if ($socid > 0) { + $param .= "&search_socid=".urlencode($socid); +} +if ($showbirthday) { + $param .= "&search_showbirthday=1"; +} +if ($pid) { + $param .= "&search_projectid=".urlencode($pid); +} +if ($type) { + $param .= "&search_type=".urlencode($type); +} +if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') { + $param .= '&action='.urlencode($action); +} +if ($begin_h != '') { + $param .= '&begin_h='.urlencode($begin_h); +} +if ($end_h != '') { + $param .= '&end_h='.urlencode($end_h); +} +if ($begin_d != '') { + $param .= '&begin_d='.urlencode($begin_d); +} +if ($end_d != '') { + $param .= '&end_d='.urlencode($end_d); } -if ($resourceid > 0) $param .= "&search_resourceid=".urlencode($resourceid); -if ($status || GETPOSTISSET('status')) $param .= "&search_status=".urlencode($status); -if ($filter) $param .= "&search_filter=".urlencode($filter); -if ($filtert) $param .= "&search_filtert=".urlencode($filtert); -if ($usergroup > 0) $param .= "&search_usergroup=".urlencode($usergroup); -if ($socid > 0) $param .= "&search_socid=".urlencode($socid); -if ($showbirthday) $param .= "&search_showbirthday=1"; -if ($pid) $param .= "&search_projectid=".urlencode($pid); -if ($type) $param .= "&search_type=".urlencode($type); -if ($action == 'show_day' || $action == 'show_week' || $action == 'show_month' || $action != 'show_peruser') $param .= '&action='.urlencode($action); -if ($begin_h != '') $param .= '&begin_h='.urlencode($begin_h); -if ($end_h != '') $param .= '&end_h='.urlencode($end_h); -if ($begin_d != '') $param .= '&begin_d='.urlencode($begin_d); -if ($end_d != '') $param .= '&end_d='.urlencode($end_d); $param .= "&maxprint=".urlencode($maxprint); $paramnoactionodate = $param; @@ -301,28 +364,23 @@ print 'use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { $s = ''; $s .= ''."\n"; - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { $s .= '
'.$langs->trans("LocalAgenda").'  
'; - if (is_array($showextcals) && count($showextcals) > 0) - { - foreach ($showextcals as $val) - { + if (is_array($showextcals) && count($showextcals) > 0) { + foreach ($showextcals as $val) { $htmlname = md5($val['name']); $s .= ''."\n"; - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { $s .= '
'.$langs->trans("LocalAgenda").'  
'; - if (is_array($showextcals) && count($showextcals) > 0) - { - foreach ($showextcals as $val) - { + if (is_array($showextcals) && count($showextcals) > 0) { + foreach ($showextcals as $val) { $htmlname = md5($val['name']); $s .= ''."\n"; - else print ''."\n"; + if (defined('JS_JQUERY') && constant('JS_JQUERY')) { + print ''."\n"; + } else { + print ''."\n"; + } /*if (! empty($conf->global->MAIN_FEATURES_LEVEL) && ! defined('JS_JQUERY_MIGRATE_DISABLED')) { if (defined('JS_JQUERY_MIGRATE') && constant('JS_JQUERY_MIGRATE')) print ''."\n"; else print ''."\n"; }*/ - if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) print ''."\n"; - else print ''."\n"; - if (!defined('DISABLE_JQUERY_TABLEDND')) print ''."\n"; + if (defined('JS_JQUERY_UI') && constant('JS_JQUERY_UI')) { + print ''."\n"; + } else { + print ''."\n"; + } + if (!defined('DISABLE_JQUERY_TABLEDND')) { + print ''."\n"; + } // jQuery jnotify if (empty($conf->global->MAIN_DISABLE_JQUERY_JNOTIFY) && !defined('DISABLE_JQUERY_JNOTIFY')) { print ''."\n"; @@ -1502,16 +1583,14 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr $tmpplugin = empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) ?constant('REQUIRE_JQUERY_MULTISELECT') : $conf->global->MAIN_USE_JQUERY_MULTISELECT; print ''."\n"; // We include full because we need the support of containerCssClass } - if (!defined('DISABLE_MULTISELECT')) // jQuery plugin "mutiselect" to select with checkboxes. Can be removed once we have an enhanced search tool - { + if (!defined('DISABLE_MULTISELECT')) { // jQuery plugin "mutiselect" to select with checkboxes. Can be removed once we have an enhanced search tool print ''."\n"; } } if (!$disablejs && !empty($conf->use_javascript_ajax)) { // CKEditor - if ((!empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && !defined('DISABLE_CKEDITOR')) || defined('FORCE_CKEDITOR')) - { + if ((!empty($conf->fckeditor->enabled) && (empty($conf->global->FCKEDITOR_EDITORNAME) || $conf->global->FCKEDITOR_EDITORNAME == 'ckeditor') && !defined('DISABLE_CKEDITOR')) || defined('FORCE_CKEDITOR')) { print ''."\n"; $pathckeditor = DOL_URL_ROOT.'/includes/ckeditor/ckeditor/'; $jsckeditor = 'ckeditor.js'; @@ -1520,7 +1599,7 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr $pathckeditor = constant('JS_CKEDITOR'); } print ''."\n"; } @@ -1554,27 +1635,21 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr print ''."\n"; // JS forced by modules (relative url starting with /) - if (!empty($conf->modules_parts['js'])) // $conf->modules_parts['js'] is array('module'=>array('file1','file2')) - { + if (!empty($conf->modules_parts['js'])) { // $conf->modules_parts['js'] is array('module'=>array('file1','file2')) $arrayjs = (array) $conf->modules_parts['js']; - foreach ($arrayjs as $modjs => $filesjs) - { + foreach ($arrayjs as $modjs => $filesjs) { $filesjs = (array) $filesjs; // To be sure filejs is an array - foreach ($filesjs as $jsfile) - { + foreach ($filesjs as $jsfile) { // jsfile is a relative path print ''."\n".''."\n"; } } } // JS forced by page in top_htmlhead (relative url starting with /) - if (is_array($arrayofjs)) - { + if (is_array($arrayofjs)) { print ''."\n"; - foreach ($arrayofjs as $jsfile) - { - if (preg_match('/^(http|\/\/)/i', $jsfile)) - { + foreach ($arrayofjs as $jsfile) { + if (preg_match('/^(http|\/\/)/i', $jsfile)) { print ''."\n"; } else { print ''."\n"; @@ -1583,8 +1658,12 @@ function top_htmlhead($head, $title = '', $disablejs = 0, $disablehead = 0, $arr } } - if (!empty($head)) print $head."\n"; - if (!empty($conf->global->MAIN_HTML_HEADER)) print $conf->global->MAIN_HTML_HEADER."\n"; + if (!empty($head)) { + print $head."\n"; + } + if (!empty($conf->global->MAIN_HTML_HEADER)) { + print $conf->global->MAIN_HTML_HEADER."\n"; + } $parameters = array(); $result = $hookmanager->executeHooks('addHtmlHeader', $parameters); // Note that $action and $object may have been modified by some hooks @@ -1628,18 +1707,16 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead $toprightmenu = ''; // For backward compatibility with old modules - if (empty($conf->headerdone)) - { + if (empty($conf->headerdone)) { $disablenofollow = 0; top_htmlhead($head, $title, $disablejs, $disablehead, $arrayofjs, $arrayofcss, 0, $disablenofollow); print ''; } /* - * Top menu - */ - if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) - { + * Top menu + */ + if ((empty($conf->dol_hide_topmenu) || GETPOST('dol_invisible_topmenu', 'int')) && (!defined('NOREQUIREMENU') || !constant('NOREQUIREMENU'))) { if (!isset($form) || !is_object($form)) { include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; $form = new Form($db); @@ -1657,24 +1734,28 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead // Define link to login card $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) - { + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $appli = $conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core - } else $appli .= " ".DOL_VERSION; - } else $appli .= " ".DOL_VERSION; + if (preg_match('/\d\.\d/', $appli)) { + if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) { + $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core + } + } else { + $appli .= " ".DOL_VERSION; + } + } else { + $appli .= " ".DOL_VERSION; + } - if (!empty($conf->global->MAIN_FEATURES_LEVEL)) $appli .= "
".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL; + if (!empty($conf->global->MAIN_FEATURES_LEVEL)) { + $appli .= "
".$langs->trans("LevelOfFeature").': '.$conf->global->MAIN_FEATURES_LEVEL; + } $logouttext = ''; $logouthtmltext = ''; - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { //$logouthtmltext=$appli.'
'; - if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http') - { + if ($_SESSION["dol_authmode"] != 'forceuser' && $_SESSION["dol_authmode"] != 'http') { $logouthtmltext .= $langs->trans("Logout").'
'; $logouttext .= ''; @@ -1693,11 +1774,10 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead // Execute hook printTopRightMenu (hooks should output string like '') $parameters = array(); $result = $hookmanager->executeHooks('printTopRightMenu', $parameters); // Note that $action and $object may have been modified by some hooks - if (is_numeric($result)) - { - if ($result == 0) + if (is_numeric($result)) { + if ($result == 0) { $toprightmenu .= $hookmanager->resPrint; // add - else { + } else { $toprightmenu = $hookmanager->resPrint; // replace } } else { @@ -1705,8 +1785,7 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead } // Link to module builder - if (!empty($conf->modulebuilder->enabled)) - { + if (!empty($conf->modulebuilder->enabled)) { $text = ''; //$text.= img_picto(":".$langs->trans("ModuleBuilder"), 'printer_top.png', 'class="printer"'); $text .= ''; @@ -1715,14 +1794,14 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead } // Link to print main content area - if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone') - { + if (empty($conf->global->MAIN_PRINT_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER) && $conf->browser->layout != 'phone') { $qs = dol_escape_htmltag($_SERVER["QUERY_STRING"]); - if (is_array($_POST)) - { - foreach ($_POST as $key=>$value) { - if ($key !== 'action' && $key !== 'password' && !is_array($value)) $qs .= '&'.$key.'='.urlencode($value); + if (is_array($_POST)) { + foreach ($_POST as $key => $value) { + if ($key !== 'action' && $key !== 'password' && !is_array($value)) { + $qs .= '&'.$key.'='.urlencode($value); + } } } $qs .= (($qs && $morequerystring) ? '&' : '').$morequerystring; @@ -1734,8 +1813,7 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead } // Link to Dolibarr wiki pages - if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($conf->global->MAIN_HELP_DISABLELINK) && empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $langs->load("help"); $helpbaseurl = ''; @@ -1756,21 +1834,28 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead $mode = $arrayres['mode']; // Link to help pages - if ($helpbaseurl && $helppage) - { + if ($helpbaseurl && $helppage) { $text = ''; $title = $langs->trans($mode == 'wiki' ? 'GoToWikiHelpPage' : 'GoToHelpPage').'...'; if ($mode == 'wiki') { $title .= '
'.$langs->trans("PageWiki").' '.dol_escape_htmltag('"'.strtr($helppage, '_', ' ').'"'); - if ($helppresent) $title .= ' ('.$langs->trans("DedicatedPageAvailable").')'; - else $title .= ' ('.$langs->trans("HomePage").')'; + if ($helppresent) { + $title .= ' ('.$langs->trans("DedicatedPageAvailable").')'; + } else { + $title .= ' ('.$langs->trans("HomePage").')'; + } } $text .= '
'; $text .= ''; - if ($helppresent) $text .= ''; + if ($helppresent) { + $text .= ''; + } $text .= ''; $toprightmenu .= $form->textwithtooltip('', $title, 2, 1, $text, 'login_block_elem', 2); } @@ -1831,7 +1916,9 @@ function top_menu($head, $title = '', $target = '', $disablejs = 0, $disablehead print "\n\n"; } - if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) print '
'; + if (empty($conf->dol_hide_leftmenu) && empty($conf->dol_use_jmobile)) { + print '
'; + } } @@ -1849,14 +1936,17 @@ function top_menu_user($hideloginname = 0, $urllogout = '') global $menumanager; $userImage = $userDropDownImage = ''; - if (!empty($user->photo)) - { + if (!empty($user->photo)) { $userImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'photouserphoto userphoto', 'small', 0, 1); $userDropDownImage = Form::showphoto('userphoto', $user, 0, 0, 0, 'dropdown-user-image', 'small', 0, 1); } else { $nophoto = '/public/theme/common/user_anonymous.png'; - if ($user->gender == 'man') $nophoto = '/public/theme/common/user_man.png'; - if ($user->gender == 'woman') $nophoto = '/public/theme/common/user_woman.png'; + if ($user->gender == 'man') { + $nophoto = '/public/theme/common/user_man.png'; + } + if ($user->gender == 'woman') { + $nophoto = '/public/theme/common/user_woman.png'; + } $userImage = 'No photo'; $userDropDownImage = 'No photo'; @@ -1870,8 +1960,7 @@ function top_menu_user($hideloginname = 0, $urllogout = '') if (!empty($user->admin)) { $dropdownBody .= '
'.$langs->trans("Administrator").': '.yn($user->admin); } - if (!empty($user->socid)) // Add thirdparty for external users - { + if (!empty($user->socid)) { // Add thirdparty for external users $thirdpartystatic = new Societe($db); $thirdpartystatic->fetch($user->socid); $companylink = ' '.$thirdpartystatic->getNomUrl(2); // picto only of company @@ -1884,7 +1973,9 @@ function top_menu_user($hideloginname = 0, $urllogout = '') $dropdownBody .= '
'.$langs->trans("Session").''; $dropdownBody .= '
'.$langs->trans("IPAddress").': '.dol_escape_htmltag($_SERVER["REMOTE_ADDR"]); - if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) $dropdownBody .= '
'.$langs->trans("ConnectedOnMultiCompany").': '.$conf->entity.' (user entity '.$user->entity.')'; + if (!empty($conf->global->MAIN_MODULE_MULTICOMPANY)) { + $dropdownBody .= '
'.$langs->trans("ConnectedOnMultiCompany").': '.$conf->entity.' (user entity '.$user->entity.')'; + } $dropdownBody .= '
'.$langs->trans("AuthenticationMode").': '.$_SESSION["dol_authmode"].(empty($dolibarr_main_demo) ? '' : ' (demo)'); $dropdownBody .= '
'.$langs->trans("ConnectedSince").': '.dol_print_date($user->datelastlogin, "dayhour", 'tzuser'); $dropdownBody .= '
'.$langs->trans("PreviousConnexion").': '.dol_print_date($user->datepreviouslogin, "dayhour", 'tzuser'); @@ -1903,15 +1994,18 @@ function top_menu_user($hideloginname = 0, $urllogout = '') $dropdownBody .= '
'.$langs->trans("Browser").': '.$conf->browser->name.($conf->browser->version ? ' '.$conf->browser->version : '').' ('.dol_escape_htmltag($_SERVER['HTTP_USER_AGENT']).')'; $dropdownBody .= '
'.$langs->trans("Layout").': '.$conf->browser->layout; $dropdownBody .= '
'.$langs->trans("Screen").': '.$_SESSION['dol_screenwidth'].' x '.$_SESSION['dol_screenheight']; - if ($conf->browser->layout == 'phone') $dropdownBody .= '
'.$langs->trans("Phone").': '.$langs->trans("Yes"); - if (!empty($_SESSION["disablemodules"])) $dropdownBody .= '
'.$langs->trans("DisabledModules").':
'.join(', ', explode(',', $_SESSION["disablemodules"])); + if ($conf->browser->layout == 'phone') { + $dropdownBody .= '
'.$langs->trans("Phone").': '.$langs->trans("Yes"); + } + if (!empty($_SESSION["disablemodules"])) { + $dropdownBody .= '
'.$langs->trans("DisabledModules").':
'.join(', ', explode(',', $_SESSION["disablemodules"])); + } $dropdownBody .= '
'; // Execute hook $parameters = array('user'=>$user, 'langs' => $langs); $result = $hookmanager->executeHooks('printTopRightMenuLoginDropdownBody', $parameters); // Note that $action and $object may have been modified by some hooks - if (is_numeric($result)) - { + if (is_numeric($result)) { if ($result == 0) { $dropdownBody .= $hookmanager->resPrint; // add } else { @@ -1934,14 +2028,18 @@ function top_menu_user($hideloginname = 0, $urllogout = '') // Define version to show $appli = constant('DOL_APPLICATION_TITLE'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) - { + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $appli = $conf->global->MAIN_APPLICATION_TITLE; - if (preg_match('/\d\.\d/', $appli)) - { - if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core - } else $appli .= " ".DOL_VERSION; - } else $appli .= " ".DOL_VERSION; + if (preg_match('/\d\.\d/', $appli)) { + if (!preg_match('/'.preg_quote(DOL_VERSION).'/', $appli)) { + $appli .= " (".DOL_VERSION.")"; // If new title contains a version that is different than core + } + } else { + $appli .= " ".DOL_VERSION; + } + } else { + $appli .= " ".DOL_VERSION; + } if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $btnUser = ' @@ -1990,8 +2088,7 @@ function top_menu_user($hideloginname = 0, $urllogout = '')
'; } - if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) // This may be set by some pages that use different jquery version to avoid errors - { + if (!defined('JS_JQUERY_DISABLE_DROPDOWN') && !empty($conf->use_javascript_ajax)) { // This may be set by some pages that use different jquery version to avoid errors $btnUser .= ' '."\n"; } // Wrapper to add log when clicking on download or preview - if (!empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0) - { - if (in_array($object->element, array('facture'))) // Restrict for the moment to element 'facture' - { + if (!empty($conf->blockedlog->enabled) && is_object($object) && $object->id > 0 && $object->statut > 0) { + if (in_array($object->element, array('facture'))) { // Restrict for the moment to element 'facture' print "\n\n"; ?> - + \n"; @@ -2916,20 +3063,17 @@ if (!function_exists("llxFooter")) // Add code for the asynchronous anonymous first ping (for telemetry) // You can use &forceping=1 in parameters to force the ping if the ping was already sent. $forceping = GETPOST('forceping', 'alpha'); - if (($_SERVER["PHP_SELF"] == DOL_URL_ROOT.'/index.php') || $forceping) - { + if (($_SERVER["PHP_SELF"] == DOL_URL_ROOT.'/index.php') || $forceping) { //print ''; $hash_unique_id = md5('dolibarr'.$conf->file->instance_unique_id); if (empty($conf->global->MAIN_FIRST_PING_OK_DATE) || (!empty($conf->file->instance_unique_id) && ($hash_unique_id != $conf->global->MAIN_FIRST_PING_OK_ID) && ($conf->global->MAIN_FIRST_PING_OK_ID != 'disabled')) - || $forceping) - { + || $forceping) { // No ping done if we are into an alpha version if (strpos('alpha', DOL_VERSION) > 0 && !$forceping) { print "\n\n"; - } elseif (empty($_COOKIE['DOLINSTALLNOPING_'.$hash_unique_id]) || $forceping) // Cookie is set when we uncheck the checkbox in the installation wizard. - { - // MAIN_LAST_PING_KO_DATE + } elseif (empty($_COOKIE['DOLINSTALLNOPING_'.$hash_unique_id]) || $forceping) { // Cookie is set when we uncheck the checkbox in the installation wizard. + // MAIN_LAST_PING_KO_DATE // Disable ping if MAIN_LAST_PING_KO_DATE is set and is recent if (!empty($conf->global->MAIN_LAST_PING_KO_DATE) && substr($conf->global->MAIN_LAST_PING_KO_DATE, 0, 6) == dol_print_date(dol_now(), '%Y%m') && !$forceping) { print "\n\n"; @@ -2941,51 +3085,55 @@ if (!function_exists("llxFooter")) $url_for_ping = (empty($conf->global->MAIN_URL_FOR_PING) ? "https://ping.dolibarr.org/" : $conf->global->MAIN_URL_FOR_PING); // Try to guess the distrib used $distrib = 'standard'; - if ($_SERVER["SERVER_ADMIN"] == 'doliwamp@localhost') $distrib = 'doliwamp'; - if (!empty($dolibarr_distrib)) $distrib = $dolibarr_distrib; + if ($_SERVER["SERVER_ADMIN"] == 'doliwamp@localhost') { + $distrib = 'doliwamp'; + } + if (!empty($dolibarr_distrib)) { + $distrib = $dolibarr_distrib; + } ?> - + Date: Tue, 23 Feb 2021 20:46:19 +0100 Subject: [PATCH 19/64] code syntax commande directory --- htdocs/commande/card.php | 812 +++++------ htdocs/commande/class/api_orders.class.php | 127 +- htdocs/commande/class/commande.class.php | 1274 +++++++++-------- htdocs/commande/class/commandestats.class.php | 53 +- htdocs/commande/contact.php | 49 +- htdocs/commande/customer.php | 65 +- htdocs/commande/document.php | 41 +- htdocs/commande/index.php | 173 ++- htdocs/commande/info.php | 17 +- htdocs/commande/list.php | 1095 ++++++++------ htdocs/commande/note.php | 16 +- htdocs/commande/stats/index.php | 159 +- htdocs/commande/tpl/linkedobjectblock.tpl.php | 7 +- 13 files changed, 2140 insertions(+), 1748 deletions(-) diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index f0c05ec7986..889eb036ab4 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -60,9 +60,15 @@ if (!empty($conf->variants->enabled)) { // Load translation files required by the page $langs->loadLangs(array('orders', 'sendings', 'companies', 'bills', 'propal', 'deliveries', 'products', 'other')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); -if (!empty($conf->margin->enabled)) $langs->load('margins'); -if (!empty($conf->productbatch->enabled)) $langs->load("productbatch"); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} +if (!empty($conf->margin->enabled)) { + $langs->load('margins'); +} +if (!empty($conf->productbatch->enabled)) { + $langs->load("productbatch"); +} $id = (GETPOST('id', 'int') ? GETPOST('id', 'int') : GETPOST('orderid', 'int')); $ref = GETPOST('ref', 'alpha'); @@ -82,8 +88,9 @@ $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($ $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); // Security check -if (!empty($user->socid)) +if (!empty($user->socid)) { $socid = $user->socid; +} $result = restrictedArea($user, 'commande', $id); $object = new Commande($db); @@ -125,14 +132,13 @@ $date_delivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int' $parameters = array('socid' => $socid); // Note that $action and $object may be modified by some hooks $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -146,20 +152,16 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) - { - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { + if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { - if ($object->id > 0) - { + if ($object->id > 0) { // Because createFromClone modifies the object, we must clone it so that we can restore it later $orig = clone $object; $result = $object->createFromClone($user, $socid); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -169,49 +171,38 @@ if (empty($reshook)) } } } - } - - // Reopen a closed order - elseif ($action == 'reopen' && $usercancreate) - { - if ($object->statut == Commande::STATUS_CANCELED || $object->statut == Commande::STATUS_CLOSED) - { + } elseif ($action == 'reopen' && $usercancreate) { + // Reopen a closed order + if ($object->statut == Commande::STATUS_CANCELED || $object->statut == Commande::STATUS_CLOSED) { $result = $object->set_reopen($user); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans('OrderReopened', $object->ref), null); } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // Remove order - elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) - { + } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { + // Remove order $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { header('Location: list.php?restore_lastsearch_values=1'); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Remove a product line - elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { + // Remove a product line $result = $object->deleteline($user, $lineid); - if ($result > 0) - { + if ($result > 0) { // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -226,17 +217,11 @@ if (empty($reshook)) } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Link to a project - elseif ($action == 'classin' && $usercancreate) - { + } elseif ($action == 'classin' && $usercancreate) { + // Link to a project $object->setProject(GETPOST('projectid', 'int')); - } - - // Add order - elseif ($action == 'add' && $usercancreate) - { + } elseif ($action == 'add' && $usercancreate) { + // Add order $datecommande = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $date_delivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); $selectedLines = GETPOST('toselect', 'array'); @@ -282,15 +267,15 @@ if (empty($reshook)) $object->multicurrency_code = GETPOST('multicurrency_code', 'alpha'); $object->multicurrency_tx = GETPOST('originmulticurrency_tx', 'int'); // Fill array 'array_options' with data from add form - if (!$error) - { + if (!$error) { $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } // If creation from another object of another module (Example: origin=propal, originid=1) - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) { @@ -320,12 +305,10 @@ if (empty($reshook)) $object->linked_objects = array_merge($object->linked_objects, $other_linked_objects); } - if (!$error) - { + if (!$error) { $object_id = $object->create($user); - if ($object_id > 0) - { + if ($object_id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); @@ -333,11 +316,9 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $srcobject->fetch($object->origin_id); - if ($result > 0) - { + if ($result > 0) { $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } @@ -345,9 +326,10 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { - if (!in_array($lines[$i]->id, $selectedLines)) continue; // Skip unselected lines + for ($i = 0; $i < $num; $i++) { + if (!in_array($lines[$i]->id, $selectedLines)) { + continue; // Skip unselected lines + } $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : ''); @@ -356,15 +338,19 @@ if (empty($reshook)) // Dates // TODO mutualiser $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) + if ($lines[$i]->date_debut_reel) { $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) + } + if ($lines[$i]->date_start) { $date_start = $lines[$i]->date_start; + } $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) + if ($lines[$i]->date_fin_reel) { $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) + } + if ($lines[$i]->date_end) { $date_end = $lines[$i]->date_end; + } // Reset fk_parent_line for no child products and special product if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { @@ -372,20 +358,42 @@ if (empty($reshook)) } // Extrafields - if (method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if trigger used - { + if (method_exists($lines[$i], 'fetch_optionals')) { // For avoid conflicts if trigger used $lines[$i]->fetch_optionals(); $array_options = $lines[$i]->array_options; } $tva_tx = $lines[$i]->tva_tx; - if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) $tva_tx .= ' ('.$lines[$i]->vat_src_code.')'; + if (!empty($lines[$i]->vat_src_code) && !preg_match('/\(/', $tva_tx)) { + $tva_tx .= ' ('.$lines[$i]->vat_src_code.')'; + } $result = $object->addline( - $desc, $lines[$i]->subprice, $lines[$i]->qty, $tva_tx, $lines[$i]->localtax1_tx, $lines[$i]->localtax2_tx, $lines[$i]->fk_product, - $lines[$i]->remise_percent, $lines[$i]->info_bits, $lines[$i]->fk_remise_except, 'HT', 0, $date_start, $date_end, $product_type, - $lines[$i]->rang, $lines[$i]->special_code, $fk_parent_line, $lines[$i]->fk_fournprice, $lines[$i]->pa_ht, $label, $array_options, - $lines[$i]->fk_unit, $object->origin, $lines[$i]->rowid + $desc, + $lines[$i]->subprice, + $lines[$i]->qty, + $tva_tx, + $lines[$i]->localtax1_tx, + $lines[$i]->localtax2_tx, + $lines[$i]->fk_product, + $lines[$i]->remise_percent, + $lines[$i]->info_bits, + $lines[$i]->fk_remise_except, + 'HT', + 0, + $date_start, + $date_end, + $product_type, + $lines[$i]->rang, + $lines[$i]->special_code, + $fk_parent_line, + $lines[$i]->fk_fournprice, + $lines[$i]->pa_ht, + $label, + $array_options, + $lines[$i]->fk_unit, + $object->origin, + $lines[$i]->rowid ); if ($result < 0) { @@ -407,26 +415,26 @@ if (empty($reshook)) /* Useless, already into the create if (! empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN)) { - $originforcontact = $object->origin; - $originidforcontact = $object->origin_id; - if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order - { - $originforcontact=$srcobject->origin; - $originidforcontact=$srcobject->origin_id; - } - $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; - $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'"; + $originforcontact = $object->origin; + $originidforcontact = $object->origin_id; + if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order + { + $originforcontact=$srcobject->origin; + $originidforcontact=$srcobject->origin_id; + } + $sqlcontact = "SELECT code, fk_socpeople FROM ".MAIN_DB_PREFIX."element_contact as ec, ".MAIN_DB_PREFIX."c_type_contact as ctc"; + $sqlcontact.= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$db->escape($originforcontact)."'"; - $resqlcontact = $db->query($sqlcontact); - if ($resqlcontact) - { - while($objcontact = $db->fetch_object($resqlcontact)) - { - //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n"; - $object->add_contact($objcontact->fk_socpeople, $objcontact->code); - } - } - else dol_print_error($resqlcontact); + $resqlcontact = $db->query($sqlcontact); + if ($resqlcontact) + { + while($objcontact = $db->fetch_object($resqlcontact)) + { + //print $objcontact->code.'-'.$objcontact->fk_socpeople."\n"; + $object->add_contact($objcontact->fk_socpeople, $objcontact->code); + } + } + else dol_print_error($resqlcontact); }*/ // Hooks @@ -445,15 +453,13 @@ if (empty($reshook)) $action = 'create'; } } else { - if (!$error) - { + if (!$error) { $object_id = $object->create($user); } } // Insert default contacts if defined - if ($object_id > 0) - { + if ($object_id > 0) { if (GETPOST('contactid', 'int')) { $result = $object->add_contact(GETPOST('contactid', 'int'), 'CUSTOMER', 'external'); if ($result < 0) { @@ -467,8 +473,7 @@ if (empty($reshook)) } // End of object creation, we show it - if ($object_id > 0 && !$error) - { + if ($object_id > 0 && !$error) { $db->commit(); header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object_id); exit(); @@ -478,32 +483,26 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - } elseif ($action == 'classifybilled' && $usercancreate) - { + } elseif ($action == 'classifybilled' && $usercancreate) { $ret = $object->classifyBilled($user); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'classifyunbilled' && $usercancreate) - { + } elseif ($action == 'classifyunbilled' && $usercancreate) { $ret = $object->classifyUnBilled(); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Positionne ref commande client - elseif ($action == 'setref_client' && $usercancreate) { + } elseif ($action == 'setref_client' && $usercancreate) { + // Positionne ref commande client $result = $object->set_ref_client($user, GETPOST('ref_client')); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action == 'setremise' && $usercancreate) { $result = $object->setDiscount($user, GETPOST('remise')); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action == 'setabsolutediscount' && $usercancreate) { @@ -533,26 +532,25 @@ if (empty($reshook)) } } elseif ($action == 'setmode' && $usercancreate) { $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); - } - - // Multicurrency Code - elseif ($action == 'setmulticurrencycode' && $usercancreate) { + } + } elseif ($action == 'setmulticurrencycode' && $usercancreate) { + // Multicurrency Code $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha')); - } - - // Multicurrency rate - elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + // Multicurrency rate $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx'))); } elseif ($action == 'setavailability' && $usercancreate) { $result = $object->availability(GETPOST('availability_id')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } elseif ($action == 'setdemandreason' && $usercancreate) { $result = $object->demand_reason(GETPOST('demand_reason_id')); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } elseif ($action == 'setconditions' && $usercancreate) { $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); if ($result < 0) { @@ -562,8 +560,9 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = GETPOST('lang_id', 'alpha'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -573,35 +572,26 @@ if (empty($reshook)) $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); } } - } - - // Set incoterm - elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { + } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { + // Set incoterm $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // bank account - elseif ($action == 'setbankaccount' && $usercancreate) { + } elseif ($action == 'setbankaccount' && $usercancreate) { + // bank account $result = $object->setBankAccount(GETPOST('fk_account', 'int')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // shipping method - elseif ($action == 'setshippingmethod' && $usercancreate) { + } elseif ($action == 'setshippingmethod' && $usercancreate) { + // shipping method $result = $object->setShippingMethod(GETPOST('shipping_method_id', 'int')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // warehouse - elseif ($action == 'setwarehouse' && $usercancreate) { + } elseif ($action == 'setwarehouse' && $usercancreate) { + // warehouse $result = $object->setWarehouse(GETPOST('warehouse_id', 'int')); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -619,8 +609,7 @@ if (empty($reshook)) foreach ($object->lines as $line) { $result = $object->updateline($line->id, $line->desc, $line->subprice, $line->qty, $line->remise_percent, $vat_rate, $localtax1_rate, $localtax2_rate, 'HT', $line->info_bits, $line->date_start, $line->date_end, $line->product_type, $line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->fk_unit, $line->multicurrency_subprice); } - } elseif ($action == 'addline' && $usercancreate) // Add a new line - { + } elseif ($action == 'addline' && $usercancreate) { // Add a new line $langs->load('errors'); $error = 0; @@ -630,8 +619,7 @@ if (empty($reshook)) $price_ht = price2num(GETPOST('price_ht'), 'MU'); $price_ht_devise = price2num(GETPOST('multicurrency_price_ht'), 'CU'); $prod_entry_mode = GETPOST('prod_entry_mode'); - if ($prod_entry_mode == 'free') - { + if ($prod_entry_mode == 'free') { $idprod = 0; $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); } else { @@ -665,8 +653,7 @@ if (empty($reshook)) setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && empty($idprod) && $price_ht == '' && $price_ht_devise == '') // Unit price can be 0 but not ''. Also price can be negative for order. - { + if ($prod_entry_mode == 'free' && empty($idprod) && $price_ht == '' && $price_ht_devise == '') { // Unit price can be 0 but not ''. Also price can be negative for order. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("UnitPriceHT")), null, 'errors'); $error++; } @@ -712,7 +699,9 @@ if (empty($reshook)) // Update if prices fields are defined $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $pu_ht = $prod->price; $pu_ttc = $prod->price_ttc; @@ -720,21 +709,21 @@ if (empty($reshook)) $price_base_type = $prod->price_base_type; // If price per segment - if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) - { + if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($object->thirdparty->price_level)) { $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) // using this option is a bug. kept for backward compatibility - { - if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level]; - if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level]; + if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility + if (isset($prod->multiprices_tva_tx[$object->thirdparty->price_level])) { + $tva_tx = $prod->multiprices_tva_tx[$object->thirdparty->price_level]; + } + if (isset($prod->multiprices_recuperableonly[$object->thirdparty->price_level])) { + $tva_npr = $prod->multiprices_recuperableonly[$object->thirdparty->price_level]; + } } - } - // If price per customer - elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) - { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { + // If price per customer require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; $prodcustprice = new Productcustomerprice($db); @@ -742,38 +731,37 @@ if (empty($reshook)) $filter = array('t.fk_product' => $prod->id, 't.fk_soc' => $object->thirdparty->id); $result = $prodcustprice->fetch_all('', '', 0, 0, $filter); - if ($result >= 0) - { - if (count($prodcustprice->lines) > 0) - { + if ($result >= 0) { + if (count($prodcustprice->lines) > 0) { $pu_ht = price($prodcustprice->lines[0]->price); $pu_ttc = price($prodcustprice->lines[0]->price_ttc); $price_min = price($prodcustprice->lines[0]->price_min); $price_base_type = $prodcustprice->lines[0]->price_base_type; $tva_tx = $prodcustprice->lines[0]->tva_tx; - if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) { + $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + } $tva_npr = $prodcustprice->lines[0]->recuperableonly; - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } } } else { setEventMessages($prodcustprice->error, $prodcustprice->errors, 'errors'); } - } - // If price per quantity - elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) - { - if ($prod->prices_by_qty[0]) // yes, this product has some prices per quantity - { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) { + // If price per quantity + if ($prod->prices_by_qty[0]) { // yes, this product has some prices per quantity // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp']. $pqp = GETPOST('pbq', 'int'); // Search price into product_price_by_qty from $prod->id - foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) - { - if ($priceforthequantityarray['rowid'] != $pqp) continue; + foreach ($prod->prices_by_qty_list[0] as $priceforthequantityarray) { + if ($priceforthequantityarray['rowid'] != $pqp) { + continue; + } // We found the price - if ($priceforthequantityarray['price_base_type'] == 'HT') - { + if ($priceforthequantityarray['price_base_type'] == 'HT') { $pu_ht = $priceforthequantityarray['unitprice']; } else { $pu_ttc = $priceforthequantityarray['unitprice']; @@ -782,21 +770,18 @@ if (empty($reshook)) break; } } - } - // If price per quantity and customer - elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) - { - if ($prod->prices_by_qty[$object->thirdparty->price_level]) // yes, this product has some prices per quantity - { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) { + // If price per quantity and customer + if ($prod->prices_by_qty[$object->thirdparty->price_level]) { // yes, this product has some prices per quantity // Search the correct price into loaded array product_price_by_qty using id of array retrieved into POST['pqp']. $pqp = GETPOST('pbq', 'int'); // Search price into product_price_by_qty from $prod->id - foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) - { - if ($priceforthequantityarray['rowid'] != $pqp) continue; + foreach ($prod->prices_by_qty_list[$object->thirdparty->price_level] as $priceforthequantityarray) { + if ($priceforthequantityarray['rowid'] != $pqp) { + continue; + } // We found the price - if ($priceforthequantityarray['price_base_type'] == 'HT') - { + if ($priceforthequantityarray['price_base_type'] == 'HT') { $pu_ht = $priceforthequantityarray['unitprice']; } else { $pu_ttc = $priceforthequantityarray['unitprice']; @@ -814,10 +799,9 @@ if (empty($reshook)) if (!empty($price_ht) || $price_ht === '0') { $pu_ht = price2num($price_ht, 'MU'); $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); - } - // On reevalue prix selon taux tva car taux tva transaction peut etre different - // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - elseif ($tmpvat != $tmpprodvat) { + } elseif ($tmpvat != $tmpprodvat) { + // On reevalue prix selon taux tva car taux tva transaction peut etre different + // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). if ($price_base_type != 'HT') { $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); } else { @@ -831,16 +815,18 @@ if (empty($reshook)) if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) + } + if (empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - $desc = (!empty($prod->multilangs [$outputlangs->defaultlang] ["description"])) ? $prod->multilangs [$outputlangs->defaultlang] ["description"] : $prod->description; + $desc = (!empty($prod->multilangs[$outputlangs->defaultlang]["description"])) ? $prod->multilangs[$outputlangs->defaultlang]["description"] : $prod->description; } else { $desc = $prod->description; } @@ -850,8 +836,11 @@ if (empty($reshook)) $product_desc=''; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; - else $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) { + $desc = $product_desc; + } else { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } // Add custom code and origin country into description if (empty($conf->global->MAIN_PRODUCT_DISABLE_CUSTOMCOUNTRYCODE) && (!empty($prod->customcode) || !empty($prod->country_code))) { @@ -860,28 +849,36 @@ if (empty($reshook)) if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'alpha')) + if (empty($newlang) && GETPOST('lang_id', 'alpha')) { $newlang = GETPOST('lang_id', 'alpha'); - if (empty($newlang)) + } + if (empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('products'); } - if (!empty($prod->customcode)) + if (!empty($prod->customcode)) { $tmptxt .= $outputlangs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; - if (!empty($prod->customcode) && !empty($prod->country_code)) + } + if (!empty($prod->customcode) && !empty($prod->country_code)) { $tmptxt .= ' - '; - if (!empty($prod->country_code)) + } + if (!empty($prod->country_code)) { $tmptxt .= $outputlangs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $outputlangs, 0); + } } else { - if (!empty($prod->customcode)) + if (!empty($prod->customcode)) { $tmptxt .= $langs->transnoentitiesnoconv("CustomCode").': '.$prod->customcode; - if (!empty($prod->customcode) && !empty($prod->country_code)) + } + if (!empty($prod->customcode) && !empty($prod->country_code)) { $tmptxt .= ' - '; - if (!empty($prod->country_code)) + } + if (!empty($prod->country_code)) { $tmptxt .= $langs->transnoentitiesnoconv("CountryOrigin").': '.getCountry($prod->country_code, 0, $db, $langs, 0); + } } $tmptxt .= ')'; $desc = dol_concatdesc($desc, $tmptxt); @@ -912,8 +909,9 @@ if (empty($reshook)) $desc = dol_htmlcleanlastbr($desc); $info_bits = 0; - if ($tva_npr) + if ($tva_npr) { $info_bits |= 0x01; + } if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && (!empty($price_min) && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) { $mesg = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, - 1, $conf->currency)); @@ -930,8 +928,9 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = GETPOST('lang_id', 'alpha'); - if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) + if (!empty($conf->global->MAIN_MULTILANGS) && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -977,13 +976,8 @@ if (empty($reshook)) } } } - } - - /* - * Update a line - */ - elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) - { + } elseif ($action == 'updateline' && $usercancreate && GETPOST('save')) { + // Update a line // Clean parameters $date_start = ''; $date_end = ''; @@ -996,8 +990,9 @@ if (empty($reshook)) // Define info_bits $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) + if (preg_match('/\*/', $vat_rate)) { $info_bits |= 0x01; + } // Define vat_rate $vat_rate = str_replace('*', '', $vat_rate); @@ -1020,7 +1015,9 @@ if (empty($reshook)) // Define special_code for special lines $special_code = GETPOST('special_code'); - if (!GETPOST('qty')) $special_code = 3; + if (!GETPOST('qty')) { + $special_code = 3; + } // Check minimum price $productid = GETPOST('productid', 'int'); @@ -1031,8 +1028,9 @@ if (empty($reshook)) $type = $product->type; $price_min = $product->price_min; - if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) + if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !empty($object->thirdparty->price_level)) { $price_min = $product->multiprices_min[$object->thirdparty->price_level]; + } $label = ((GETPOST('update_label') && GETPOST('product_label')) ? GETPOST('product_label') : ''); @@ -1052,12 +1050,9 @@ if (empty($reshook)) } if (!$error) { - if (empty($user->rights->margins->creer)) - { - foreach ($object->lines as &$line) - { - if ($line->id == GETPOST('lineid')) - { + if (empty($user->rights->margins->creer)) { + foreach ($object->lines as &$line) { + if ($line->id == GETPOST('lineid')) { $fournprice = $line->fk_fournprice; $buyingprice = $line->pa_ht; break; @@ -1071,10 +1066,12 @@ if (empty($reshook)) // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -1117,23 +1114,19 @@ if (empty($reshook)) } elseif ($action == 'updateline' && $usercancreate && GETPOST('cancel', 'alpha') == $langs->trans("Cancel")) { header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); // Pour reaffichage de la fiche en cours d'edition exit(); - } elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) - { + } elseif ($action == 'confirm_validate' && $confirm == 'yes' && $usercanvalidate) { $idwarehouse = GETPOST('idwarehouse', 'int'); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + 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 = $object->hasProductsOrServices(1); } // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) - { - if (!$idwarehouse || $idwarehouse == -1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -1142,15 +1135,17 @@ if (empty($reshook)) if (!$error) { $result = $object->valid($user, $idwarehouse); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -1164,25 +1159,20 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // Go back to draft status - elseif ($action == 'confirm_modif' && $usercancreate) { + } elseif ($action == 'confirm_modif' && $usercancreate) { + // Go back to draft status $idwarehouse = GETPOST('idwarehouse'); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + 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 = $object->hasProductsOrServices(1); } // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) - { - if (!$idwarehouse || $idwarehouse == -1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -1191,15 +1181,17 @@ if (empty($reshook)) if (!$error) { $result = $object->setDraft($user, $idwarehouse); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -1216,23 +1208,19 @@ if (empty($reshook)) if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanvalidate) - { + } elseif ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanvalidate) { $idwarehouse = GETPOST('idwarehouse', 'int'); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + 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 = $object->hasProductsOrServices(1); } // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) - { - if (!$idwarehouse || $idwarehouse == -1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) && $qualified_for_stock_change) { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -1248,58 +1236,53 @@ if (empty($reshook)) } } - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $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 ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('ORDER_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } - if ($error) $action = 'edit_extras'; + if ($error) { + $action = 'edit_extras'; + } } // add lines from objectlinked if ($action == 'import_lines_from_object' && $usercancreate && $object->statut == Commande::STATUS_DRAFT - ) - { + ) { $fromElement = GETPOST('fromelement'); $fromElementid = GETPOST('fromelementid'); $importLines = GETPOST('line_checkbox'); - if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) - { - if ($fromElement == 'commande') - { + if (!empty($importLines) && is_array($importLines) && !empty($fromElement) && ctype_alpha($fromElement) && !empty($fromElementid)) { + if ($fromElement == 'commande') { dol_include_once('/'.$fromElement.'/class/'.$fromElement.'.class.php'); $lineClassName = 'OrderLine'; - } elseif ($fromElement == 'propal') - { + } elseif ($fromElement == 'propal') { dol_include_once('/comm/'.$fromElement.'/class/'.$fromElement.'.class.php'); $lineClassName = 'PropaleLigne'; } $nextRang = count($object->lines) + 1; $importCount = 0; $error = 0; - foreach ($importLines as $lineId) - { + foreach ($importLines as $lineId) { $lineId = intval($lineId); $originLine = new $lineClassName($db); - if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) - { + if (intval($fromElementid) > 0 && $originLine->fetch($lineId) > 0) { $originLine->fetch_optionals(); $desc = $originLine->desc; $pu_ht = $originLine->subprice; @@ -1343,8 +1326,7 @@ if (empty($reshook)) } } - if ($error) - { + if ($error) { setEventMessages($langs->trans('ErrorsOnXLines', $error), null, 'errors'); } } @@ -1366,10 +1348,8 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - if (!$error && !empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) - { - if ($action == 'addcontact') - { + if (!$error && !empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { + if ($action == 'addcontact') { if ($object->id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); @@ -1387,21 +1367,15 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // bascule du statut d'un contact - elseif ($action == 'swapstatut') - { + } elseif ($action == 'swapstatut') { + // bascule du statut d'un contact if ($object->id > 0) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } - } - - // Efface un contact - elseif ($action == 'deletecontact') - { + } elseif ($action == 'deletecontact') { + // Efface un contact $result = $object->delete_contact($lineid); if ($result >= 0) { @@ -1425,16 +1399,18 @@ $form = new Form($db); $formfile = new FormFile($db); $formorder = new FormOrder($db); $formmargin = new FormMargin($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} // Mode creation -if ($action == 'create' && $usercancreate) -{ +if ($action == 'create' && $usercancreate) { print load_fiche_titre($langs->trans('CreateOrder'), '', 'order'); $soc = new Societe($db); - if ($socid > 0) + if ($socid > 0) { $res = $soc->fetch($socid); + } $remise_absolue = 0; @@ -1481,8 +1457,9 @@ if ($action == 'create' && $usercancreate) $classname = ucfirst($subelement); $objectsrc = new $classname($db); $objectsrc->fetch($originid); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { $objectsrc->fetch_lines(); + } $objectsrc->fetch_thirdparty(); // Replicate extrafields @@ -1505,12 +1482,17 @@ if ($action == 'create' && $usercancreate) $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER) ?-1 : ''; $date_delivery = (!empty($objectsrc->delivery_date) ? $objectsrc->delivery_date : ''); - if (empty($date_delivery)) $date_delivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : ''); + if (empty($date_delivery)) { + $date_delivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : ''); + } - if (!empty($conf->multicurrency->enabled)) - { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($conf->multicurrency->enabled)) { + if (!empty($objectsrc->multicurrency_code)) { + $currency_code = $objectsrc->multicurrency_code; + } + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) { + $currency_tx = $objectsrc->multicurrency_tx; + } } $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null)); @@ -1531,18 +1513,25 @@ if ($action == 'create' && $usercancreate) $remise_absolue = 0; $dateorder = empty($conf->global->MAIN_AUTOFILL_DATE_ORDER) ?-1 : ''; - if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) { + $currency_code = $soc->multicurrency_code; + } $note_private = $object->getDefaultCreateValueFor('note_private'); $note_public = $object->getDefaultCreateValueFor('note_public'); } //Warehouse default if null - if ($soc->fk_warehouse > 0) $warehouse_id = $soc->fk_warehouse; - if (!empty($conf->stock->enabled) && empty($warehouse_id) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) - { - if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) $warehouse_id = $conf->global->MAIN_DEFAULT_WAREHOUSE; - if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) $warehouse_id = $user->fk_warehouse; + if ($soc->fk_warehouse > 0) { + $warehouse_id = $soc->fk_warehouse; + } + if (!empty($conf->stock->enabled) && empty($warehouse_id) && !empty($conf->global->WAREHOUSE_ASK_WAREHOUSE_DURING_ORDER)) { + if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE)) { + $warehouse_id = $conf->global->MAIN_DEFAULT_WAREHOUSE; + } + if (empty($object->warehouse_id) && !empty($conf->global->MAIN_DEFAULT_WAREHOUSE_USER)) { + $warehouse_id = $user->fk_warehouse; + } } print ''; @@ -1552,7 +1541,9 @@ if ($action == 'create' && $usercancreate) print ''; print ''; print ''; - if (!empty($currency_tx)) print ''; + if (!empty($currency_tx)) { + print ''; + } print dol_get_fiche_head(''); @@ -1563,9 +1554,11 @@ if ($action == 'create' && $usercancreate) // Reference client print ''; - else print ''; + } else { + print ''; + } print ''; // Thirdparty @@ -1580,8 +1573,7 @@ if ($action == 'create' && $usercancreate) print ''; print ''."\n"; } @@ -2958,15 +3072,21 @@ if ($action == 'create') $invoice_predefined->fetch(GETPOST('fac_rec', 'int')); $dateinvoice = $invoice_predefined->date_when; // To use next gen date by default later - if (empty($projectid)) $projectid = $invoice_predefined->fk_project; + if (empty($projectid)) { + $projectid = $invoice_predefined->fk_project; + } $cond_reglement_id = $invoice_predefined->cond_reglement_id; $mode_reglement_id = $invoice_predefined->mode_reglement_id; $fk_account = $invoice_predefined->fk_account; $note_public = $invoice_predefined->note_public; $note_private = $invoice_predefined->note_private; - if (!empty($invoice_predefined->multicurrency_code)) $currency_code = $invoice_predefined->multicurrency_code; - if (!empty($invoice_predefined->multicurrency_tx)) $currency_tx = $invoice_predefined->multicurrency_tx; + if (!empty($invoice_predefined->multicurrency_code)) { + $currency_code = $invoice_predefined->multicurrency_code; + } + if (!empty($invoice_predefined->multicurrency_tx)) { + $currency_tx = $invoice_predefined->multicurrency_tx; + } $sql = 'SELECT r.rowid, r.titre as title, r.total_ttc'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_rec as r'; @@ -2985,8 +3105,7 @@ if ($action == 'create') while ($i < $num) { $objp = $db->fetch_object($resql); print '
'; print $form->selectDate($datestart, 'datestart', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', '', 'tzuserrel'); @@ -579,8 +709,12 @@ if ($resql) if (!empty($arrayfields['s.nom']['checked'])) { print ''; $formactions->form_select_status_action('formaction', $search_status, 1, 'search_status', 1, 2, 'minwidth100imp maxwidth125'); @@ -606,17 +744,37 @@ if ($resql) print "
'; // With edge and chrome the td overflow is not supported correctly when content is not full text. - if ($obj->fk_user_action > 0) - { + if ($obj->fk_user_action > 0) { $userstatic->fetch($obj->fk_user_action); print $userstatic->getNomUrl(-1); - } else print ' '; + } else { + print ' '; + } print ''; print $actionstatic->getTypePicto(); $labeltype = $obj->type_code; - if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) $labeltype = 'AC_OTH'; + if (empty($conf->global->AGENDA_USE_EVENT_TYPE) && empty($arraylist[$labeltype])) { + $labeltype = 'AC_OTH'; + } if ($actionstatic->type_code == 'AC_OTH' && $actionstatic->code == 'TICKET_MSG') { $labeltype = $langs->trans("Message"); } else { - if (!empty($arraylist[$labeltype])) $labeltype = $arraylist[$labeltype]; - if ($obj->type_code == 'AC_OTH_AUTO' && ($obj->type_code != $obj->code) && $labeltype && !empty($arraylist[$obj->code])) $labeltype .= ' - '.$arraylist[$obj->code]; // Use code in priority on type_code + if (!empty($arraylist[$labeltype])) { + $labeltype = $arraylist[$labeltype]; + } + if ($obj->type_code == 'AC_OTH_AUTO' && ($obj->type_code != $obj->code) && $labeltype && !empty($arraylist[$obj->code])) { + $labeltype .= ' - '.$arraylist[$obj->code]; // Use code in priority on type_code + } } print dol_trunc($labeltype, 28); print ''; print dol_print_date($db->jdate($obj->dp), $formatToUse, 'tzuser'); $late = 0; - if ($obj->percent == 0 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) $late = 1; - if ($obj->percent == 0 && !$obj->dp && $obj->dp2 && $db->jdate($obj->dp) < ($now - $delay_warning)) $late = 1; - if ($obj->percent > 0 && $obj->percent < 100 && $obj->dp2 && $db->jdate($obj->dp2) < ($now - $delay_warning)) $late = 1; - if ($obj->percent > 0 && $obj->percent < 100 && !$obj->dp2 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) $late = 1; - if ($late) print img_warning($langs->trans("Late")).' '; + if ($obj->percent == 0 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) { + $late = 1; + } + if ($obj->percent == 0 && !$obj->dp && $obj->dp2 && $db->jdate($obj->dp) < ($now - $delay_warning)) { + $late = 1; + } + if ($obj->percent > 0 && $obj->percent < 100 && $obj->dp2 && $db->jdate($obj->dp2) < ($now - $delay_warning)) { + $late = 1; + } + if ($obj->percent > 0 && $obj->percent < 100 && !$obj->dp2 && $obj->dp && $db->jdate($obj->dp) < ($now - $delay_warning)) { + $late = 1; + } + if ($late) { + print img_warning($langs->trans("Late")).' '; + } print ''; - if ($obj->socid > 0) - { + if ($obj->socid > 0) { $societestatic->id = $obj->socid; $societestatic->client = $obj->client; $societestatic->name = $obj->societe; $societestatic->email = $obj->socemail; print $societestatic->getNomUrl(1, '', 28); - } else print ' '; + } else { + print ' '; + } print ''; - if (!empty($actionstatic->socpeopleassigned)) - { + if (!empty($actionstatic->socpeopleassigned)) { $contactList = array(); - foreach ($actionstatic->socpeopleassigned as $socpeopleassigned) - { - if (!isset($contactListCache[$socpeopleassigned['id']])) - { + foreach ($actionstatic->socpeopleassigned as $socpeopleassigned) { + if (!isset($contactListCache[$socpeopleassigned['id']])) { // if no cache found we fetch it $contact = new Contact($db); - if ($contact->fetch($socpeopleassigned['id']) > 0) - { + if ($contact->fetch($socpeopleassigned['id']) > 0) { $contactListCache[$socpeopleassigned['id']] = $contact->getNomUrl(1, '', 0); $contactList[] = $contact->getNomUrl(1, '', 0); } @@ -782,8 +956,7 @@ if ($resql) if (!empty($contactList)) { print implode(', ', $contactList); } - } elseif ($obj->fk_contact > 0) //keep for retrocompatibility with faraway event - { + } elseif ($obj->fk_contact > 0) { //keep for retrocompatibility with faraway event $contactstatic->id = $obj->fk_contact; $contactstatic->email = $obj->email; $contactstatic->lastname = $obj->lastname; @@ -835,10 +1008,11 @@ if ($resql) } // Action column print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->id, $arrayofselected)) $selected = 1; + if (in_array($obj->id, $arrayofselected)) { + $selected = 1; + } print ''; } print '
'.$langs->trans('RefCustomer').''; - if (!empty($conf->global->MAIN_USE_PROPAL_REFCLIENT_FOR_ORDER) && !empty($origin) && !empty($originid)) + if (!empty($conf->global->MAIN_USE_PROPAL_REFCLIENT_FOR_ORDER) && !empty($origin) && !empty($originid)) { print '
'; print img_picto('', 'company').$form->select_company('', 'socid', '(s.client = 1 OR s.client = 2 OR s.client = 3)', 'SelectThirdParty', 0, 0, null, 0, 'minwidth175 maxwidth500 widthcentpercentminusxx'); // reload page to retrieve customer informations - if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) - { + if (empty($conf->global->RELOAD_PAGE_ON_CUSTOMER_CHANGE_DISABLED)) { print ''; } - if (!GETPOST('fac_rec', 'int')) print ' '; + if (!GETPOST('fac_rec', 'int')) { + print ' '; + } print '
'; print '
'; - } + } } if ($socid > 0) { @@ -3124,8 +3243,9 @@ if ($action == 'create') $tmp .= '> '; $text = ' '; $text .= ''; @@ -3146,8 +3266,9 @@ if ($action == 'create') if (is_array($facids)) { foreach ($facids as $facparam) { $options .= ''; @@ -3234,8 +3355,9 @@ if ($action == 'create') $newinvoice_static->paye = $valarray ['paye']; $optionsav .= '
'; print ''; - if ($usercancreate && $action != 'editmulticurrencyrate' && !empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) + if ($usercancreate && $action != 'editmulticurrencyrate' && !empty($object->brouillon) && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print ''; + } print '
'; print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print 'id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'
'; print '
'; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { @@ -4299,8 +4426,9 @@ if ($action == 'create') print ''; + } print '
'; print $langs->trans('BankAccount'); print ''; - if (($action != 'editbankaccount') && $usercancreate) + if (($action != 'editbankaccount') && $usercancreate) { print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
'; print '
'; if ($action == 'editbankaccount') { @@ -4318,8 +4446,11 @@ if ($action == 'create') print '
'; print $langs->trans('IncotermLabel'); print ''; - if ($usercancreate) print ''.img_edit().''; - else print ' '; + if ($usercancreate) { + print ''.img_edit().''; + } else { + print ' '; + } print '
'; print '
'; @@ -4351,8 +4482,7 @@ if ($action == 'create') print '
'; print '
'; - if ($action == 'editretainedwarranty') - { + if ($action == 'editretainedwarranty') { print ''; print ''; print ''; @@ -4575,7 +4705,9 @@ if ($action == 'create') print ''.$langs->trans('ListOfSituationInvoices').''.$langs->trans('Situation').''.$langs->trans('AmountHT').''.$langs->trans('AmountTTC').' '.$prev_invoice->getNomUrl(1).''.(($prev_invoice->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$prev_invoice->situation_counter.''.price($prev_invoice->total_ht).''.price($prev_invoice->total_ttc).''.$prev_invoice->getLibStatut(3, $tmptotalpaidforthisinvoice).''.$object->getNomUrl(1).''.(($object->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$object->situation_counter.''.price($object->total_ht).''.price($object->total_ttc).''.$object->getLibStatut(3, $object->getSommePaiement()).''.price($total_global_ht).''.price($total_global_ttc).' 
' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
' . $langs->trans('ListOfNextSituationInvoices') . '' . $langs->trans('AmountHT') . '' . $langs->trans('AmountTTC') . ' 
'.$next_invoice->getNomUrl(1).''.(($next_invoice->type == Facture::TYPE_CREDIT_NOTE) ? $langs->trans('situationInvoiceShortcode_AS') : $langs->trans('situationInvoiceShortcode_S')).$next_invoice->situation_counter.''.price($next_invoice->total_ht).''.price($next_invoice->total_ttc).''.$next_invoice->getLibStatut(3, $totalpaye).'
'.price($total_global_ht).''.price($total_global_ttc).' 
'; print ''; - if ($invoice->type == Facture::TYPE_CREDIT_NOTE) + if ($invoice->type == Facture::TYPE_CREDIT_NOTE) { print $langs->trans("CreditNote").' '; - if ($invoice->type == Facture::TYPE_DEPOSIT) + } + if ($invoice->type == Facture::TYPE_DEPOSIT) { print $langs->trans("Deposit").' '; + } print $invoice->getNomUrl(0); print ''; print '
'; $text = $langs->trans("HelpAbandonOther"); - if ($object->close_note) + if ($object->close_note) { $text .= '

'.$langs->trans("Reason").':'.$object->close_note; + } print ''; print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1); print ''; @@ -4932,8 +5083,9 @@ if ($action == 'create') // Remainder to pay back print '
'; print $langs->trans('RemainderToPayBack'); - if ($resteapayeraffiche > 0) + if ($resteapayeraffiche > 0) { print ' ('.$langs->trans('ExcessPaid').')'; + } print ' :'.price($sign * $resteapayeraffiche).' 
'.$objectstatic->getLibStatut(0).''.(isset($vals[$status]) ? $vals[$status] : 0).'
'; $result .= ''; return $result; @@ -269,8 +271,7 @@ function getDraftTable($maxCount = 500, $socid = 0) $total = 0; $i = 0; - while ($i < $nbofloop) - { + while ($i < $nbofloop) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -291,14 +292,11 @@ function getDraftTable($maxCount = 500, $socid = 0) $total += $obj->total_ttc; } - if ($num > $nbofloop) - { + if ($num > $nbofloop) { $result .= '
'.$langs->trans("XMoreLines", ($num - $nbofloop)).'
'.$langs->trans("Total").''.price($total).''.$langs->trans("LastCustomersBills", $maxCount).'
'; $result .= ''; return $result; @@ -360,8 +362,7 @@ function getLatestEditTable($maxCount = 5, $socid = 0) $companystatic = new Societe($db); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -421,18 +422,23 @@ function getOpenTable($maxCount = 500, $socid = 0) $sql .= ", f.datef as df, f.date_lim_reglement as datelimite"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."facture as f"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture').")"; $sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " ORDER BY f.rowid DESC"; $sql .= $db->plimit($maxCount, 0); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); } @@ -450,8 +456,7 @@ function getOpenTable($maxCount = 500, $socid = 0) $result .= '
'; $result .= ''; return $result; @@ -465,8 +470,7 @@ function getOpenTable($maxCount = 500, $socid = 0) $total = 0; $i = 0; - while ($i < $nbofloop) - { + while ($i < $nbofloop) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->id; @@ -490,8 +494,7 @@ function getOpenTable($maxCount = 500, $socid = 0) $result .= '
'; - if ($db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) - { + if ($db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) { $result .= img_warning($langs->trans("Late")); } @@ -513,14 +516,11 @@ function getOpenTable($maxCount = 500, $socid = 0) $total += $obj->total_ttc; } - if ($num > $nbofloop) - { + if ($num > $nbofloop) { $result .= '
'.$langs->trans("XMoreLines", ($num - $nbofloop)).'
'.$langs->trans("Total").''.price($total).'
'; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; $form->select_conditions_paiements($search_payment_term, 'search_payment_term', -1, 1, 1, 'maxwidth100'); print "'; $form->select_types_paiements($search_payment_mode, 'search_payment_mode', '', 0, 1, 1, 0, 1, 'maxwidth100'); print ''; print $form->selectyesno('search_recurring', $search_recurring, 1, false, 1); print ''; print ''; print ''; print ''; print ''; print ''; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) 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, 0, 0, '', 'widthauto valignmiddle'); print ''; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print ''; + } print ''; $formother->select_year($search_year_date_when ? $search_year_date_when : -1, 'search_year_date_when', 1, 20, 5, 0, 0, '', 'widthauto valignmiddle'); print ''; print ''; print ''; $liststatus = array( 0=>$langs->trans("Draft"), @@ -478,35 +558,67 @@ if ($resql) print "
'; print $invoicerectmp->getNomUrl(1); print ""; print "'.$companystatic->getNomUrl(1, 'customer').''.price($objp->total).''.price($objp->total_vat).''.price($objp->total_ttc).''; $form->form_conditions_reglement('', $objp->fk_cond_reglement, 'none'); print ''; $form->form_modes_reglement('', $objp->fk_mode_reglement, 'none'); print ''.yn($objp->frequency ? 1 : 0).''.($objp->frequency > 0 ? $objp->frequency : '').''.($objp->frequency > 0 ? $objp->unit_frequency : '').''; print ($objp->frequency > 0 ? $objp->nb_gen_done.($objp->nb_gen_max > 0 ? ' / '.$objp->nb_gen_max : '') : ''.$langs->trans('NA').''); print ''; print ($objp->frequency > 0 ? dol_print_date($db->jdate($objp->date_last_gen), 'day') : ''.$langs->trans('NA').''); print ''; print '
'; print ($objp->frequency ? ($invoicerectmp->isMaxNbGenReached() ? '' : '').dol_print_date($db->jdate($objp->date_when), 'day').($invoicerectmp->isMaxNbGenReached() ? '' : '') : ''.$langs->trans('NA').''); - if (!$invoicerectmp->isMaxNbGenReached()) - { - if (!$objp->suspended && $objp->frequency > 0 && $db->jdate($objp->date_when) && $db->jdate($objp->date_when) < $now) print img_warning($langs->trans("Late")); + if (!$invoicerectmp->isMaxNbGenReached()) { + if (!$objp->suspended && $objp->frequency > 0 && $db->jdate($objp->date_when) && $db->jdate($objp->date_when) < $now) { + print img_warning($langs->trans("Late")); + } } else { print img_info($langs->trans("MaxNumberOfGenerationReached")); } print '
'; print '
'; print dol_print_date($db->jdate($objp->datec), 'dayhour'); print ''; print dol_print_date($db->jdate($objp->tms), 'dayhour'); print ''; print $invoicerectmp->getLibStatut(3, 0); print ''; - if ($user->rights->facture->creer && empty($invoicerectmp->suspended)) - { - if ($invoicerectmp->isMaxNbGenReached()) - { + if ($user->rights->facture->creer && empty($invoicerectmp->suspended)) { + if ($invoicerectmp->isMaxNbGenReached()) { print $langs->trans("MaxNumberOfGenerationReached"); - } elseif (empty($objp->frequency) || $db->jdate($objp->date_when) <= $today) - { + } elseif (empty($objp->frequency) || $db->jdate($objp->date_when) <= $today) { print ''; print $langs->trans("CreateBill").''; } else { @@ -663,7 +796,9 @@ if ($resql) } else { print " "; } - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "
'.$langs->trans("NoRecordFound").'
'."\n"; @@ -781,22 +989,19 @@ if ($resql) print ''; } // Ref - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print ''; } // Ref customer - if (!empty($arrayfields['f.ref_client']['checked'])) - { + if (!empty($arrayfields['f.ref_client']['checked'])) { print ''; } // Type - if (!empty($arrayfields['f.type']['checked'])) - { + if (!empty($arrayfields['f.type']['checked'])) { print ''; } // Date invoice - if (!empty($arrayfields['f.date']['checked'])) - { + if (!empty($arrayfields['f.date']['checked'])) { print ''; } // Date valid - if (!empty($arrayfields['f.date_valid']['checked'])) - { + if (!empty($arrayfields['f.date_valid']['checked'])) { print ''; } // Date due - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) - { + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { print ''; } // Project ref - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print ''; } // Project label - if (!empty($arrayfields['p.title']['checked'])) - { + if (!empty($arrayfields['p.title']['checked'])) { print ''; } // Thirdparty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; } // Alias - if (!empty($arrayfields['s.name_alias']['checked'])) - { + if (!empty($arrayfields['s.name_alias']['checked'])) { print ''; } // Town - if (!empty($arrayfields['s.town']['checked'])) print ''; + if (!empty($arrayfields['s.town']['checked'])) { + print ''; + } // Zip - if (!empty($arrayfields['s.zip']['checked'])) print ''; + if (!empty($arrayfields['s.zip']['checked'])) { + print ''; + } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print ''; } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; } // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print ''; } // Payment mode - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { print ''; } // Payment terms - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { print ''; } // Module source - if (!empty($arrayfields['f.module_source']['checked'])) - { + if (!empty($arrayfields['f.module_source']['checked'])) { print ''; } // POS Terminal - if (!empty($arrayfields['f.pos_source']['checked'])) - { + if (!empty($arrayfields['f.pos_source']['checked'])) { print ''; } - if (!empty($arrayfields['f.total_ht']['checked'])) - { + if (!empty($arrayfields['f.total_ht']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['f.total_vat']['checked'])) - { + if (!empty($arrayfields['f.total_vat']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['f.total_localtax1']['checked'])) - { + if (!empty($arrayfields['f.total_localtax1']['checked'])) { // Localtax1 print ''; } - if (!empty($arrayfields['f.total_localtax2']['checked'])) - { + if (!empty($arrayfields['f.total_localtax2']['checked'])) { // Localtax2 print ''; } - if (!empty($arrayfields['f.total_ttc']['checked'])) - { + if (!empty($arrayfields['f.total_ttc']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { // Author print ''; } - if (!empty($arrayfields['f.retained_warranty']['checked'])) - { + if (!empty($arrayfields['f.retained_warranty']['checked'])) { print ''; } - if (!empty($arrayfields['dynamount_payed']['checked'])) - { + if (!empty($arrayfields['dynamount_payed']['checked'])) { print ''; } - if (!empty($arrayfields['rtp']['checked'])) - { + if (!empty($arrayfields['rtp']['checked'])) { print ''; } - if (!empty($arrayfields['f.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_code']['checked'])) { // Currency print ''; } - if (!empty($arrayfields['f.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { // Currency rate print ''; } - if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { // Amount print ''; } - if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) - { + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { print ''; } - if (!empty($arrayfields['multicurrency_rtp']['checked'])) - { + if (!empty($arrayfields['multicurrency_rtp']['checked'])) { print ''; } - if (!empty($arrayfields['f.date_closing']['checked'])) - { + if (!empty($arrayfields['f.date_closing']['checked'])) { print ''; } - if (!empty($arrayfields['total_pa']['checked'])) - { + if (!empty($arrayfields['total_pa']['checked'])) { print ''; } - if (!empty($arrayfields['total_margin']['checked'])) - { + if (!empty($arrayfields['total_margin']['checked'])) { print ''; } - if (!empty($arrayfields['total_margin_rate']['checked'])) - { + if (!empty($arrayfields['total_margin_rate']['checked'])) { print ''; } - if (!empty($arrayfields['total_mark_rate']['checked'])) - { + if (!empty($arrayfields['total_mark_rate']['checked'])) { print ''; } @@ -1061,32 +1234,27 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print ''; } // Date modification - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print ''; } - if (!empty($arrayfields['f.note_public']['checked'])) - { + if (!empty($arrayfields['f.note_public']['checked'])) { // Note public print ''; } - if (!empty($arrayfields['f.note_private']['checked'])) - { + if (!empty($arrayfields['f.note_private']['checked'])) { // Note private print ''; } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '\n"; print ''; - if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.ref']['checked'])) print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.ref_client']['checked'])) print_liste_field_titre($arrayfields['f.ref_client']['label'], $_SERVER["PHP_SELF"], 'f.ref_client', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.date']['checked'])) print_liste_field_titre($arrayfields['f.date']['label'], $_SERVER['PHP_SELF'], 'f.datef', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.date_valid']['checked'])) print_liste_field_titre($arrayfields['f.date_valid']['label'], $_SERVER['PHP_SELF'], 'f.date_valid', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['p.title']['checked'])) print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER['PHP_SELF'], "p.title", '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.name_alias']['checked'])) print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER['PHP_SELF'], 's.name_alias', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.module_source']['checked'])) print_liste_field_titre($arrayfields['f.module_source']['label'], $_SERVER["PHP_SELF"], "f.module_source", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.pos_source']['checked'])) print_liste_field_titre($arrayfields['f.pos_source']['label'], $_SERVER["PHP_SELF"], "f.pos_source", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'], $_SERVER['PHP_SELF'], 'f.tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['f.retained_warranty']['checked'])) print_liste_field_titre($arrayfields['f.retained_warranty']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'align="right"', $sortfield, $sortorder); - if (!empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_code', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_tx', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['multicurrency_dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['multicurrency_rtp']['checked'])) print_liste_field_titre($arrayfields['multicurrency_rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['total_pa']['checked'])) print_liste_field_titre($arrayfields['total_pa']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['total_margin']['checked'])) print_liste_field_titre($arrayfields['total_margin']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['total_margin_rate']['checked'])) print_liste_field_titre($arrayfields['total_margin_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['total_mark_rate']['checked'])) print_liste_field_titre($arrayfields['total_mark_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.ref']['checked'])) { + print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.ref_client']['checked'])) { + print_liste_field_titre($arrayfields['f.ref_client']['label'], $_SERVER["PHP_SELF"], 'f.ref_client', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.type']['checked'])) { + print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.date']['checked'])) { + print_liste_field_titre($arrayfields['f.date']['label'], $_SERVER['PHP_SELF'], 'f.datef', '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.date_valid']['checked'])) { + print_liste_field_titre($arrayfields['f.date_valid']['label'], $_SERVER['PHP_SELF'], 'f.date_valid', '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.ref']['checked'])) { + print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['p.title']['checked'])) { + print_liste_field_titre($arrayfields['p.title']['label'], $_SERVER['PHP_SELF'], "p.title", '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.name_alias']['checked'])) { + print_liste_field_titre($arrayfields['s.name_alias']['label'], $_SERVER['PHP_SELF'], 's.name_alias', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['state.nom']['checked'])) { + print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['country.code_iso']['checked'])) { + print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['f.module_source']['checked'])) { + print_liste_field_titre($arrayfields['f.module_source']['label'], $_SERVER["PHP_SELF"], "f.module_source", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['f.pos_source']['checked'])) { + print_liste_field_titre($arrayfields['f.pos_source']['label'], $_SERVER["PHP_SELF"], "f.pos_source", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['f.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.total_vat']['checked'])) { + print_liste_field_titre($arrayfields['f.total_vat']['label'], $_SERVER['PHP_SELF'], 'f.tva', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.total_localtax1']['checked'])) { + print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.total_localtax2']['checked'])) { + print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['u.login']['checked'])) { + print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.retained_warranty']['checked'])) { + print_liste_field_titre($arrayfields['f.retained_warranty']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'align="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['dynamount_payed']['checked'])) { + print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['rtp']['checked'])) { + print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_code']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { + print_liste_field_titre($arrayfields['multicurrency_dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['multicurrency_rtp']['checked'])) { + print_liste_field_titre($arrayfields['multicurrency_rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['total_pa']['checked'])) { + print_liste_field_titre($arrayfields['total_pa']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['total_margin']['checked'])) { + print_liste_field_titre($arrayfields['total_margin']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['total_margin_rate']['checked'])) { + print_liste_field_titre($arrayfields['total_margin_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['total_mark_rate']['checked'])) { + print_liste_field_titre($arrayfields['total_mark_rate']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (!empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (!empty($arrayfields['f.date_closing']['checked'])) print_liste_field_titre($arrayfields['f.date_closing']['label'], $_SERVER["PHP_SELF"], "f.date_closing", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (!empty($arrayfields['f.note_public']['checked'])) print_liste_field_titre($arrayfields['f.note_public']['label'], $_SERVER["PHP_SELF"], "f.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.note_private']['checked'])) print_liste_field_titre($arrayfields['f.note_private']['label'], $_SERVER["PHP_SELF"], "f.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "f.fk_statut,f.paye,f.type,dynamount_payed", "", $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.datec']['checked'])) { + print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.tms']['checked'])) { + print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.date_closing']['checked'])) { + print_liste_field_titre($arrayfields['f.date_closing']['label'], $_SERVER["PHP_SELF"], "f.date_closing", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.note_public']['checked'])) { + print_liste_field_titre($arrayfields['f.note_public']['label'], $_SERVER["PHP_SELF"], "f.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.note_private']['checked'])) { + print_liste_field_titre($arrayfields['f.note_private']['label'], $_SERVER["PHP_SELF"], "f.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "f.fk_statut,f.paye,f.type,dynamount_payed", "", $param, 'class="right"', $sortfield, $sortorder); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; @@ -1159,12 +1419,10 @@ if ($resql) $discount = new DiscountAbsolute($db); $userstatic = new User($db); - if ($num > 0) - { + if ($num > 0) { $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $datelimit = $db->jdate($obj->datelimite); @@ -1193,8 +1451,7 @@ if ($resql) $facturestatic->note_public = $obj->note_public; $facturestatic->note_private = $obj->note_private; - if ($conf->global->INVOICE_USE_SITUATION && $conf->global->INVOICE_USE_RETAINED_WARRANTY) - { + if ($conf->global->INVOICE_USE_SITUATION && $conf->global->INVOICE_USE_RETAINED_WARRANTY) { $facturestatic->retained_warranty = $obj->retained_warranty; $facturestatic->retained_warranty_date_limit = $obj->retained_warranty_date_limit; $facturestatic->situation_final = $obj->retained_warranty_date_limit; @@ -1250,8 +1507,7 @@ if ($resql) } print ''; @@ -1262,15 +1518,13 @@ if ($resql) } // Ref - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Customer ref - if (!empty($arrayfields['f.ref_client']['checked'])) - { + if (!empty($arrayfields['f.ref_client']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type - if (!empty($arrayfields['f.type']['checked'])) - { + if (!empty($arrayfields['f.type']['checked'])) { print '"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date - if (!empty($arrayfields['f.date']['checked'])) - { + if (!empty($arrayfields['f.date']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date - if (!empty($arrayfields['f.date_valid']['checked'])) - { + if (!empty($arrayfields['f.date_valid']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date limit - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) - { + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project ref - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project title - if (!empty($arrayfields['p.title']['checked'])) - { + if (!empty($arrayfields['p.title']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Third party - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Alias - if (!empty($arrayfields['s.name_alias']['checked'])) - { + if (!empty($arrayfields['s.name_alias']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Staff - if (!empty($arrayfields['staff.code']['checked'])) - { + if (!empty($arrayfields['staff.code']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment mode - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment terms - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Module Source - if (!empty($arrayfields['f.module_source']['checked'])) - { + if (!empty($arrayfields['f.module_source']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // POS Terminal - if (!empty($arrayfields['f.pos_source']['checked'])) - { + if (!empty($arrayfields['f.pos_source']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['f.total_ht']['checked'])) - { + if (!empty($arrayfields['f.total_ht']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ht'; + } $totalarray['val']['f.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['f.total_vat']['checked'])) - { + if (!empty($arrayfields['f.total_vat']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_vat'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_vat'; + } $totalarray['val']['f.total_vat'] += $obj->total_vat; } // Amount LocalTax1 - if (!empty($arrayfields['f.total_localtax1']['checked'])) - { + if (!empty($arrayfields['f.total_localtax1']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax1'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax1'; + } $totalarray['val']['f.total_localtax1'] += $obj->total_localtax1; } // Amount LocalTax2 - if (!empty($arrayfields['f.total_localtax2']['checked'])) - { + if (!empty($arrayfields['f.total_localtax2']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax2'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax2'; + } $totalarray['val']['f.total_localtax2'] += $obj->total_localtax2; } // Amount TTC - if (!empty($arrayfields['f.total_ttc']['checked'])) - { + if (!empty($arrayfields['f.total_ttc']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; + } $totalarray['val']['f.total_ttc'] += $obj->total_ttc; } // Author - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { $userstatic->id = $obj->fk_user_author; $userstatic->login = $obj->login; print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['f.retained_warranty']['checked'])) - { + if (!empty($arrayfields['f.retained_warranty']['checked'])) { print ''; } - if (!empty($arrayfields['dynamount_payed']['checked'])) - { + if (!empty($arrayfields['dynamount_payed']['checked'])) { print ''; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalam'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'totalam'; + } $totalarray['val']['totalam'] += $totalpay; } // Pending amount - if (!empty($arrayfields['rtp']['checked'])) - { + if (!empty($arrayfields['rtp']['checked'])) { print ''; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'rtp'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'rtp'; + } $totalarray['val']['rtp'] += $remaintopay; } // Currency - if (!empty($arrayfields['f.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_code']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Currency rate - if (!empty($arrayfields['f.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount VAT - if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount TTC - if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) - { + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { print ''; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Pending amount - if (!empty($arrayfields['multicurrency_rtp']['checked'])) - { + if (!empty($arrayfields['multicurrency_rtp']['checked'])) { print ''; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Total buying or cost price - if (!empty($arrayfields['total_pa']['checked'])) - { + if (!empty($arrayfields['total_pa']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Total margin - if (!empty($arrayfields['total_margin']['checked'])) - { + if (!empty($arrayfields['total_margin']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'total_margin'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'total_margin'; + } $totalarray['val']['total_margin'] += $marginInfo['total_margin']; } // Total margin rate - if (!empty($arrayfields['total_margin_rate']['checked'])) - { + if (!empty($arrayfields['total_margin_rate']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // total mark rate - if (!empty($arrayfields['total_mark_rate']['checked'])) - { + if (!empty($arrayfields['total_mark_rate']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -1627,64 +1939,73 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date closing - if (!empty($arrayfields['f.date_closing']['checked'])) - { + if (!empty($arrayfields['f.date_closing']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note public - if (!empty($arrayfields['f.note_public']['checked'])) - { + if (!empty($arrayfields['f.note_public']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note private - if (!empty($arrayfields['f.note_private']['checked'])) - { + if (!empty($arrayfields['f.note_private']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column (Show the massaction button only when this page is not opend from the Extended POS) print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; @@ -1709,7 +2030,9 @@ if ($resql) // Show the file area only when this page is not opend from the Extended POS if ($contextpage != 'poslist') { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/compta/facture/note.php b/htdocs/compta/facture/note.php index aa3bd40c591..23d4afb0417 100644 --- a/htdocs/compta/facture/note.php +++ b/htdocs/compta/facture/note.php @@ -43,7 +43,9 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = 0; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'facture', $id, ''); $object = new Facture($db); @@ -70,8 +72,7 @@ llxHeader('', $title, $helpurl); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object = new Facture($db); $object->fetch($id, $ref); @@ -94,15 +95,14 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1, 'customer'); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') + 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 .= ''; diff --git a/htdocs/compta/facture/prelevement.php b/htdocs/compta/facture/prelevement.php index 26bab3c1984..b6cf7ec5c06 100644 --- a/htdocs/compta/facture/prelevement.php +++ b/htdocs/compta/facture/prelevement.php @@ -48,7 +48,9 @@ $action = GETPOST('action', 'aZ09'); $type = GETPOST('type', 'aZ09'); $fieldid = (!empty($ref) ? 'ref' : 'rowid'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} if ($type == 'bank-transfer') { $object = new FactureFournisseur($db); @@ -57,12 +59,10 @@ if ($type == 'bank-transfer') { } // Load object -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); $isdraft = (($object->statut == FactureFournisseur::STATUS_DRAFT) ? 1 : 0); - if ($ret > 0) - { + if ($ret > 0) { $object->fetch_thirdparty(); } } @@ -71,10 +71,14 @@ $hookmanager->initHooks(array('directdebitcard', 'globalcard')); if ($type == 'bank-transfer') { $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture', 'fk_soc', $fieldid, $isdraft); - if (!$user->rights->fournisseur->facture->lire) accessforbidden(); + if (!$user->rights->fournisseur->facture->lire) { + accessforbidden(); + } } else { $result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid, $isdraft); - if (!$user->rights->facture->lire) accessforbidden(); + if (!$user->rights->facture->lire) { + accessforbidden(); + } } @@ -84,14 +88,13 @@ if ($type == 'bank-transfer') { $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if ($action == "new") - { - if ($object->id > 0) - { +if (empty($reshook)) { + if ($action == "new") { + if ($object->id > 0) { $db->begin(); $newtype = $type; @@ -102,8 +105,7 @@ if (empty($reshook)) } $result = $object->demande_prelevement($user, price2num(GETPOST('withdraw_request_amount', 'alpha')), $newtype, $sourcetype); - if ($result > 0) - { + if ($result > 0) { $db->commit(); setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); @@ -115,13 +117,10 @@ if (empty($reshook)) $action = ''; } - if ($action == "delete") - { - if ($object->id > 0) - { + if ($action == "delete") { + if ($object->id > 0) { $result = $object->demande_prelevement_delete($user, GETPOST('did', 'int')); - if ($result == 0) - { + if ($result == 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id.'&type='.$type); exit; } @@ -155,8 +154,7 @@ llxHeader('', $title, $helpurl); /* */ /* *************************************************************************** */ -if ($object->id > 0) -{ +if ($object->id > 0) { $selleruserevenustamp = $mysoc->useRevenueStamp(); $totalpaye = $object->getSommePaiement(); @@ -170,7 +168,9 @@ if ($object->id > 0) //$resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT); $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); - if ($object->paye) $resteapayer = 0; + if ($object->paye) { + $resteapayer = 0; + } $resteapayeraffiche = $resteapayer; if ($type == 'bank-transfer') { @@ -202,8 +202,7 @@ if ($object->id > 0) } $author = new User($db); - if ($object->user_author) - { + if ($object->user_author) { $author->fetch($object->user_author); } @@ -234,17 +233,19 @@ if ($object->id > 0) // Thirdparty $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); if ($type == 'bank-transfer') { - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; + } } else { - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherBills").')'; + } } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { + if ($user->rights->facture->creer) { if ($action != 'classify') { //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; $morehtmlref .= ' : '; @@ -293,8 +294,7 @@ if ($object->id > 0) if ($object->module_source) { print ' ('.$langs->trans("POS").' '.$object->module_source.' - '.$langs->trans("Terminal").' '.$object->pos_source.')'; } - if ($object->type == $object::TYPE_REPLACEMENT) - { + if ($object->type == $object::TYPE_REPLACEMENT) { if ($type == 'bank-transfer') { $facreplaced = new FactureFournisseur($db); } else { @@ -303,8 +303,7 @@ if ($object->id > 0) $facreplaced->fetch($object->fk_facture_source); print ' ('.$langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)).')'; } - if ($object->type == $object::TYPE_CREDIT_NOTE) - { + if ($object->type == $object::TYPE_CREDIT_NOTE) { if ($type == 'bank-transfer') { $facusing = new FactureFournisseur($db); } else { @@ -315,14 +314,15 @@ if ($object->id > 0) } $facidavoir = $object->getListIdAvoirFromInvoice(); - if (count($facidavoir) > 0) - { + if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i = 0; - foreach ($facidavoir as $id) - { - if ($i == 0) print ' '; - else print ','; + foreach ($facidavoir as $id) { + if ($i == 0) { + print ' '; + } else { + print ','; + } if ($type == 'bank-transfer') { $facavoir = new FactureFournisseur($db); } else { @@ -374,14 +374,14 @@ if ($object->id > 0) print '
'; print ''; print ''; print ''; print ''; $listtype = array( Facture::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), @@ -804,8 +1009,7 @@ if ($resql) Facture::TYPE_CREDIT_NOTE=>$langs->trans("InvoiceAvoir"), Facture::TYPE_DEPOSIT=>$langs->trans("InvoiceDeposit"), ); - if (!empty($conf->global->INVOICE_USE_SITUATION)) - { + if (!empty($conf->global->INVOICE_USE_SITUATION)) { $listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation"); } //$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma"); // A proformat invoice is not an invoice but must be an order. @@ -813,8 +1017,7 @@ if ($resql) print ''; print '
'; print $form->selectDate($search_date_start ? $search_date_start : -1, 'search_date_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); @@ -825,8 +1028,7 @@ if ($resql) print '
'; print '
'; print $form->selectDate($search_date_valid_start ? $search_date_valid_start : -1, 'search_date_valid_start', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); @@ -837,8 +1039,7 @@ if ($resql) print '
'; print '
'; /* @@ -853,202 +1054,174 @@ if ($resql) print '
'; print ''; print ''; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print ''; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), 'maxwidth100', 1); print ''; $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 10); print ''; $form->select_conditions_paiements($search_paymentterms, 'search_paymentterms', -1, 1, 1); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; $liststatus = array('0'=>$langs->trans("BillShortStatusDraft"), '1'=>$langs->trans("BillShortStatusNotPaid"), '2'=>$langs->trans("BillShortStatusPaid"), '1,2'=>$langs->trans("BillShortStatusNotPaid").'+'.$langs->trans("BillShortStatusPaid"), '3'=>$langs->trans("BillShortStatusCanceled")); print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', '', 1); @@ -1100,58 +1268,150 @@ if ($resql) print "
'; print ''; print '
'; - if ($contextpage == 'poslist') - { + if ($contextpage == 'poslist') { print $obj->ref; } else { print $facturestatic->getNomUrl(1, '', 200, 0, '', 0, 1); @@ -1285,339 +1539,397 @@ if ($resql) print '
'; print "
'; print $obj->ref_client; print ''; print $facturestatic->getLibType(); print "'; print dol_print_date($db->jdate($obj->df), 'day'); print ''; print dol_print_date($db->jdate($obj->date_valid), 'day'); print ''.dol_print_date($datelimit, 'day'); - if ($facturestatic->hasDelay()) - { + if ($facturestatic->hasDelay()) { print img_warning($langs->trans('Alert').' - '.$langs->trans('Late')); } print ''; - if ($obj->project_id > 0) - { + if ($obj->project_id > 0) { print $projectstatic->getNomUrl(1); } print ''; - if ($obj->project_id > 0) - { + if ($obj->project_id > 0) { print $projectstatic->title; } print ''; - if ($contextpage == 'poslist') - { + if ($contextpage == 'poslist') { print $thirdpartystatic->name; } else { print $thirdpartystatic->getNomUrl(1, 'customer'); } print ''; print $obj->name_alias; print ''; print $obj->town; print ''; print $obj->zip; print '".$obj->state_name."'; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print ''; - if (!is_array($typenArray) || count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); + if (!is_array($typenArray) || count($typenArray) == 0) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print ''; - if (!is_array($staffArray) || count($staffArray) == 0) $staffArray = $formcompany->effectif_array(1); + if (!is_array($staffArray) || count($staffArray) == 0) { + $staffArray = $formcompany->effectif_array(1); + } print $staffArray[$obj->staff_code]; print ''; $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); print ''; $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none'); print ''; print $obj->module_source; print ''; print $obj->pos_source; print ''.price($obj->total_ht)."'.price($obj->total_vat)."'.price($obj->total_localtax1)."'.price($obj->total_localtax2)."'.price($obj->total_ttc)."'; - if ($userstatic->id) print $userstatic->getLoginUrl(1); - else print ' '; + if ($userstatic->id) { + print $userstatic->getLoginUrl(1); + } else { + print ' '; + } print "'.(!empty($obj->retained_warranty) ?price($obj->retained_warranty).'%' : ' ').''.(!empty($totalpay) ?price($totalpay, 0, $langs) : ' ').''; print (!empty($remaintopay) ? price($remaintopay, 0, $langs) : ' '); print ''.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."'; $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); print "'.price($obj->multicurrency_total_ht)."'.price($obj->multicurrency_total_vat)."'.price($obj->multicurrency_total_ttc)."'.(!empty($multicurrency_totalpay) ?price($multicurrency_totalpay, 0, $langs) : ' ').''; print (!empty($multicurrency_remaintopay) ? price($multicurrency_remaintopay, 0, $langs) : ' '); print ''.price($marginInfo['pa_total']).''.price($marginInfo['total_margin']).''.(($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], null, null, null, null, 2).'%').''.(($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], null, null, null, null, 2).'%').''; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_closing), 'dayhour', 'tzuser'); print ''; print dol_escape_htmltag($obj->note_public); print ''; print dol_escape_htmltag($obj->note_private); print ''; print $facturestatic->LibStatut($obj->paye, $obj->fk_statut, 5, $paiement, $obj->type); print "'; - if (($massactionbutton || $massaction) && $contextpage != 'poslist') // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if (($massactionbutton || $massaction) && $contextpage != 'poslist') { // 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->id, $arrayofselected)) $selected = 1; + if (in_array($obj->id, $arrayofselected)) { + $selected = 1; + } print ''; } print '
'; - if ($object->type != $object::TYPE_CREDIT_NOTE && $action != 'editinvoicedate' && !empty($object->brouillon) && $user->rights->facture->creer) print ''; + if ($object->type != $object::TYPE_CREDIT_NOTE && $action != 'editinvoicedate' && !empty($object->brouillon) && $user->rights->facture->creer) { + print ''; + } print '
'; print $langs->trans('DateInvoice'); print 'id.'">'.img_edit($langs->trans('SetDate'), 1).'id.'">'.img_edit($langs->trans('SetDate'), 1).'
'; print '
'; - if ($object->type != $object::TYPE_CREDIT_NOTE) - { - if ($action == 'editinvoicedate') - { + if ($object->type != $object::TYPE_CREDIT_NOTE) { + if ($action == 'editinvoicedate') { $form->form_date($_SERVER['PHP_SELF'].'?id='.$object->id, $object->date, 'invoicedate'); } else { print dol_print_date($object->date, 'day'); @@ -397,13 +397,13 @@ if ($object->id > 0) print ''; - if ($object->type != $object::TYPE_CREDIT_NOTE && $action != 'editconditions' && !empty($object->brouillon) && $user->rights->facture->creer) print ''; + if ($object->type != $object::TYPE_CREDIT_NOTE && $action != 'editconditions' && !empty($object->brouillon) && $user->rights->facture->creer) { + print ''; + } print '
'; print $langs->trans('PaymentConditionsShort'); print 'id.'">'.img_edit($langs->trans('SetConditions'), 1).'id.'">'.img_edit($langs->trans('SetConditions'), 1).'
'; print '
'; - if ($object->type != $object::TYPE_CREDIT_NOTE) - { - if ($action == 'editconditions') - { + if ($object->type != $object::TYPE_CREDIT_NOTE) { + if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none'); @@ -418,18 +418,18 @@ if ($object->id > 0) print ''; - if ($object->type != $object::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && !empty($object->brouillon) && $user->rights->facture->creer) print ''; + if ($object->type != $object::TYPE_CREDIT_NOTE && $action != 'editpaymentterm' && !empty($object->brouillon) && $user->rights->facture->creer) { + print ''; + } print '
'; print $langs->trans('DateMaxPayment'); print 'id.'">'.img_edit($langs->trans('SetDate'), 1).'id.'">'.img_edit($langs->trans('SetDate'), 1).'
'; print '
'; - if ($object->type != $object::TYPE_CREDIT_NOTE) - { + if ($object->type != $object::TYPE_CREDIT_NOTE) { $duedate = $object->date_lim_reglement; if ($type == 'bank-transfer') { $duedate = $object->date_echeance; } - if ($action == 'editpaymentterm') - { + if ($action == 'editpaymentterm') { $form->form_date($_SERVER['PHP_SELF'].'?id='.$object->id, $duedate, 'paymentterm'); } else { print dol_print_date($duedate, 'day'); @@ -447,11 +447,12 @@ if ($object->id > 0) print ''; - if ($action != 'editmode' && !empty($object->brouillon) && $user->rights->facture->creer) print ''; + if ($action != 'editmode' && !empty($object->brouillon) && $user->rights->facture->creer) { + print ''; + } print '
'; print $langs->trans('PaymentMode'); print 'id.'">'.img_edit($langs->trans('SetMode'), 1).'id.'">'.img_edit($langs->trans('SetMode'), 1).'
'; print '
'; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id'); } else { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); @@ -463,12 +464,12 @@ if ($object->id > 0) print ''; + } print '
'; print $langs->trans('BankAccount'); print ''; - if (($action != 'editbankaccount') && $user->rights->commande->creer && !empty($object->brouillon)) + if (($action != 'editbankaccount') && $user->rights->commande->creer && !empty($object->brouillon)) { print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
'; print '
'; - if ($action == 'editbankaccount') - { + if ($action == 'editbankaccount') { $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'fk_account', 1); } else { $form->formSelectAccount($_SERVER['PHP_SELF'].'?id='.$object->id, $object->fk_account, 'none'); @@ -487,7 +488,9 @@ if ($object->id > 0) print $bac->iban.(($bac->iban && $bac->bic) ? ' / ' : '').$bac->bic; if (!empty($bac->iban)) { - if ($bac->verif() <= 0) print img_warning('Error on default bank number for IBAN : '.$bac->error_message); + if ($bac->verif() <= 0) { + print img_warning('Error on default bank number for IBAN : '.$bac->error_message); + } } else { print img_warning($langs->trans("NoDefaultIBANFound")); } @@ -503,8 +506,7 @@ if ($object->id > 0) print ''; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) - { + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT print ''; print ''; @@ -530,31 +532,27 @@ if ($object->id > 0) print ''; // Amount Local Taxes - if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) // Localtax1 - { + if (($mysoc->localtax1_assuj == "1" && $mysoc->useLocalTax(1)) || $object->total_localtax1 != 0) { // Localtax1 print ''; print ''; } - if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) // Localtax2 - { + if (($mysoc->localtax2_assuj == "1" && $mysoc->useLocalTax(2)) || $object->total_localtax2 != 0) { // Localtax2 print ''; print ''; } // Revenue stamp - if ($selleruserevenustamp) // Test company use revenue stamp - { + if ($selleruserevenustamp) { // Test company use revenue stamp print ''; } @@ -597,8 +595,7 @@ if ($object->id > 0) $sql .= " ORDER BY pfd.date_demande DESC"; $result_sql = $db->query($sql); - if ($result_sql) - { + if ($result_sql) { $num = $db->num_rows($result_sql); $numopen = $num; } else { @@ -618,10 +615,11 @@ if ($object->id > 0) $sql .= " AND pfd.ext_payment_id IS NULL"; $result_sql = $db->query($sql); - if ($result_sql) - { + if ($result_sql) { $obj = $db->fetch_object($result_sql); - if ($obj) $pending = $obj->amount; + if ($obj) { + $pending = $obj->amount; + } } else { dol_print_error($db); } @@ -641,12 +639,9 @@ if ($object->id > 0) } // Add a transfer request - if ($object->statut > $object::STATUS_DRAFT && $object->paye == 0 && $num == 0) - { - if ($resteapayer > 0) - { - if ($user_perms) - { + if ($object->statut > $object::STATUS_DRAFT && $object->paye == 0 && $num == 0) { + if ($resteapayer > 0) { + if ($user_perms) { $remaintopaylesspendingdebit = $resteapayer - $pending; print ''; @@ -665,10 +660,12 @@ if ($object->id > 0) print ''.$buttonlabel.''; } } else { - if ($num == 0) - { - if ($object->statut > $object::STATUS_DRAFT) print ''.$buttonlabel.''; - else print ''.$buttonlabel.''; + if ($num == 0) { + if ($object->statut > $object::STATUS_DRAFT) { + print ''.$buttonlabel.''; + } else { + print ''.$buttonlabel.''; + } } else { print ''.$buttonlabel.''; } @@ -722,15 +719,13 @@ if ($object->id > 0) $result_sql = $db->query($sql); $num = 0; - if ($result_sql) - { + if ($result_sql) { $i = 0; $tmpuser = new User($db); $num = $db->num_rows($result); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result_sql); $tmpuser->id = $obj->user_id; @@ -788,16 +783,14 @@ if ($object->id > 0) $sql .= " ORDER BY pfd.date_demande DESC"; $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $numclosed = $num; $i = 0; $tmpuser = new User($db); - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); $tmpuser->id = $obj->user_id; @@ -819,8 +812,7 @@ if ($object->id > 0) print ''; print ''; + } $db->free($result); } else { diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index 2a722f8723d..536beff168d 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -32,7 +32,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facturestats.class.php'; -if (!empty($conf->category->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +if (!empty($conf->category->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +} $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); @@ -41,8 +43,12 @@ $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $langs->loadLangs(array('bills', 'companies', 'other')); $mode = GETPOST("mode") ?GETPOST("mode") : 'customer'; -if ($mode == 'customer' && !$user->rights->facture->lire) accessforbidden(); -if ($mode == 'supplier' && !$user->rights->fournisseur->facture->lire) accessforbidden(); +if ($mode == 'customer' && !$user->rights->facture->lire) { + accessforbidden(); +} +if ($mode == 'supplier' && !$user->rights->fournisseur->facture->lire) { + accessforbidden(); +} $object_status = GETPOST('object_status', 'intcomma'); $typent_id = GETPOST('typent_id', 'int'); @@ -52,23 +58,27 @@ $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); $custcats = GETPOST('custcats', 'array'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } $nowyear = strftime("%Y", dol_now()); $year = GETPOST('year') > 0 ? GETPOST('year', 'int') : $nowyear; -if (!empty($conf->global->INVOICE_STATS_GRAPHS_SHOW_2_YEARS)) $startyear = $year - 2; -else $startyear = $year - 1; +if (!empty($conf->global->INVOICE_STATS_GRAPHS_SHOW_2_YEARS)) { + $startyear = $year - 2; +} else { + $startyear = $year - 1; +} $endyear = $year; /* * View */ -if (!empty($conf->category->enabled)) $langs->load('categories'); +if (!empty($conf->category->enabled)) { + $langs->load('categories'); +} $form = new Form($db); $formcompany = new FormCompany($db); $formother = new FormOther($db); @@ -79,8 +89,7 @@ $picto = 'bill'; $title = $langs->trans("BillsStatistics"); $dir = $conf->facture->dir_temp; -if ($mode == 'supplier') -{ +if ($mode == 'supplier') { $picto = 'supplier_invoice'; $title = $langs->trans("BillsStatisticsSuppliers"); $dir = $conf->fournisseur->facture->dir_temp; @@ -92,17 +101,19 @@ print load_fiche_titre($title, '', $picto); dol_mkdir($dir); $stats = new FactureStats($db, $socid, $mode, ($userid > 0 ? $userid : 0), ($typent_id > 0 ? $typent_id : 0), ($categ_id > 0 ? $categ_id : 0)); -if ($mode == 'customer') -{ - if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND f.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($mode == 'customer') { + if ($object_status != '' && $object_status >= 0) { + $stats->where .= ' AND f.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; + } if (is_array($custcats) && !empty($custcats)) { $stats->from .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_societe as cat ON (f.fk_soc = cat.fk_soc)'; $stats->where .= ' AND cat.fk_categorie IN ('.implode(',', $custcats).')'; } } -if ($mode == 'supplier') -{ - if ($object_status != '' && $object_status >= 0) $stats->where .= ' AND f.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($mode == 'supplier') { + if ($object_status != '' && $object_status >= 0) { + $stats->where .= ' AND f.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; + } } // Build graphic number of object @@ -111,17 +122,19 @@ $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); //var_dump($data); $filenamenb = $dir."/invoicesnbinyear-".$year.".png"; -if ($mode == 'customer') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=billstats&file=invoicesnbinyear-'.$year.'.png'; -if ($mode == 'supplier') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=billstatssupplier&file=invoicesnbinyear-'.$year.'.png'; +if ($mode == 'customer') { + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=billstats&file=invoicesnbinyear-'.$year.'.png'; +} +if ($mode == 'supplier') { + $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=billstatssupplier&file=invoicesnbinyear-'.$year.'.png'; +} $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -144,17 +157,19 @@ $data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) $filenameamount = $dir."/invoicesamountinyear-".$year.".png"; -if ($mode == 'customer') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=billstats&file=invoicesamountinyear-'.$year.'.png'; -if ($mode == 'supplier') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=billstatssupplier&file=invoicesamountinyear-'.$year.'.png'; +if ($mode == 'customer') { + $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=billstats&file=invoicesamountinyear-'.$year.'.png'; +} +if ($mode == 'supplier') { + $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=billstatssupplier&file=invoicesamountinyear-'.$year.'.png'; +} $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -175,25 +190,30 @@ if (!$mesg) $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } } else { $filename_avg = $dir.'/ordersaverage-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + } } $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -218,7 +238,9 @@ $arrayyears = array(); foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; @@ -228,8 +250,12 @@ $head[$h][1] = $langs->trans("ByMonthYear"); $head[$h][2] = 'byyear'; $h++; -if ($mode == 'customer') $type = 'invoice_stats'; -if ($mode == 'supplier') $type = 'supplier_invoice_stats'; +if ($mode == 'customer') { + $type = 'invoice_stats'; +} +if ($mode == 'supplier') { + $type = 'supplier_invoice_stats'; +} complete_head_from_modules($conf, $langs, null, $head, $h, $type); @@ -256,8 +282,12 @@ print '
'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).''.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'
'.$langs->transcountry("AmountLT1", $mysoc->country_code).''.price($object->total_localtax1, 1, '', 1, - 1, - 1, $conf->currency).'
'.$langs->transcountry("AmountLT2", $mysoc->country_code).''.price($object->total_localtax2, 1, '', 1, - 1, - 1, $conf->currency).'
'; print ''; - if ($action != 'editrevenuestamp' && !empty($object->brouillon) && $user->rights->facture->creer) - { + if ($action != 'editrevenuestamp' && !empty($object->brouillon) && $user->rights->facture->creer) { print ''; } print '
'; print $langs->trans('RevenueStamp'); print 'id.'">'.img_edit($langs->trans('SetRevenuStamp'), 1).'
'; print '
'; - print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency); + print price($object->revenuestamp, 1, '', 1, - 1, - 1, $conf->currency); print '
'.price($obj->amount).''; - if ($obj->fk_prelevement_bons > 0) - { + if ($obj->fk_prelevement_bons > 0) { $withdrawreceipt = new BonPrelevement($db); $withdrawreceipt->id = $obj->fk_prelevement_bons; $withdrawreceipt->ref = $obj->ref; @@ -838,8 +830,9 @@ if ($object->id > 0) $i++; } - if (!$numopen && !$numclosed) + if (!$numopen && !$numclosed) { print '
'.$langs->trans("None").'
'; print ''; // Company print ''; @@ -265,18 +295,18 @@ print ''; print ''; // Category if (!empty($conf->category->enabled)) { - if ($mode == 'customer') - { + if ($mode == 'customer') { $cat_type = Categorie::TYPE_CUSTOMER; $cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Customer")); } - if ($mode == 'supplier') - { + if ($mode == 'supplier') { $cat_type = Categorie::TYPE_SUPPLIER; $cat_label = $langs->trans("Category").' '.lcfirst($langs->trans("Supplier")); } @@ -293,21 +323,23 @@ print $form->select_dolusers($userid, 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0 print ''; // Status print ''; // Year print ''; @@ -329,11 +361,9 @@ print ''; print ''; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while ($year && $oldyear > $year + 1) - { // If we have empty year + while ($year && $oldyear > $year + 1) { // If we have empty year $oldyear--; print ''; @@ -367,7 +397,9 @@ print '
'; // Show graphs print '
'.$langs->trans("Filter").'
'.$langs->trans("ThirdParty").''; -if ($mode == 'customer') $filter = 's.client in (1,2,3)'; -if ($mode == 'supplier') $filter = 's.fournisseur = 1'; +if ($mode == 'customer') { + $filter = 's.client in (1,2,3)'; +} +if ($mode == 'supplier') { + $filter = 's.fournisseur = 1'; +} print $form->selectarray('socid', $companies, $socid, 1, 0, 0, 'style="width: 95%"', 0, 0, 0, '', '', 1); print '
'.$langs->trans("ThirdPartyType").''; $sortparam_typent = (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT); // NONE means we keep sort of original array, so we sort on position. ASC, means next function will sort on label. print $form->selectarray("typent_id", $formcompany->typent_array(0), $typent_id, 1, 0, 0, '', 0, 0, 0, $sortparam_typent, '', 1); -if ($user->admin) print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); +if ($user->admin) { + print ' '.info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); +} print '
'.$langs->trans("Status").''; -if ($mode == 'customer') -{ +if ($mode == 'customer') { $liststatus = array('0'=>$langs->trans("BillStatusDraft"), '1'=>$langs->trans("BillStatusNotPaid"), '2'=>$langs->trans("BillStatusPaid"), '1,2'=>$langs->trans("BillStatusNotPaid").' / '.$langs->trans("BillStatusPaid"), '3'=>$langs->trans("BillStatusCanceled")); print $form->selectarray('object_status', $liststatus, $object_status, 1); } -if ($mode == 'supplier') -{ +if ($mode == 'supplier') { $liststatus = array('0'=>$langs->trans("BillStatusDraft"), '1'=>$langs->trans("BillStatusNotPaid"), '2'=>$langs->trans("BillStatusPaid")); print $form->selectarray('object_status', $liststatus, $object_status, 1); } print '
'.$langs->trans("Year").''; -if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; -if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '
%
'; print ''; print "\n"; } -if (count($linkedObjectBlock) > 1) -{ +if (count($linkedObjectBlock) > 1) { print ''; print ''; print ''; diff --git a/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php b/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php index 1c8473637f3..935f6b03948 100644 --- a/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php +++ b/htdocs/compta/facture/tpl/linkedobjectblockForRec.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -38,16 +37,17 @@ $langs->load("bills"); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - - + + 1) -{ +if (count($linkedObjectBlock) > 1) { ?> - - - - - - - - - - "> + + + + + + + + + \n"; diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index 8a50619f17c..7cc15d7f9a7 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -47,16 +47,16 @@ require_once DOL_DOCUMENT_ROOT.'/compta/sociales/class/chargesociales.class.php' // Load translation files required by the page $langs->loadLangs(array('compta', 'bills')); -if (!empty($conf->commande->enabled)) +if (!empty($conf->commande->enabled)) { $langs->load("orders"); +} $action = GETPOST('action', 'aZ09'); $bid = GETPOST('bid', 'int'); // Security check $socid = ''; -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -89,37 +89,35 @@ print load_fiche_titre($langs->trans("AccountancyTreasuryArea"), '', 'bill'); print '
'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search customer invoices - if (!empty($conf->facture->enabled) && $user->rights->facture->lire) - { + if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $listofsearchfields['search_invoice'] = array('text'=>'CustomerInvoice'); } // Search supplier invoices - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->lire) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->lire) { $listofsearchfields['search_supplier_invoice'] = array('text'=>'SupplierInvoice'); } - if (!empty($conf->don->enabled) && $user->rights->don->lire) - { + if (!empty($conf->don->enabled) && $user->rights->don->lire) { $langs->load("donations"); $listofsearchfields['search_donation'] = array('text'=>'Donation'); } - if (count($listofsearchfields)) - { + if (count($listofsearchfields)) { print ''; print ''; print '
'; print '
'; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "
\n"; print $px2->show(); diff --git a/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php b/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php index 92745a276e1..f9bb5902cce 100644 --- a/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php +++ b/htdocs/compta/facture/tpl/linkedobjectblock.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -38,12 +37,13 @@ $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1) $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } print '
'; switch ($objectlink->type) { @@ -73,7 +73,9 @@ foreach ($linkedObjectBlock as $key => $objectlink) print ''; if ($user->rights->facture->lire) { $sign = 1; - if ($object->type == Facture::TYPE_CREDIT_NOTE) $sign = -1; + if ($object->type == Facture::TYPE_CREDIT_NOTE) { + $sign = -1; + } if ($objectlink->statut != 3) { // If not abandonned $total = $total + $sign * $objectlink->total_ht; @@ -87,8 +89,7 @@ foreach ($linkedObjectBlock as $key => $objectlink) print ''.img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink').'
'.$langs->trans("Total").'
trans("RepeatableInvoice"); ?>getNomUrl(1); ?>trans("RepeatableInvoice"); ?>getNomUrl(1); ?> date_when, 'day'); ?> $objectlink)
trans("Total"); ?>
trans("Total"); ?>
'; $i = 0; - foreach ($listofsearchfields as $key => $value) - { - if ($i == 0) print ''; + foreach ($listofsearchfields as $key => $value) { + if ($i == 0) { + print ''; + } print ''; print ''; - if ($i == 0) print ''; + if ($i == 0) { + print ''; + } print ''; $i++; } @@ -134,8 +132,7 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles /** * Draft customers invoices */ -if (!empty($conf->facture->enabled) && $user->rights->facture->lire) -{ +if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $tmpinvoice = new Facture($db); $sql = "SELECT f.rowid, f.ref, f.datef as date, f.total as total_ht, f.tva as total_tva, f.total_ttc, f.ref_client"; @@ -144,15 +141,20 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $sql .= ", s.rowid as socid, s.email"; $sql .= ", s.code_client, s.code_compta, s.code_fournisseur, s.code_compta_fournisseur"; $sql .= ", cc.rowid as country_id, cc.code as country_code"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.rowid = f.fk_soc AND f.fk_statut = ".Facture::STATUS_DRAFT; $sql .= " AND f.entity IN (".getEntity('invoice').")"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } - if ($socid) - { + if ($socid) { $sql .= " AND f.fk_soc = $socid"; } // Add where from hooks @@ -163,7 +165,9 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $sql .= " GROUP BY f.rowid, f.ref, f.datef, f.total, f.tva, f.total_ttc, f.ref_client, f.type, f.fk_statut, f.paye,"; $sql .= " s.nom, s.rowid, s.email, s.code_client, s.code_compta, s.code_fournisseur, s.code_compta_fournisseur,"; $sql .= " cc.rowid, cc.code"; - if (!$user->rights->societe->client->voir && !$socid) $sql.= ", sc.fk_soc, sc.fk_user"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql.= ", sc.fk_soc, sc.fk_user"; + } // Add Group from hooks $parameters = array(); @@ -172,8 +176,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
'; @@ -188,15 +191,13 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) print ''; print ''; - if ($num) - { + if ($num) { $companystatic = new Societe($db); $i = 0; $othernb = 0; $tot_ttc = 0; - while ($i < $num && $i < $conf->liste_limit) - { + while ($i < $num && $i < $conf->liste_limit) { $obj = $db->fetch_object($resql); if ($i >= $max) { @@ -264,8 +265,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) /** * Draft suppliers invoices */ -if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) -{ +if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { $facturesupplierstatic = new FactureFournisseur($db); $sql = "SELECT f.ref, f.rowid, f.total_ht, f.total_tva, f.total_ttc, f.type, f.ref_supplier, f.fk_statut as status, f.paye"; @@ -274,19 +274,24 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $sql .= ", s.code_fournisseur, s.code_compta_fournisseur"; $sql .= ", cc.rowid as country_id, cc.code as country_code"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f, ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.rowid = f.fk_soc AND f.fk_statut = ".FactureFournisseur::STATUS_DRAFT; $sql .= " AND f.entity IN (".getEntity('invoice').')'; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhereSupplierDraft', $parameters); $sql .= $hookmanager->resPrint; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
'; @@ -301,15 +306,13 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU print ''; print ''; - if ($num) - { + if ($num) { $companystatic = new Societe($db); $i = 0; $othernb = 0; $tot_ttc = 0; - while ($i < $num && $i < $conf->liste_limit) - { + while ($i < $num && $i < $conf->liste_limit) { $obj = $db->fetch_object($resql); if ($i >= $max) { @@ -378,8 +381,7 @@ print '
'; // Latest modified customer invoices -if (!empty($conf->facture->enabled) && $user->rights->facture->lire) -{ +if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $langs->load("boxes"); $tmpinvoice = new Facture($db); @@ -392,11 +394,17 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $sql .= ", sum(pf.amount) as am"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s LEFT JOIN ".MAIN_DB_PREFIX."c_country as cc ON cc.rowid = s.fk_pays, ".MAIN_DB_PREFIX."facture as f"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf on f.rowid=pf.fk_facture"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.rowid = f.fk_soc"; $sql .= " AND f.entity IN (".getEntity('invoice').")"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhereCustomerLastModified', $parameters); @@ -409,8 +417,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) $sql .= $db->plimit($max, 0); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $othernb = 0; @@ -418,16 +425,16 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) print '
'; print '
'.$langs->trans("Search").'
'.$langs->trans("Search").'
'; print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; print ''; - if ($num) - { + if ($num) { $total_ttc = $totalam = $total = 0; - while ($i < $num && $i < $conf->liste_limit) - { + while ($i < $num && $i < $conf->liste_limit) { $obj = $db->fetch_object($resql); if ($i >= $max) { @@ -483,7 +490,9 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; @@ -505,7 +514,9 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) } } else { $colspan = 5; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + $colspan++; + } print ''; } print '
'.$langs->trans("BoxTitleLastCustomerBills", $max).''.$langs->trans("AmountHT").''.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").''.$langs->trans("DateModificationShort").' 
'; print $thirdpartystatic->getNomUrl(1, 'customer', 44); print ''.price($obj->total_ht).''.price($obj->total_ht).''.price($obj->total_ttc).''.dol_print_date($db->jdate($obj->tms), 'day').''.$tmpinvoice->getLibStatut(3, $obj->am).'
'.$langs->trans("NoInvoice").'

'; @@ -518,8 +529,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) // Last modified supplier invoices -if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) -{ +if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { $langs->load("boxes"); $facstatic = new FactureFournisseur($db); @@ -530,11 +540,17 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $sql .= ", SUM(pf.amount) as am"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as ff"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf on ff.rowid=pf.fk_facturefourn"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.rowid = ff.fk_soc"; $sql .= " AND ff.entity = ".$conf->entity; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND ff.fk_soc = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND ff.fk_soc = ".$socid; + } // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhereSupplierLastModified', $parameters); @@ -546,26 +562,25 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $sql .= $db->plimit($max, 0); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
'; print ''; print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; print "\n"; - if ($num) - { + if ($num) { $i = 0; $total = $total_ttc = $totalam = 0; $othernb = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); if ($i >= $max) { @@ -602,7 +617,9 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU print ''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''; + } print ''; print ''; print ''; @@ -622,7 +639,9 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU } } else { $colspan = 5; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + $colspan++; + } print ''; } print '
'.$langs->trans("BoxTitleLastSupplierBills", $max).''.$langs->trans("AmountHT").''.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").''.$langs->trans("DateModificationShort").' 
'; print $thirdpartystatic->getNomUrl(1, 'supplier'); print ''.price($obj->total_ht).''.price($obj->total_ht).''.price($obj->total_ttc).''.dol_print_date($db->jdate($obj->tms), 'day').''.$facstatic->getLibStatut(3).'
'.$langs->trans("NoInvoice").'

'; @@ -634,8 +653,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU // Latest donations -if (!empty($conf->don->enabled) && $user->rights->don->lire) -{ +if (!empty($conf->don->enabled) && $user->rights->don->lire) { include_once DOL_DOCUMENT_ROOT.'/don/class/don.class.php'; $langs->load("boxes"); @@ -653,8 +671,7 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) $sql .= $db->plimit($max, 0); $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; @@ -669,12 +686,10 @@ if (!empty($conf->don->enabled) && $user->rights->don->lire) print '
'.$langs->trans("DateModificationShort").' 
'.$donationstatic->getNomUrl(1).'
'.$langs->trans("None").'

'; - } else dol_print_error($db); + } else { + dol_print_error($db); + } } /** * Social contributions to pay */ -if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) -{ - if (!$socid) - { +if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { + if (!$socid) { $chargestatic = new ChargeSociales($db); $sql = "SELECT c.rowid, c.amount, c.date_ech, c.paye,"; @@ -746,8 +763,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql .= " GROUP BY c.rowid, c.amount, c.date_ech, c.paye, cc.libelle"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
'; @@ -759,14 +775,12 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print '
'.$langs->trans("Paid").' 
'.$langs->trans("AmountHT").''.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").''.$langs->trans("ToBill").' '; print $societestatic->getNomUrl(1, 'customer'); print ''.price($obj->total_ht).''.price($obj->total_ht).''.price($obj->total_ttc).''.price($obj->total_ttc - $obj->tot_fttc).''.$commandestatic->getLibStatut(3).'
'.$langs->trans("Total").'   ('.$langs->trans("RemainderToBill").': '.price($tot_tobill).') '.price($tot_ht).''.price($tot_ht).''.price($tot_ttc).''.price($tot_tobill).' '.$langs->trans("DateDue").''.$langs->trans("AmountHT").''.$langs->trans("AmountHT").''.$langs->trans("AmountTTC").''.$langs->trans("Received").' 
'.dol_print_date($db->jdate($obj->datelimite), 'day').''.price($obj->total_ht).''.price($obj->total_ht).''.price($obj->total_ttc).''.price($obj->am).''.$tmpinvoice->getLibStatut(3, $obj->am).'
'; print ''.$langs->trans("More").'... ('.$othernb.')'; @@ -1104,14 +1134,18 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) print '
'.$langs->trans("Total").'   ('.$langs->trans("RemainderToTake").': '.price($total_ttc - $totalam).')  '.price($total).''.price($total).''.price($total_ttc).''.price($totalam).' 
'.$langs->trans("NoInvoice").'

'; @@ -1124,8 +1158,7 @@ if (!empty($conf->facture->enabled) && $user->rights->facture->lire) /* * Unpaid supplier invoices */ -if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) -{ +if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { $facstatic = new FactureFournisseur($db); $sql = "SELECT ff.rowid, ff.ref, ff.fk_statut as status, ff.type, ff.libelle as label, ff.total_ht, ff.total_tva, ff.total_ttc, ff.paye"; @@ -1137,13 +1170,19 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $sql .= ", sum(pf.amount) as am"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."facture_fourn as ff"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf on ff.rowid=pf.fk_facturefourn"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.rowid = ff.fk_soc"; $sql .= " AND ff.entity = ".$conf->entity; $sql .= " AND ff.paye = 0"; $sql .= " AND ff.fk_statut = ".FactureFournisseur::STATUS_VALIDATED; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND ff.fk_soc = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND ff.fk_soc = ".$socid; + } // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhereSupplierUnpaid', $parameters); @@ -1154,8 +1193,7 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU $sql .= " ORDER BY ff.date_lim_reglement ASC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $othernb = 0; @@ -1173,18 +1211,18 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU print ''; print ''.$langs->trans("DateDue").''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.$langs->trans("AmountHT").''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''.$langs->trans("AmountHT").''; + } print ''.$langs->trans("AmountTTC").''; print ''.$langs->trans("Paid").''; print ' '; print "\n"; $societestatic = new Societe($db); - if ($num) - { + if ($num) { $i = 0; $total = $total_ttc = $totalam = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); if ($i >= $max) { @@ -1219,7 +1257,9 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU print ''; print ''.$societestatic->getNomUrl(1, 'supplier').''; print ''.dol_print_date($db->jdate($obj->date_lim_reglement), 'day').''; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.price($obj->total_ht).''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''.price($obj->total_ht).''; + } print ''.price($obj->total_ttc).''; print ''.price($obj->am).''; print ''.$facstatic->getLibStatut(3, $obj->am).''; @@ -1232,7 +1272,9 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU if ($othernb) { $colspan = 6; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + $colspan++; + } print ''; print ''; print ''.$langs->trans("More").'... ('.$othernb.')'; @@ -1242,14 +1284,18 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU print ''.$langs->trans("Total").'   ('.$langs->trans("RemainderToPay").': '.price($total_ttc - $totalam).') '; print ' '; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) print ''.price($total).''; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + print ''.price($total).''; + } print ''.price($total_ttc).''; print ''.price($totalam).''; print ' '; print ''; } else { $colspan = 6; - if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) $colspan++; + if (!empty($conf->global->MAIN_SHOW_HT_ON_SUMMARY)) { + $colspan++; + } print ''.$langs->trans("NoInvoice").''; } print '

'; @@ -1262,15 +1308,13 @@ if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SU // TODO Mettre ici recup des actions en rapport avec la compta $resql = 0; -if ($resql) -{ +if ($resql) { print '
'; print ''; print ''.$langs->trans("TasksToDo").''; print "\n"; $i = 0; - while ($i < $db->num_rows($resql)) - { + while ($i < $db->num_rows($resql)) { $obj = $db->fetch_object($resql); print ''; diff --git a/htdocs/compta/journal/purchasesjournal.php b/htdocs/compta/journal/purchasesjournal.php index 45ffae7c1ff..fda83a75668 100644 --- a/htdocs/compta/journal/purchasesjournal.php +++ b/htdocs/compta/journal/purchasesjournal.php @@ -45,9 +45,15 @@ $date_endday = GETPOST('date_endday'); $date_endyear = GETPOST('date_endyear'); // Security check -if ($user->socid > 0) $socid = $user->socid; -if (!empty($conf->comptabilite->enabled)) $result = restrictedArea($user, 'compta', '', '', 'resultat'); -if (!empty($conf->accounting->enabled)) $result = restrictedArea($user, 'accounting', '', '', 'comptarapport'); +if ($user->socid > 0) { + $socid = $user->socid; +} +if (!empty($conf->comptabilite->enabled)) { + $result = restrictedArea($user, 'compta', '', '', 'resultat'); +} +if (!empty($conf->accounting->enabled)) { + $result = restrictedArea($user, 'accounting', '', '', 'comptarapport'); +} /* @@ -70,8 +76,7 @@ $form = new Form($db); $year_current = strftime("%Y", dol_now()); $pastmonth = strftime("%m", dol_now()) - 1; $pastmonthyear = $year_current; -if ($pastmonth == 0) -{ +if ($pastmonth == 0) { $pastmonth = 12; $pastmonthyear--; } @@ -79,8 +84,7 @@ if ($pastmonth == 0) $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); -if (empty($date_start) || empty($date_end)) // We define date_start and date_end -{ +if (empty($date_start) || empty($date_end)) { // We define date_start and date_end $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); } @@ -90,8 +94,11 @@ $periodlink = ''; $exportlink = ''; $builddate = dol_now(); $description = $langs->trans("DescPurchasesJournal").'
'; -if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description .= $langs->trans("DepositsAreNotIncluded"); -else $description .= $langs->trans("DepositsAreIncluded"); +if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $description .= $langs->trans("DepositsAreNotIncluded"); +} else { + $description .= $langs->trans("DepositsAreIncluded"); +} $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink); @@ -111,16 +118,22 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = fd.fk_product"; $sql .= " JOIN ".MAIN_DB_PREFIX."facture_fourn as f ON f.rowid = fd.fk_facture_fourn"; $sql .= " JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = f.fk_soc"; $sql .= " WHERE f.fk_statut > 0 AND f.entity IN (".getEntity('invoice').")"; -if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2)"; -else $sql .= " AND f.type IN (0,1,2,3)"; -if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; +if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2)"; +} else { + $sql .= " AND f.type IN (0,1,2,3)"; +} +if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; +} // TODO Find a better trick to avoid problem with some mysql installations -if (in_array($db->type, array('mysql', 'mysqli'))) $db->query('SET SQL_BIG_SELECTS=1'); +if (in_array($db->type, array('mysql', 'mysqli'))) { + $db->query('SET SQL_BIG_SELECTS=1'); +} $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); // les variables $cptfour = (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : $langs->trans("CodeNotDef")); @@ -135,16 +148,17 @@ if ($result) $tabcompany = array(); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); // contrôles $compta_soc = (($obj->code_compta_fournisseur != "") ? $obj->code_compta_fournisseur : $cptfour); $compta_prod = $obj->accountancy_code_buy; - if (empty($compta_prod)) - { - if ($obj->product_type == 0) $compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : $langs->trans("CodeNotDef")); - else $compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : $langs->trans("CodeNotDef")); + if (empty($compta_prod)) { + if ($obj->product_type == 0) { + $compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_BUY_ACCOUNT : $langs->trans("CodeNotDef")); + } else { + $compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_BUY_ACCOUNT : $langs->trans("CodeNotDef")); + } } $compta_tva = (!empty($obj->account_tva) ? $obj->account_tva : $cpttva); $compta_localtax1 = (!empty($obj->account_localtax1) ? $obj->account_localtax1 : $langs->trans("CodeNotDef")); @@ -161,9 +175,11 @@ if ($result) $tabfac[$obj->rowid]["lib"] = $obj->label; $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc; $tabht[$obj->rowid][$compta_prod] += $obj->total_ht; - if ($obj->recuperableonly != 1) $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva; + if ($obj->recuperableonly != 1) { + $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva; + } $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1; - $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2; + $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2; $tabcompany[$obj->rowid] = array('id'=>$obj->socid, 'name'=>$obj->name); $i++; @@ -188,8 +204,7 @@ print "\n"; $invoicestatic = new FactureFournisseur($db); $companystatic = new Fournisseur($db); -foreach ($tabfac as $key => $val) -{ +foreach ($tabfac as $key => $val) { $invoicestatic->id = $key; $invoicestatic->ref = $val["ref"]; $invoicestatic->type = $val["type"]; @@ -222,19 +237,15 @@ foreach ($tabfac as $key => $val) ) ); - foreach ($lines as $line) - { - foreach ($line['var'] as $k => $mt) - { - if (isset($line['nomtcheck']) || $mt) - { + foreach ($lines as $line) { + foreach ($line['var'] as $k => $mt) { + if (isset($line['nomtcheck']) || $mt) { print ''; print ""; print ""; print ""; - if (isset($line['inv'])) - { + if (isset($line['inv'])) { print '"; print '"; } else { diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php index ea6222dc63f..39faf295c45 100644 --- a/htdocs/compta/journal/sellsjournal.php +++ b/htdocs/compta/journal/sellsjournal.php @@ -47,9 +47,15 @@ $date_endday = GETPOST('date_endday'); $date_endyear = GETPOST('date_endyear'); // Security check -if ($user->socid > 0) $socid = $user->socid; -if (!empty($conf->comptabilite->enabled)) $result = restrictedArea($user, 'compta', '', '', 'resultat'); -if (!empty($conf->accounting->enabled)) $result = restrictedArea($user, 'accounting', '', '', 'comptarapport'); +if ($user->socid > 0) { + $socid = $user->socid; +} +if (!empty($conf->comptabilite->enabled)) { + $result = restrictedArea($user, 'compta', '', '', 'resultat'); +} +if (!empty($conf->accounting->enabled)) { + $result = restrictedArea($user, 'accounting', '', '', 'comptarapport'); +} /* * Actions @@ -73,8 +79,7 @@ llxHeader('', $langs->trans("SellsJournal"), '', '', 0, 0, '', '', $morequery); $year_current = strftime("%Y", dol_now()); $pastmonth = strftime("%m", dol_now()) - 1; $pastmonthyear = $year_current; -if ($pastmonth == 0) -{ +if ($pastmonth == 0) { $pastmonth = 12; $pastmonthyear--; } @@ -82,8 +87,7 @@ if ($pastmonth == 0) $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); -if (empty($date_start) || empty($date_end)) // We define date_start and date_end -{ +if (empty($date_start) || empty($date_end)) { // We define date_start and date_end $date_start = dol_get_first_day($pastmonthyear, $pastmonth, false); $date_end = dol_get_last_day($pastmonthyear, $pastmonth, false); } @@ -92,8 +96,11 @@ $periodlink = ''; $exportlink = ''; $builddate = dol_now(); $description = $langs->trans("DescSellsJournal").'
'; -if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $description .= $langs->trans("DepositsAreNotIncluded"); -else $description .= $langs->trans("DepositsAreIncluded"); +if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $description .= $langs->trans("DepositsAreNotIncluded"); +} else { + $description .= $langs->trans("DepositsAreIncluded"); +} $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink); @@ -119,15 +126,18 @@ if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { } $sql .= " AND fd.product_type IN (0,1)"; -if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; +if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; +} $sql .= " ORDER BY f.rowid"; // TODO Find a better trick to avoid problem with some mysql installations -if (in_array($db->type, array('mysql', 'mysqli'))) $db->query('SET SQL_BIG_SELECTS=1'); +if (in_array($db->type, array('mysql', 'mysqli'))) { + $db->query('SET SQL_BIG_SELECTS=1'); +} $result = $db->query($sql); -if ($result) -{ +if ($result) { $tabfac = array(); $tabht = array(); $tabtva = array(); @@ -139,19 +149,20 @@ if ($result) $account_localtax2 = 0; $num = $db->num_rows($result); - $i = 0; - $resligne = array(); - while ($i < $num) - { - $obj = $db->fetch_object($result); - // les variables - $cptcli = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef")); - $compta_soc = (!empty($obj->code_compta) ? $obj->code_compta : $cptcli); + $i = 0; + $resligne = array(); + while ($i < $num) { + $obj = $db->fetch_object($result); + // les variables + $cptcli = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef")); + $compta_soc = (!empty($obj->code_compta) ? $obj->code_compta : $cptcli); $compta_prod = $obj->accountancy_code_sell; - if (empty($compta_prod)) - { - if ($obj->product_type == 0) $compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); - else $compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + if (empty($compta_prod)) { + if ($obj->product_type == 0) { + $compta_prod = (!empty($conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_PRODUCT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + } else { + $compta_prod = (!empty($conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_SERVICE_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); + } } $cpttva = (!empty($conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT) ? $conf->global->ACCOUNTING_VAT_SOLD_ACCOUNT : $langs->trans("CodeNotDef")); $compta_tva = (!empty($obj->account_tva) ? $obj->account_tva : $cpttva); @@ -178,22 +189,34 @@ if ($result) } //la ligne facture - $tabfac[$obj->rowid]["date"] = $obj->datef; - $tabfac[$obj->rowid]["ref"] = $obj->ref; - $tabfac[$obj->rowid]["type"] = $obj->type; - if (!isset($tabttc[$obj->rowid][$compta_soc])) $tabttc[$obj->rowid][$compta_soc] = 0; - if (!isset($tabht[$obj->rowid][$compta_prod])) $tabht[$obj->rowid][$compta_prod] = 0; - if (!isset($tabtva[$obj->rowid][$compta_tva])) $tabtva[$obj->rowid][$compta_tva] = 0; - if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) $tablocaltax1[$obj->rowid][$compta_localtax1] = 0; - if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) $tablocaltax2[$obj->rowid][$compta_localtax2] = 0; + $tabfac[$obj->rowid]["date"] = $obj->datef; + $tabfac[$obj->rowid]["ref"] = $obj->ref; + $tabfac[$obj->rowid]["type"] = $obj->type; + if (!isset($tabttc[$obj->rowid][$compta_soc])) { + $tabttc[$obj->rowid][$compta_soc] = 0; + } + if (!isset($tabht[$obj->rowid][$compta_prod])) { + $tabht[$obj->rowid][$compta_prod] = 0; + } + if (!isset($tabtva[$obj->rowid][$compta_tva])) { + $tabtva[$obj->rowid][$compta_tva] = 0; + } + if (!isset($tablocaltax1[$obj->rowid][$compta_localtax1])) { + $tablocaltax1[$obj->rowid][$compta_localtax1] = 0; + } + if (!isset($tablocaltax2[$obj->rowid][$compta_localtax2])) { + $tablocaltax2[$obj->rowid][$compta_localtax2] = 0; + } $tabttc[$obj->rowid][$compta_soc] += $obj->total_ttc * $situation_ratio; $tabht[$obj->rowid][$compta_prod] += $obj->total_ht * $situation_ratio; - if ($obj->recuperableonly != 1) $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; - $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1; - $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2; - $tabcompany[$obj->rowid] = array('id'=>$obj->socid, 'name'=>$obj->name, 'client'=>$obj->client); - $i++; - } + if ($obj->recuperableonly != 1) { + $tabtva[$obj->rowid][$compta_tva] += $obj->total_tva * $situation_ratio; + } + $tablocaltax1[$obj->rowid][$compta_localtax1] += $obj->total_localtax1; + $tablocaltax2[$obj->rowid][$compta_localtax2] += $obj->total_localtax2; + $tabcompany[$obj->rowid] = array('id'=>$obj->socid, 'name'=>$obj->name, 'client'=>$obj->client); + $i++; + } } else { dol_print_error($db); } @@ -216,8 +239,7 @@ print "\n"; $invoicestatic = new Facture($db); $companystatic = new Client($db); -foreach ($tabfac as $key => $val) -{ +foreach ($tabfac as $key => $val) { $invoicestatic->id = $key; $invoicestatic->ref = $val["ref"]; $invoicestatic->type = $val["type"]; @@ -251,19 +273,15 @@ foreach ($tabfac as $key => $val) ) ); - foreach ($lines as $line) - { - foreach ($line['var'] as $k => $mt) - { - if (isset($line['nomtcheck']) || $mt) - { + foreach ($lines as $line) { + foreach ($line['var'] as $k => $mt) { + if (isset($line['nomtcheck']) || $mt) { print ''; print ""; print ""; print ""; - if (isset($line['inv'])) - { + if (isset($line['inv'])) { print '"; print '"; } else { diff --git a/htdocs/compta/localtax/card.php b/htdocs/compta/localtax/card.php index ec365ac68e7..ee7dbb5e3f4 100644 --- a/htdocs/compta/localtax/card.php +++ b/htdocs/compta/localtax/card.php @@ -34,13 +34,17 @@ $langs->loadLangs(array('compta', 'banks', 'bills')); $id = GETPOST("id", 'int'); $action = GETPOST("action", "alpha"); $refund = GETPOST("refund", "int"); -if (empty($refund)) $refund = 0; +if (empty($refund)) { + $refund = 0; +} $lttype = GETPOST('localTaxType', 'int'); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); $object = new Localtax($db); @@ -53,14 +57,12 @@ $hookmanager->initHooks(array('localtaxvatcard', 'globalcard')); * Actions */ -if ($_POST["cancel"] == $langs->trans("Cancel") && !$id) -{ +if ($_POST["cancel"] == $langs->trans("Cancel") && !$id) { header("Location: list.php?localTaxType=".$lttype); exit; } -if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) -{ +if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) { $db->begin(); $datev = dol_mktime(12, 0, 0, $_POST["datevmonth"], $_POST["datevday"], $_POST["datevyear"]); @@ -75,8 +77,7 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) $object->ltt = $lttype; $ret = $object->addPayment($user); - if ($ret > 0) - { + if ($ret > 0) { $db->commit(); header("Location: list.php?localTaxType=".$lttype); exit; @@ -88,26 +89,23 @@ if ($action == 'add' && $_POST["cancel"] <> $langs->trans("Cancel")) } //delete payment of localtax -if ($action == 'delete') -{ +if ($action == 'delete') { $result = $object->fetch($id); - if ($object->rappro == 0) - { + if ($object->rappro == 0) { $db->begin(); $ret = $object->delete($user); - if ($ret > 0) - { - if ($object->fk_bank) - { + if ($ret > 0) { + if ($object->fk_bank) { $accountline = new AccountLine($db); $result = $accountline->fetch($object->fk_bank); - if ($result > 0) $result = $accountline->delete($user); // $result may be 0 if not found (when bank entry was deleted manually and fk_bank point to nothing) + if ($result > 0) { + $result = $accountline->delete($user); // $result may be 0 if not found (when bank entry was deleted manually and fk_bank point to nothing) + } } - if ($result >= 0) - { + if ($result >= 0) { $db->commit(); header("Location: ".DOL_URL_ROOT.'/compta/localtax/list.php?localTaxType='.$object->ltt); exit; @@ -131,11 +129,9 @@ if ($action == 'delete') * View */ -if ($id) -{ +if ($id) { $result = $object->fetch($id); - if ($result <= 0) - { + if ($result <= 0) { dol_print_error($db); exit; } @@ -147,8 +143,7 @@ $title = $langs->trans("LT".$object->ltt)." - ".$langs->trans("Card"); $help_url = ''; llxHeader("", $title, $helpurl); -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->transcountry($lttype == 2 ? "newLT2Payment" : "newLT1Payment", $mysoc->country_code)); print ''."\n"; @@ -175,8 +170,7 @@ if ($action == 'create') // Amount print ''; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print ''; @@ -211,8 +205,7 @@ if ($action == 'create') // View mode -if ($id) -{ +if ($id) { $h = 0; $head[$h][0] = DOL_URL_ROOT.'/compta/localtax/card.php?id='.$object->id; $head[$h][1] = $langs->trans('Card'); @@ -246,11 +239,9 @@ if ($id) print ''; - if (!empty($conf->banque->enabled)) - { - if ($object->fk_account > 0) - { - $bankline = new AccountLine($db); + if (!empty($conf->banque->enabled)) { + if ($object->fk_account > 0) { + $bankline = new AccountLine($db); $bankline->fetch($object->fk_bank); print ''; @@ -278,8 +269,7 @@ if ($id) * Action buttons */ print "
\n"; - if ($object->rappro == 0) - { + if ($object->rappro == 0) { print ''.$langs->trans("Delete").''; } else { print ''.$langs->trans("Delete").''; diff --git a/htdocs/compta/localtax/class/localtax.class.php b/htdocs/compta/localtax/class/localtax.class.php index 18367a04a46..cdea12902bc 100644 --- a/htdocs/compta/localtax/class/localtax.class.php +++ b/htdocs/compta/localtax/class/localtax.class.php @@ -122,19 +122,19 @@ class Localtax extends CommonObject $sql .= " ".((int) $this->fk_user_modif); $sql .= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); + dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."localtax"); // Call trigger $result = $this->call_trigger('LOCALTAX_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -184,22 +184,21 @@ class Localtax extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = "Error ".$this->db->lasterror(); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LOCALTAX_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -239,10 +238,8 @@ class Localtax extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -265,7 +262,7 @@ class Localtax extends CommonObject return 1; } else { - $this->error = "Error ".$this->db->lasterror(); + $this->error = "Error ".$this->db->lasterror(); return -1; } } @@ -281,16 +278,17 @@ class Localtax extends CommonObject { // Call trigger $result = $this->call_trigger('LOCALTAX_DELETE', $user); - if ($result < 0) return -1; + if ($result < 0) { + return -1; + } // End call triggers $sql = "DELETE FROM ".MAIN_DB_PREFIX."localtax"; $sql .= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -355,16 +353,13 @@ class Localtax extends CommonObject // phpcs:enable $sql = "SELECT sum(f.localtax) as amount"; $sql .= " FROM ".MAIN_DB_PREFIX."facture as f WHERE f.paye = 1"; - if ($year) - { + if ($year) { $sql .= " AND f.datef >= '$year-01-01' AND f.datef <= '$year-12-31' "; } $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $ret = $obj->amount; $this->db->free($result); @@ -392,16 +387,13 @@ class Localtax extends CommonObject $sql = "SELECT sum(f.total_localtax) as total_localtax"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - if ($year) - { + if ($year) { $sql .= " WHERE f.datef >= '$year-01-01' AND f.datef <= '$year-12-31' "; } $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $ret = $obj->total_localtax; $this->db->free($result); @@ -430,16 +422,13 @@ class Localtax extends CommonObject $sql = "SELECT sum(f.amount) as amount"; $sql .= " FROM ".MAIN_DB_PREFIX."localtax as f"; - if ($year) - { + if ($year) { $sql .= " WHERE f.datev >= '$year-01-01' AND f.datev <= '$year-12-31' "; } $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $ret = $obj->amount; $this->db->free($result); @@ -469,62 +458,64 @@ class Localtax extends CommonObject // Check parameters $this->amount = price2num($this->amount); - if (!$this->label) - { + if (!$this->label) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); return -3; } - if ($this->amount <= 0) - { + if ($this->amount <= 0) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); return -4; } - if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) - { + if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); return -5; } - if (!empty($conf->banque->enabled) && (empty($this->paymenttype) || $this->paymenttype <= 0)) - { + if (!empty($conf->banque->enabled) && (empty($this->paymenttype) || $this->paymenttype <= 0)) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); return -5; } // Insertion dans table des paiement localtax $sql = "INSERT INTO ".MAIN_DB_PREFIX."localtax (localtaxtype, datep, datev, amount"; - if ($this->note) $sql .= ", note"; - if ($this->label) $sql .= ", label"; + if ($this->note) { + $sql .= ", note"; + } + if ($this->label) { + $sql .= ", label"; + } $sql .= ", fk_user_creat, fk_bank"; $sql .= ") "; $sql .= " VALUES (".$this->ltt.", '".$this->db->idate($this->datep)."',"; $sql .= "'".$this->db->idate($this->datev)."',".$this->amount; - if ($this->note) $sql .= ", '".$this->db->escape($this->note)."'"; - if ($this->label) $sql .= ", '".$this->db->escape($this->label)."'"; + if ($this->note) { + $sql .= ", '".$this->db->escape($this->note)."'"; + } + if ($this->label) { + $sql .= ", '".$this->db->escape($this->label)."'"; + } $sql .= ", ".((int) $user->id).", NULL"; $sql .= ")"; dol_syslog(get_class($this)."::addPayment", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."localtax"); // TODO devrait s'appeler paiementlocaltax - if ($this->id > 0) - { + if ($this->id > 0) { $ok = 1; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { // Insertion dans llx_bank require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $acc = new Account($this->db); $result = $acc->fetch($this->accountid); - if ($result <= 0) dol_print_error($this->db); + if ($result <= 0) { + dol_print_error($this->db); + } $bank_line_id = $acc->addline($this->datep, $this->paymenttype, $this->label, -abs($this->amount), '', '', $user); // Mise a jour fk_bank dans llx_localtax. On connait ainsi la ligne de localtax qui a g�n�r� l'�criture bancaire - if ($bank_line_id > 0) - { + if ($bank_line_id > 0) { $this->update_fk_bank($bank_line_id); } else { $this->error = $acc->error; @@ -533,15 +524,13 @@ class Localtax extends CommonObject // Mise a jour liens $result = $acc->add_url_line($bank_line_id, $this->id, DOL_URL_ROOT.'/compta/localtax/card.php?id=', "(VATPayment)", "payment_vat"); - if ($result < 0) - { + if ($result < 0) { $this->error = $acc->error; $ok = 0; } } - if ($ok) - { + if ($ok) { $this->db->commit(); return $this->id; } else { @@ -601,9 +590,15 @@ class Localtax extends CommonObject $picto = 'payment'; - if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.$this->ref.$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.$this->ref.$linkend; + } return $result; } diff --git a/htdocs/compta/localtax/clients.php b/htdocs/compta/localtax/clients.php index fe605c2224d..603e8564927 100644 --- a/htdocs/compta/localtax/clients.php +++ b/htdocs/compta/localtax/clients.php @@ -37,8 +37,7 @@ $local = GETPOST('localTaxType', 'int'); // Date range $year = GETPOST("year", "int"); -if (empty($year)) -{ +if (empty($year)) { $year_current = strftime("%Y", dol_now()); $year_start = $year_current; } else { @@ -48,41 +47,60 @@ if (empty($year)) $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); // Quarter -if (empty($date_start) || empty($date_end)) // We define date_start and date_end -{ +if (empty($date_start) || empty($date_end)) { // We define date_start and date_end $q = GETPOST("q"); - if (empty($q)) - { - if (GETPOST("month")) { $date_start = dol_get_first_day($year_start, GETPOST("month"), false); $date_end = dol_get_last_day($year_start, GETPOST("month"), false); } else { + if (empty($q)) { + if (GETPOST("month")) { + $date_start = dol_get_first_day($year_start, GETPOST("month"), false); $date_end = dol_get_last_day($year_start, GETPOST("month"), false); + } else { $date_start = dol_get_first_day($year_start, empty($conf->global->SOCIETE_FISCAL_MONTH_START) ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START, false); - if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; - elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; - elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) $date_end = dol_time_plus_duree($date_start, 1, 'm') - 1; + if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { + $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; + } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { + $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; + } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) { + $date_end = dol_time_plus_duree($date_start, 1, 'm') - 1; + } } } else { - if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); } - if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); } - if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); } - if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); } + if ($q == 1) { + $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + } + if ($q == 2) { + $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + } + if ($q == 3) { + $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + } + if ($q == 4) { + $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + } } } $min = price2num(GETPOST("min", "alpha")); -if (empty($min)) $min = 0; +if (empty($min)) { + $min = 0; +} // Define modetax (0 or 1) // 0=normal, 1=option vat for services is on debit, 2=option on payments for products $modetax = $conf->global->TAX_MODE; -if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int'); -if (empty($modetax)) $modetax = 0; +if (GETPOSTISSET("modetax")) { + $modetax = GETPOST("modetax", 'int'); +} +if (empty($modetax)) { + $modetax = 0; +} // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); -if (empty($local)) -{ +if (empty($local)) { accessforbidden('Parameter localTaxType is missing'); exit; } @@ -98,9 +116,10 @@ $company_static = new Societe($db); $morequerystring = ''; $listofparams = array('date_startmonth', 'date_startyear', 'date_startday', 'date_endmonth', 'date_endyear', 'date_endday'); -foreach ($listofparams as $param) -{ - if (GETPOST($param) != '') $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); +foreach ($listofparams as $param) { + if (GETPOST($param) != '') { + $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); + } } llxHeader('', '', '', '', 0, 0, '', '', $morequerystring); @@ -117,12 +136,13 @@ $fsearch .= ''; $calc = $conf->global->MAIN_INFO_LOCALTAX_CALC.$local; // Affiche en-tete du rapport -if ($calc == 0 || $calc == 1) // Calculate on invoice for goods and services -{ +if ($calc == 0 || $calc == 1) { // Calculate on invoice for goods and services $calcmode = $calc == 0 ? $langs->trans("CalcModeLT".$local) : $langs->trans("CalcModeLT".$local."Rec"); $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); - if (!empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description .= '
'.$langs->trans("WarningDepositsNotIncluded"); + if (!empty($conf->global->MAIN_MODULE_COMPTABILITE)) { + $description .= '
'.$langs->trans("WarningDepositsNotIncluded"); + } $description .= $fsearch; $description .= ' ('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; $builddate = dol_now(); @@ -134,12 +154,13 @@ if ($calc == 0 || $calc == 1) // Calculate on invoice for goods and services $productsup = $langs->trans("Description"); $amountsup = $langs->trans("AmountHT"); } -if ($calc == 2) // Invoice for goods, payment for services -{ +if ($calc == 2) { // Invoice for goods, payment for services $calcmode = $langs->trans("CalcModeLT2Debt"); $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); - if (!empty($conf->global->MAIN_MODULE_COMPTABILITE)) $description .= '
'.$langs->trans("WarningDepositsNotIncluded"); + if (!empty($conf->global->MAIN_MODULE_COMPTABILITE)) { + $description .= '
'.$langs->trans("WarningDepositsNotIncluded"); + } $description .= $fsearch; $description .= '('.$langs->trans("TaxModuleSetupToModifyRulesLT", DOL_URL_ROOT.'/admin/company.php').')'; $builddate = dol_now(); @@ -161,8 +182,7 @@ print '
'; print '
'.dol_print_date($db->jdate($obj->da), "day").'
".dol_print_date($db->jdate($val["date"]))."".$invoicestatic->getNomUrl(1)."".$k."".$line['label']."'.($mt < 0 ?price(-$mt) : '')."'.($mt >= 0 ?price($mt) : '')."
".dol_print_date($db->jdate($val["date"]))."".$invoicestatic->getNomUrl(1)."".$k."".$line['label']."'.($mt >= 0 ?price($mt) : '')."'.($mt < 0 ?price(-$mt) : '')."
'.$langs->trans("Amount").'
'.$langs->trans("Account").''; $form->select_comptes($_POST["accountid"], "accountid", 0, "courant=1", 2); // Affiche liste des comptes courant print '
'.$langs->trans("Amount").''.price($object->amount).'
'; // IRPF that the customer has retained me -if ($calc == 0 || $calc == 2) -{ +if ($calc == 0 || $calc == 2) { print ''; print ''; print ''; @@ -185,19 +205,14 @@ if ($calc == 0 || $calc == 2) $hookmanager->initHooks(array('externalbalance')); $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (is_array($coll_list)) - { + if (is_array($coll_list)) { $total = 0; $totalamount = 0; $i = 1; - foreach ($coll_list as $coll) - { - if (($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local == 1 ? $coll->localtax1 : $coll->localtax2) != 0) - { + foreach ($coll_list as $coll) { + if (($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local == 1 ? $coll->localtax1 : $coll->localtax2) != 0) { $intra = str_replace($find, $replace, $coll->tva_intra); - if (empty($intra)) - { - if ($coll->assuj == '1') - { + if (empty($intra)) { + if ($coll->assuj == '1') { $intra = $langs->trans('Unknown'); } else { $intra = ''; @@ -227,11 +242,13 @@ if ($calc == 0 || $calc == 2) print ''; } else { $langs->load("errors"); - if ($coll_list == -1) + if ($coll_list == -1) { print ''; - elseif ($coll_list == -2) + } elseif ($coll_list == -2) { print ''; - else print ''; + } else { + print ''; + } } } @@ -252,19 +269,14 @@ if ($calc == 0 || $calc == 1) { $parameters["type"] = 'localtax'.$local; $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (is_array($coll_list)) - { + if (is_array($coll_list)) { $total = 0; $totalamount = 0; $i = 1; - foreach ($coll_list as $coll) - { - if (($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local == 1 ? $coll->localtax1 : $coll->localtax2) != 0) - { + foreach ($coll_list as $coll) { + if (($min == 0 || ($min > 0 && $coll->amount > $min)) && ($local == 1 ? $coll->localtax1 : $coll->localtax2) != 0) { $intra = str_replace($find, $replace, $coll->tva_intra); - if (empty($intra)) - { - if ($coll->assuj == '1') - { + if (empty($intra)) { + if ($coll->assuj == '1') { $intra = $langs->trans('Unknown'); } else { $intra = ''; @@ -294,11 +306,13 @@ if ($calc == 0 || $calc == 1) { print ''; } else { $langs->load("errors"); - if ($coll_list == -1) + if ($coll_list == -1) { print ''; - elseif ($coll_list == -2) + } elseif ($coll_list == -2) { print ''; - else print ''; + } else { + print ''; + } } } diff --git a/htdocs/compta/localtax/index.php b/htdocs/compta/localtax/index.php index bedb7259184..051a98a4b3b 100644 --- a/htdocs/compta/localtax/index.php +++ b/htdocs/compta/localtax/index.php @@ -37,8 +37,7 @@ $localTaxType = GETPOST('localTaxType', 'int'); // Date range $year = GETPOST("year", "int"); -if (empty($year)) -{ +if (empty($year)) { $year_current = strftime("%Y", dol_now()); $year_start = $year_current; } else { @@ -47,32 +46,46 @@ if (empty($year)) } $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); -if (empty($date_start) || empty($date_end)) // We define date_start and date_end -{ +if (empty($date_start) || empty($date_end)) { // We define date_start and date_end $q = GETPOST("q", "int"); - if (empty($q)) - { - if (GETPOST("month", "int")) { $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } else { + if (empty($q)) { + if (GETPOST("month", "int")) { + $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); + } else { $date_start = dol_get_first_day($year_start, $conf->global->SOCIETE_FISCAL_MONTH_START, false); $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; } } else { - if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); } - if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); } - if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); } - if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); } + if ($q == 1) { + $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + } + if ($q == 2) { + $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + } + if ($q == 3) { + $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + } + if ($q == 4) { + $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + } } } // Define modetax (0 or 1) // 0=normal, 1=option vat for services is on debit, 2=option on payments for products $modetax = $conf->global->TAX_MODE; -if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int'); -if (empty($modetax)) $modetax = 0; +if (GETPOSTISSET("modetax")) { + $modetax = GETPOST("modetax", 'int'); +} +if (empty($modetax)) { + $modetax = 0; +} // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); @@ -114,8 +127,7 @@ function pt($db, $sql, $date) $mode = $obj->mode; //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode; - if ($obj->mode == 'claimed' && !empty($previousmode)) - { + if ($obj->mode == 'claimed' && !empty($previousmode)) { print ''; print '\n"; print '\n"; @@ -126,19 +138,16 @@ function pt($db, $sql, $date) $amountpaid = 0; } - if ($obj->mode == 'claimed') - { + if ($obj->mode == 'claimed') { $amountclaimed = $obj->mm; $totalclaimed = $totalclaimed + $amountclaimed; } - if ($obj->mode == 'paid') - { + if ($obj->mode == 'paid') { $amountpaid = $obj->mm; $totalpaid = $totalpaid + $amountpaid; } - if ($obj->mode == 'paid') - { + if ($obj->mode == 'paid') { print ''; print '\n"; print '\n"; @@ -156,8 +165,7 @@ function pt($db, $sql, $date) $i++; } - if ($mode == 'claimed' && !empty($previousmode)) - { + if ($mode == 'claimed' && !empty($previousmode)) { print ''; print '\n"; print '\n"; @@ -181,8 +189,7 @@ function pt($db, $sql, $date) } } -if (empty($localTaxType)) -{ +if (empty($localTaxType)) { accessforbidden('Parameter localTaxType is missing'); exit; } @@ -281,11 +288,14 @@ $mend = $tmp['mon']; $total = 0; $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; $i = 0; $mcursor = 0; -while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mcursor is to avoid too large loop -{ +while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) { // $mcursor is to avoid too large loop //$m = $conf->global->SOCIETE_FISCAL_MONTH_START + ($mcursor % 12); - if ($m == 13) $y++; - if ($m > 12) $m -= 12; + if ($m == 13) { + $y++; + } + if ($m > 12) { + $m -= 12; + } $mcursor++; // Get array with details of each line @@ -294,8 +304,7 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc $x_both = array(); //now, from these two arrays, get another array with one rate per line - foreach (array_keys($x_coll) as $my_coll_rate) - { + foreach (array_keys($x_coll) as $my_coll_rate) { $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; $x_both[$my_coll_rate]['coll']['localtax1'] = $x_coll[$my_coll_rate]['localtax1']; @@ -306,7 +315,7 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc $x_both[$my_coll_rate]['paye']['localtax2'] = 0; $x_both[$my_coll_rate]['coll']['links'] = ''; $x_both[$my_coll_rate]['coll']['detail'] = array(); - foreach ($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) { + foreach ($x_coll[$my_coll_rate]['facid'] as $id => $dummy) { //$invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; //$invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; //$invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; @@ -352,11 +361,9 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc $x_both[$my_paye_rate]['paye']['links'] = ''; $x_both[$my_paye_rate]['paye']['detail'] = array(); - foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) - { + foreach ($x_paye[$my_paye_rate]['facid'] as $id => $dummy) { // ExpenseReport - if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') - { + if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') { //$expensereport->id=$x_paye[$my_paye_rate]['facid'][$id]; //$expensereport->ref=$x_paye[$my_paye_rate]['facnum'][$id]; //$expensereport->type=$x_paye[$my_paye_rate]['type'][$id]; @@ -425,14 +432,12 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc $hookmanager->initHooks(array('externalbalance')); $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!is_array($x_coll) && $coll_listbuy == -1) - { + if (!is_array($x_coll) && $coll_listbuy == -1) { $langs->load("errors"); print ''; break; } - if (!is_array($x_paye) && $coll_listbuy == -2) - { + if (!is_array($x_paye) && $coll_listbuy == -2) { print ''; break; } @@ -442,17 +447,14 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc print ''; $x_coll_sum = 0; - foreach (array_keys($x_coll) as $rate) - { + foreach (array_keys($x_coll) as $rate) { $subtot_coll_total_ht = 0; $subtot_coll_vat = 0; - foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) - { + foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { // Payment $ratiopaymentinvoice = 1; - if ($modetax != 1) - { + if ($modetax != 1) { // Define type // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); @@ -466,8 +468,7 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc } if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) - { + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { //print $langs->trans("NA"); } else { if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { @@ -486,17 +487,14 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc print ''; $x_paye_sum = 0; - foreach (array_keys($x_paye) as $rate) - { + foreach (array_keys($x_paye) as $rate) { $subtot_paye_total_ht = 0; $subtot_paye_vat = 0; - foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) - { + foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) { // Payment $ratiopaymentinvoice = 1; - if ($modetax != 1) - { + if ($modetax != 1) { // Define type // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); @@ -510,8 +508,7 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc } if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) - { + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { //print $langs->trans("NA"); } else { if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { @@ -541,8 +538,7 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc print "\n"; $i++; $m++; - if ($i > 2) - { + if ($i > 2) { print ''; print ''; print ''; diff --git a/htdocs/compta/localtax/list.php b/htdocs/compta/localtax/list.php index 4d7e2bf0e54..8742589a6a9 100644 --- a/htdocs/compta/localtax/list.php +++ b/htdocs/compta/localtax/list.php @@ -29,7 +29,9 @@ $langs->load("compta"); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); $ltt = GETPOST("localTaxType", 'int'); @@ -43,7 +45,9 @@ llxHeader(); $localtax_static = new Localtax($db); $url = DOL_URL_ROOT.'/compta/localtax/card.php?action=create&localTaxType='.$ltt; -if (!empty($socid)) $url .= '&socid='.$socid; +if (!empty($socid)) { + $url .= '&socid='.$socid; +} $newcardbutton = dolGetButtonTitle($langs->trans('NewLocalTaxPayment', ($ltt + 1)), '', 'fa fa-plus-circle', $url, '', $user->rights->tax->charges->creer); print load_fiche_titre($langs->transcountry($ltt == 2 ? "LT2Payments" : "LT1Payments", $mysoc->country_code), $newcardbutton, 'title_accountancy'); @@ -54,8 +58,7 @@ $sql .= " WHERE f.entity = ".$conf->entity." AND localtaxtype = ".$db->escape($l $sql .= " ORDER BY datev DESC"; $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; $total = 0; @@ -69,8 +72,7 @@ if ($result) print ""; print "\n"; $var = 1; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); print ''; diff --git a/htdocs/compta/localtax/quadri_detail.php b/htdocs/compta/localtax/quadri_detail.php index 2b0415800ac..aec90544e09 100644 --- a/htdocs/compta/localtax/quadri_detail.php +++ b/htdocs/compta/localtax/quadri_detail.php @@ -47,8 +47,7 @@ $langs->loadLangs(array("other", "compta", "banks", "bills", "companies", "produ $local = GETPOST('localTaxType', 'int'); // Date range $year = GETPOST("year", "int"); -if (empty($year)) -{ +if (empty($year)) { $year_current = strftime("%Y", dol_now()); $year_start = $year_current; } else { @@ -58,43 +57,62 @@ if (empty($year)) $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); // Quarter -if (empty($date_start) || empty($date_end)) // We define date_start and date_end -{ +if (empty($date_start) || empty($date_end)) { // We define date_start and date_end $q = GETPOST("q", "int"); - if (empty($q)) - { - if (GETPOST("month", "int")) { $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } else { + if (empty($q)) { + if (GETPOST("month", "int")) { + $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); + } else { $date_start = dol_get_first_day($year_start, empty($conf->global->SOCIETE_FISCAL_MONTH_START) ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START, false); - if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; - elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; - elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) $date_end = dol_time_plus_duree($date_start, 1, 'm') - 1; + if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { + $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; + } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { + $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; + } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) { + $date_end = dol_time_plus_duree($date_start, 1, 'm') - 1; + } } } else { - if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); } - if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); } - if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); } - if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); } + if ($q == 1) { + $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + } + if ($q == 2) { + $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + } + if ($q == 3) { + $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + } + if ($q == 4) { + $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + } } } $min = price2num(GETPOST("min", "alpha")); -if (empty($min)) $min = 0; +if (empty($min)) { + $min = 0; +} // Define modetax (0 or 1) // 0=normal, 1=option vat for services is on debit, 2=option on payments for products //$modetax = $conf->global->TAX_MODE; $calc = $conf->global->MAIN_INFO_LOCALTAX_CALC.$local; $modetax = $conf->global->$calc; -if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int'); -if (empty($modetax)) $modetax = 0; +if (GETPOSTISSET("modetax")) { + $modetax = GETPOST("modetax", 'int'); +} +if (empty($modetax)) { + $modetax = 0; +} // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); -if (empty($local)) -{ +if (empty($local)) { accessforbidden('Parameter localTaxType is missing'); exit; } @@ -117,9 +135,10 @@ $paymentexpensereport_static = new PaymentExpenseReport($db); $morequerystring = ''; $listofparams = array('date_startmonth', 'date_startyear', 'date_startday', 'date_endmonth', 'date_endyear', 'date_endday'); -foreach ($listofparams as $param) -{ - if (GETPOST($param) != '') $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); +foreach ($listofparams as $param) { + if (GETPOST($param) != '') { + $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); + } } llxHeader('', $langs->trans("LocalTaxReport"), '', '', 0, 0, '', '', $morequerystring); @@ -131,9 +150,15 @@ $fsearch .= ''; $name = $langs->transcountry($local == 1 ? "LT1ReportByQuarters" : "LT2ReportByQuarters", $mysoc->country_code); $calcmode = ''; -if ($modetax == 0) $calcmode = $langs->trans('OptionVATDefault'); -if ($modetax == 1) $calcmode = $langs->trans('OptionVATDebitOption'); -if ($modetax == 2) $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +if ($modetax == 0) { + $calcmode = $langs->trans('OptionVATDefault'); +} +if ($modetax == 1) { + $calcmode = $langs->trans('OptionVATDebitOption'); +} +if ($modetax == 2) { + $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +} $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRules", DOL_URL_ROOT.'/admin/taxes.php').')'; // Set period $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); @@ -164,7 +189,9 @@ if (! empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $description.='
'.$langs->trans("DepositsAreNotIncluded"); } */ -if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description .= $langs->trans("ThisIsAnEstimatedValue"); +if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) { + $description .= $langs->trans("ThisIsAnEstimatedValue"); +} // Customers invoices $elementcust = $langs->trans("CustomersInvoices"); @@ -212,28 +239,27 @@ $columns = 4; $x_coll = tax_by_rate('localtax'.$local, $db, 0, 0, $date_start, $date_end, $modetax, 'sell'); $x_paye = tax_by_rate('localtax'.$local, $db, 0, 0, $date_start, $date_end, $modetax, 'buy'); -if (!is_array($x_coll) || !is_array($x_paye)) -{ +if (!is_array($x_coll) || !is_array($x_paye)) { $langs->load("errors"); - if ($x_coll == -1) + if ($x_coll == -1) { print ''; - elseif ($x_coll == -2) + } elseif ($x_coll == -2) { print ''; - else print ''; + } else { + print ''; + } } else { $x_both = array(); //now, from these two arrays, get another array with one rate per line - foreach (array_keys($x_coll) as $my_coll_rate) - { + foreach (array_keys($x_coll) as $my_coll_rate) { $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; $x_both[$my_coll_rate]['coll']['localtax'.$local] = $x_coll[$my_coll_rate]['localtax'.$local]; $x_both[$my_coll_rate]['paye']['totalht'] = 0; $x_both[$my_coll_rate]['paye']['localtax'.$local] = 0; $x_both[$my_coll_rate]['coll']['links'] = ''; $x_both[$my_coll_rate]['coll']['detail'] = array(); - foreach ($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) - { + foreach ($x_coll[$my_coll_rate]['facid'] as $id => $dummy) { $invoice_customer->id = $x_coll[$my_coll_rate]['facid'][$id]; $invoice_customer->ref = $x_coll[$my_coll_rate]['facnum'][$id]; $invoice_customer->type = $x_coll[$my_coll_rate]['type'][$id]; @@ -273,8 +299,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_both[$my_paye_rate]['paye']['links'] = ''; $x_both[$my_paye_rate]['paye']['detail'] = array(); - foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) - { + foreach ($x_paye[$my_paye_rate]['facid'] as $id => $dummy) { $invoice_supplier->id = $x_paye[$my_paye_rate]['facid'][$id]; $invoice_supplier->ref = $x_paye[$my_paye_rate]['facnum'][$id]; $invoice_supplier->type = $x_paye[$my_paye_rate]['type'][$id]; @@ -312,15 +337,23 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_paye_ht = 0; $span = $columns - 1; - if ($modetax != 2) $span += 1; - if ($modetax != 1) $span += 1; + if ($modetax != 2) { + $span += 1; + } + if ($modetax != 1) { + $span += 1; + } // Customers invoices print ''; print ''; print ''; - if ($modetax != 2) print ''; - if ($modetax != 1) print ''; + if ($modetax != 2) { + print ''; + } + if ($modetax != 1) { + print ''; + } print ''; print ''; print ''; @@ -328,29 +361,29 @@ if (!is_array($x_coll) || !is_array($x_paye)) $LT = 0; $sameLT = false; - foreach (array_keys($x_coll) as $rate) - { + foreach (array_keys($x_coll) as $rate) { $subtot_coll_total_ht = 0; $subtot_coll_vat = 0; - if (is_array($x_both[$rate]['coll']['detail'])) - { + if (is_array($x_both[$rate]['coll']['detail'])) { // VAT Rate if ($rate != 0) { print ""; print ''; print ''."\n"; } - foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) - { - if (($local == 1 && $fields['localtax1'] != 0) || ($local == 2 && $fields['localtax2'] != 0)) - { + foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { + if (($local == 1 && $fields['localtax1'] != 0) || ($local == 2 && $fields['localtax2'] != 0)) { // Define type $type = ($fields['dtype'] ? $fields['dtype'] : $fields['ptype']); // Try to enhance type detection using date_start and date_end for free lines where type // was not saved. - if (!empty($fields['ddate_start'])) $type = 1; - if (!empty($fields['ddate_end'])) $type = 1; + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } print ''; @@ -360,21 +393,28 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Description print ''; // Total HT - if ($modetax != 2) - { + if ($modetax != 2) { print ''; @@ -397,21 +435,22 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Payment $ratiopaymentinvoice = 1; - if ($modetax != 1) - { - if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + if ($modetax != 1) { + if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } print ''; } @@ -419,7 +458,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Total collected print ''; @@ -442,8 +483,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''; print ''; - if ($modetax != 1) - { + if ($modetax != 1) { print ''; print ''; } @@ -452,13 +492,11 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; } - if (count($x_coll) == 0) // Show a total ine if nothing shown - { + if (count($x_coll) == 0) { // Show a total ine if nothing shown print ''; print ''; print ''; - if ($modetax == 0) - { + if ($modetax == 0) { print ''; print ''; } @@ -477,8 +515,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''; print ''; - if ($modetax != 1) - { + if ($modetax != 1) { print ''; print ''; } @@ -486,28 +523,28 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''."\n"; - foreach (array_keys($x_paye) as $rate) - { + foreach (array_keys($x_paye) as $rate) { $subtot_paye_total_ht = 0; $subtot_paye_vat = 0; - if (is_array($x_both[$rate]['paye']['detail'])) - { + if (is_array($x_both[$rate]['paye']['detail'])) { if ($rate != 0) { print ""; print ''; print ''."\n"; } - foreach ($x_both[$rate]['paye']['detail'] as $index=>$fields) - { - if (($local == 1 && $fields['localtax1'] != 0) || ($local == 2 && $fields['localtax2'] != 0)) - { + foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) { + if (($local == 1 && $fields['localtax1'] != 0) || ($local == 2 && $fields['localtax2'] != 0)) { // Define type $type = ($fields['dtype'] ? $fields['dtype'] : $fields['ptype']); // Try to enhance type detection using date_start and date_end for free lines where type // was not saved. - if (!empty($fields['ddate_start'])) $type = 1; - if (!empty($fields['ddate_end'])) $type = 1; + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } print ''; @@ -517,16 +554,20 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Description print ''; // Total HT - if ($modetax != 2) - { + if ($modetax != 2) { print ''; print ''; print ''; - if ($modetax != 1) - { + if ($modetax != 1) { print ''; print ''; } diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index 8ea227482b1..0fcbf6a914a 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -59,16 +59,14 @@ $multicurrency_amounts = array(); $multicurrency_amountsresttopay = array(); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $socid = $user->socid; } $object = new Facture($db); // Load object -if ($facid > 0) -{ +if ($facid > 0) { $ret = $object->fetch($facid); } @@ -84,12 +82,12 @@ $formquestion = array(); $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) - { +if (empty($reshook)) { + if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) { $error = 0; $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); @@ -102,28 +100,27 @@ if (empty($reshook)) // Generate payment array and check if there is payment higher than invoice and payment date before invoice date $tmpinvoice = new Facture($db); - foreach ($_POST as $key => $value) - { - if (substr($key, 0, 7) == 'amount_' && GETPOST($key) != '') - { + foreach ($_POST as $key => $value) { + if (substr($key, 0, 7) == 'amount_' && GETPOST($key) != '') { $cursorfacid = substr($key, 7); $amounts[$cursorfacid] = price2num(GETPOST($key)); $totalpayment = $totalpayment + $amounts[$cursorfacid]; - if (!empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++; + if (!empty($amounts[$cursorfacid])) { + $atleastonepaymentnotnull++; + } $result = $tmpinvoice->fetch($cursorfacid); - if ($result <= 0) dol_print_error($db); + if ($result <= 0) { + dol_print_error($db); + } $amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement()); - if ($amounts[$cursorfacid]) - { + if ($amounts[$cursorfacid]) { // Check amount - if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) - { + if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) { $addwarning = 1; $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay"); } // Check date - if ($datepaye && ($datepaye < $tmpinvoice->date)) - { + if ($datepaye && ($datepaye < $tmpinvoice->date)) { $langs->load("errors"); //$error++; setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings'); @@ -131,26 +128,26 @@ if (empty($reshook)) } $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => $_POST[$key]); - } elseif (substr($key, 0, 21) == 'multicurrency_amount_') - { + } elseif (substr($key, 0, 21) == 'multicurrency_amount_') { $cursorfacid = substr($key, 21); $multicurrency_amounts[$cursorfacid] = price2num(GETPOST($key)); $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid]; - if (!empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++; + if (!empty($multicurrency_amounts[$cursorfacid])) { + $atleastonepaymentnotnull++; + } $result = $tmpinvoice->fetch($cursorfacid); - if ($result <= 0) dol_print_error($db); + if ($result <= 0) { + dol_print_error($db); + } $multicurrency_amountsresttopay[$cursorfacid] = price2num($tmpinvoice->multicurrency_total_ttc - $tmpinvoice->getSommePaiement(1)); - if ($multicurrency_amounts[$cursorfacid]) - { + if ($multicurrency_amounts[$cursorfacid]) { // Check amount - if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) - { + if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) { $addwarning = 1; $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay"); } // Check date - if ($datepaye && ($datepaye < $tmpinvoice->date)) - { + if ($datepaye && ($datepaye < $tmpinvoice->date)) { $langs->load("errors"); //$error++; setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings'); @@ -162,37 +159,31 @@ if (empty($reshook)) } // Check parameters - if (!GETPOST('paiementcode')) - { + if (!GETPOST('paiementcode')) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('PaymentMode')), null, 'errors'); $error++; } - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { // If bank module is on, account is required to enter a payment - if (GETPOST('accountid') <= 0) - { + if (GETPOST('accountid') <= 0) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors'); $error++; } } - if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull)) - { + if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull)) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->trans('PaymentAmount')), null, 'errors'); $error++; } - if (empty($datepaye)) - { + if (empty($datepaye)) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('Date')), null, 'errors'); $error++; } // Check if payments in both currency - if ($totalpayment > 0 && $multicurrency_totalpayment > 0) - { + if ($totalpayment > 0 && $multicurrency_totalpayment > 0) { setEventMessages($langs->transnoentities('ErrorPaymentInBothCurrency'), null, 'errors'); $error++; } @@ -201,10 +192,8 @@ if (empty($reshook)) /* * Action add_paiement */ - if ($action == 'add_paiement') - { - if ($error) - { + if ($action == 'add_paiement') { + if ($error) { $action = 'create'; } // The next of this action is displayed at the page's bottom. @@ -213,8 +202,7 @@ if (empty($reshook)) /* * Action confirm_paiement */ - if ($action == 'confirm_paiement' && $confirm == 'yes') - { + if ($action == 'confirm_paiement' && $confirm == 'yes') { $error = 0; $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); @@ -222,36 +210,32 @@ if (empty($reshook)) $db->begin(); $thirdparty = new Societe($db); - if ($socid > 0) $thirdparty->fetch($socid); + if ($socid > 0) { + $thirdparty->fetch($socid); + } // Clean parameters amount if payment is for a credit note - foreach ($amounts as $key => $value) // How payment is dispatched - { + foreach ($amounts as $key => $value) { // How payment is dispatched $tmpinvoice = new Facture($db); $tmpinvoice->fetch($key); - if ($tmpinvoice->type == Facture::TYPE_CREDIT_NOTE) - { + if ($tmpinvoice->type == Facture::TYPE_CREDIT_NOTE) { $newvalue = price2num($value, 'MT'); $amounts[$key] = - abs($newvalue); } } - foreach ($multicurrency_amounts as $key => $value) // How payment is dispatched - { + foreach ($multicurrency_amounts as $key => $value) { // How payment is dispatched $tmpinvoice = new Facture($db); $tmpinvoice->fetch($key); - if ($tmpinvoice->type == Facture::TYPE_CREDIT_NOTE) - { + if ($tmpinvoice->type == Facture::TYPE_CREDIT_NOTE) { $newvalue = price2num($value, 'MT'); $multicurrency_amounts[$key] = - abs($newvalue); } } - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { // If the bank module is active, an account is required to input a payment - if (GETPOST('accountid', 'int') <= 0) - { + if (GETPOST('accountid', 'int') <= 0) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors'); $error++; } @@ -266,47 +250,48 @@ if (empty($reshook)) $paiement->num_payment = GETPOST('num_paiement', 'alpha'); $paiement->note_private = GETPOST('comment', 'alpha'); - if (!$error) - { + if (!$error) { // Create payment and update this->multicurrency_amounts if this->amounts filled or // this->amounts if this->multicurrency_amounts filled. $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices') == 'on' ? 1 : 0), $thirdparty); // This include closing invoices and regenerating documents - if ($paiement_id < 0) - { + if ($paiement_id < 0) { setEventMessages($paiement->error, $paiement->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $label = '(CustomerInvoicePayment)'; - if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + if (GETPOST('type') == Facture::TYPE_CREDIT_NOTE) { + $label = '(CustomerInvoicePaymentBack)'; // Refund of a credit note + } $result = $paiement->addPaymentToBank($user, 'payment', $label, GETPOST('accountid'), GETPOST('chqemetteur'), GETPOST('chqbank')); - if ($result < 0) - { + if ($result < 0) { setEventMessages($paiement->error, $paiement->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $db->commit(); // If payment dispatching on more than one invoice, we stay on summary page, otherwise jump on invoice card $invoiceid = 0; - foreach ($paiement->amounts as $key => $amount) - { + foreach ($paiement->amounts as $key => $amount) { $facid = $key; - if (is_numeric($amount) && $amount <> 0) - { - if ($invoiceid != 0) $invoiceid = -1; // There is more than one invoice payed by this payment - else $invoiceid = $facid; + if (is_numeric($amount) && $amount <> 0) { + if ($invoiceid != 0) { + $invoiceid = -1; // There is more than one invoice payed by this payment + } else { + $invoiceid = $facid; + } } } - if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$invoiceid; - else $loc = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$paiement_id; + if ($invoiceid > 0) { + $loc = DOL_URL_ROOT.'/compta/facture/card.php?facid='.$invoiceid; + } else { + $loc = DOL_URL_ROOT.'/compta/paiement/card.php?id='.$paiement_id; + } header('Location: '.$loc); exit; } else { @@ -327,23 +312,24 @@ llxHeader('', $langs->trans("Payment")); -if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement') -{ +if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement') { $facture = new Facture($db); $result = $facture->fetch($facid); - if ($result >= 0) - { + if ($result >= 0) { $facture->fetch_thirdparty(); $title = ''; - if ($facture->type != Facture::TYPE_CREDIT_NOTE) $title .= $langs->trans("EnterPaymentReceivedFromCustomer"); - if ($facture->type == Facture::TYPE_CREDIT_NOTE) $title .= $langs->trans("EnterPaymentDueToCustomer"); + if ($facture->type != Facture::TYPE_CREDIT_NOTE) { + $title .= $langs->trans("EnterPaymentReceivedFromCustomer"); + } + if ($facture->type == Facture::TYPE_CREDIT_NOTE) { + $title .= $langs->trans("EnterPaymentDueToCustomer"); + } print load_fiche_titre($title); // Initialize data for confirmation (this is used because data can be change during confirmation) - if ($action == 'add_paiement') - { + if ($action == 'add_paiement') { $i = 0; $formquestion[$i++] = array('type' => 'hidden', 'name' => 'facid', 'value' => $facture->id); @@ -353,15 +339,15 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie // Invoice with Paypal transaction // TODO add hook here - if (!empty($conf->paypalplus->enabled) && $conf->global->PAYPAL_ENABLE_TRANSACTION_MANAGEMENT && !empty($facture->ref_ext)) - { - if (!empty($conf->global->PAYPAL_BANK_ACCOUNT)) $accountid = $conf->global->PAYPAL_BANK_ACCOUNT; + if (!empty($conf->paypalplus->enabled) && $conf->global->PAYPAL_ENABLE_TRANSACTION_MANAGEMENT && !empty($facture->ref_ext)) { + if (!empty($conf->global->PAYPAL_BANK_ACCOUNT)) { + $accountid = $conf->global->PAYPAL_BANK_ACCOUNT; + } $paymentnum = $facture->ref_ext; } // Add realtime total information - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print "\n".''."\n"; } - print ''; - print ''; - print ''; + print ''; + print ''; + print ''; - print '
'; - print '
'; - print $langs->trans("Type").':   '; - print '
'; - print ''; - print '   '; - print ''; - print '
'; - print "
\n"; + print '
'; + print '
'; + print $langs->trans("Type").':   '; + print '
'; + print ''; + print '   '; + print ''; + print '
'; + print "
\n"; - dol_fiche_head(); + dol_fiche_head(); - print '
'.$langs->trans("Num").''.$langs->trans("Customer").'
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Error").'
'.$langs->trans("Error").'
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Error").'
'.$langs->trans("Error").'
'.$previousmonth."'.price($amountclaimed)."
'.$obj->dm."'.price($amountclaimed)."
'.$previousmonth."'.price($amountclaimed)."
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.dol_print_date(dol_mktime(0, 0, 0, $m, 1, $y), "%b %Y").''.price(price2num($x_coll_sum, 'MT')).'
'.$langs->trans("SubTotal").':'.price(price2num($subtotalcoll, 'MT')).'".$langs->trans("PayedByThisPayment")."
'.$langs->trans("ErrorNoAccountancyModuleLoaded").'
'.$langs->trans("FeatureNotYetAvailable").'
'.$langs->trans("Error").'
'.$langs->trans("Error").'
'.$elementcust.''.$productcust.''.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$amountcust.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$langs->trans("BI").''.$vatcust.'
'.$langs->trans("Rate").': '.vatrate($rate).'%
'; - if ($fields['pid']) - { + if ($fields['pid']) { $product_static->id = $fields['pid']; $product_static->ref = $fields['pref']; $product_static->type = $fields['ptype']; print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']), 16); + if (dol_string_nohtmltag($fields['descr'])) { + print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']), 16); + } } else { - if ($type) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); - if (preg_match('/^\((.*)\)$/', $fields['descr'], $reg)) - { - if ($reg[1] == 'DEPOSIT') $fields['descr'] = $langs->transnoentitiesnoconv('Deposit'); - elseif ($reg[1] == 'CREDIT_NOTE') $fields['descr'] = $langs->transnoentitiesnoconv('CreditNote'); - else $fields['descr'] = $langs->transnoentitiesnoconv($reg[1]); + if ($type) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } + if (preg_match('/^\((.*)\)$/', $fields['descr'], $reg)) { + if ($reg[1] == 'DEPOSIT') { + $fields['descr'] = $langs->transnoentitiesnoconv('Deposit'); + } elseif ($reg[1] == 'CREDIT_NOTE') { + $fields['descr'] = $langs->transnoentitiesnoconv('CreditNote'); + } else { + $fields['descr'] = $langs->transnoentitiesnoconv($reg[1]); + } } print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']), 16); @@ -384,12 +424,10 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) - { + if (price2num($fields['ftotal_ttc'])) { $ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']); } print ''; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) - { + if ($fields['payment_amount'] && $fields['ftotal_ttc']) { $payment_static->id = $fields['payment_id']; print $payment_static->getNomUrl(2); } - if ($type == 0) - { + if ($type == 0) { print $langs->trans("NotUsedForGoods"); } else { print price($fields['payment_amount']); - if (isset($fields['payment_amount'])) print ' ('.round($ratiopaymentinvoice * 100, 2).'%)'; + if (isset($fields['payment_amount'])) { + print ' ('.round($ratiopaymentinvoice * 100, 2).'%)'; + } } print ''; $temp_ht = $fields['totalht']; - if ($type == 1) $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + if ($type == 1) { + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + } print price(price2num($temp_ht, 'MT')); print '
'.$langs->trans("Total").':  
 '.$langs->trans("Total").':  
'.$elementsup.''.$productsup.''.$amountsup.''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'.$vatsup.'
'.$langs->trans("Rate").': '.vatrate($rate).'%
'; - if ($fields['pid']) - { + if ($fields['pid']) { $product_static->id = $fields['pid']; $product_static->ref = $fields['pref']; $product_static->type = $fields['ptype']; print $product_static->getNomUrl(1); - if (dol_string_nohtmltag($fields['descr'])) print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']), 16); + if (dol_string_nohtmltag($fields['descr'])) { + print ' - '.dol_trunc(dol_string_nohtmltag($fields['descr']), 16); + } } else { - if ($type) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($type) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } print $text.' '.dol_trunc(dol_string_nohtmltag($fields['descr']), 16); // Show range @@ -535,12 +576,10 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) - { + if (price2num($fields['ftotal_ttc'])) { //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; $ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']); //print ' ('.round($ratiolineinvoice*100,2).'%)'; @@ -550,17 +589,16 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Payment $ratiopaymentinvoice = 1; - if ($modetax != 1) - { + if ($modetax != 1) { print ''; - if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); - if ($fields['payment_amount'] && $fields['ftotal_ttc']) - { + if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } + if ($fields['payment_amount'] && $fields['ftotal_ttc']) { $paymentfourn_static->id = $fields['payment_id']; print $paymentfourn_static->getNomUrl(2); } - if ($type == 0) - { + if ($type == 0) { print $langs->trans("NA"); } else { print price(price2num($fields['payment_amount'], 'MT')); @@ -596,8 +634,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) print '
 '.$langs->trans("Total").':  
'; + print '
'; - print ''; - print ''; + print ''; + print ''; - print ''; + print ''; // Label if ($refund == 1) { @@ -457,14 +429,13 @@ if ($action == 'create') // Amount print ''; - // Type payment + // Type payment print '\n"; print ""; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print ''; @@ -485,19 +456,19 @@ if ($action == 'create') 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; // Bouton Save payment print ''; - print '
'.$langs->trans("DatePayment").''; - print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1); - print '
'.$langs->trans("DatePayment").''; + print $form->selectDate($datep, "datep", '', '', '', 'add', 1, 1); + print '
'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).''; - print $form->selectDate((GETPOST("datevmonth", 'int') ? $datev : -1), "datev", '', '', '', 'add', 1, 1); - print '
'.$form->textwithpicto($langs->trans("PeriodEndDate"), $langs->trans("LastDayTaxIsRelatedTo")).''; + print $form->selectDate((GETPOST("datevmonth", 'int') ? $datev : -1), "datev", '', '', '', 'add', 1, 1); + print '
'.$langs->trans("Amount").'
'.$langs->trans("PaymentMode").''; $form->select_types_paiements(GETPOST("type_payment"), "type_payment"); print "
'.$langs->trans("BankAccount").''; $form->select_comptes(GETPOST("accountid", 'int'), "accountid", 0, "courant=1", 1); // List of bank account available print '
'; print $langs->trans("ClosePaidVATAutomatically"); print '
'; + print ''; - dol_fiche_end(); + dol_fiche_end(); print '
'; print ''; @@ -505,19 +476,17 @@ if ($action == 'create') print ''; print '
'; - print ''; + print ''; } // View mode -if ($id) -{ +if ($id) { $head = vat_prepare_head($object); $totalpaye = $object->getSommePaiement(); // Clone confirmation - if ($action === 'clone') - { + if ($action === 'clone') { $formquestion = array( array('type' => 'text', 'name' => 'clone_label', 'label' => $langs->trans("Label"), 'value' => $langs->trans("CopyOf").' '.$object->label), ); @@ -528,20 +497,17 @@ if ($id) print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneVAT', $object->ref), 'confirm_clone', $formquestion, 'yes', 1, 240); } - if ($action == 'paid') - { + if ($action == 'paid') { $text = $langs->trans('ConfirmPayVAT'); print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans('PayVAT'), $text, "confirm_paid", '', '', 2); } - if ($action == 'delete') - { + if ($action == 'delete') { $text = $langs->trans('ConfirmDeleteVAT'); print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('DeleteVAT'), $text, 'confirm_delete', '', '', 2); } - if ($action == 'edit') - { + if ($action == 'edit') { print "
id&action=update\" method=\"post\">"; print ''; } @@ -593,8 +559,9 @@ if ($id) print ''; - if ($action != 'editmode') + if ($action != 'editmode') { print ''; + } print '
'; print $langs->trans('PaymentMode'); print 'id.'">'.img_edit($langs->trans('SetMode'), 1).'
'; print ''; if ($action == 'editmode') { @@ -605,14 +572,14 @@ if ($id) print ''; // Bank account - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print ''; print ''; + } print '
'; print $langs->trans('BankAccount'); print ''; - if ($action != 'editbankaccount' && $user->rights->tax->charges->creer) + if ($action != 'editbankaccount' && $user->rights->tax->charges->creer) { print 'id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'
'; print ''; if ($action == 'editbankaccount') { @@ -659,8 +626,7 @@ if ($id) //print $sql; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $totalpaye = 0; $num = $db->num_rows($resql); @@ -678,11 +644,9 @@ if ($id) print ''.$langs->trans("Amount").''; print ''; - if ($num > 0) - { + if ($num > 0) { $bankaccountstatic = new Account($db); - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); print ''; @@ -690,8 +654,7 @@ if ($id) print ''.dol_print_date($db->jdate($objp->dp), 'day')."\n"; $labeltype = $langs->trans("PaymentType".$objp->type_code) != ("PaymentType".$objp->type_code) ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type; print "".$labeltype.' '.$objp->num_payment."\n"; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { $bankaccountstatic->id = $objp->baid; $bankaccountstatic->ref = $objp->baref; $bankaccountstatic->label = $objp->baref; @@ -707,8 +670,9 @@ if ($id) } print ''; - if ($bankaccountstatic->id) + if ($bankaccountstatic->id) { print $bankaccountstatic->getNomUrl(1, 'transactions'); + } print ''; } print ''.price($objp->amount)."\n"; @@ -716,8 +680,7 @@ if ($id) $totalpaye += $objp->amount; $i++; } - } - else { + } else { print ''.$langs->trans("None").''; print ''; print ''; @@ -736,8 +699,7 @@ if ($id) print '
'; $db->free($resql); - } - else { + } else { dol_print_error($db); } @@ -749,8 +711,7 @@ if ($id) dol_fiche_end(); - if ($action == 'edit') - { + if ($action == 'edit') { print '
'; print ''; print '   '; @@ -763,23 +724,19 @@ if ($id) * Action buttons */ print "
\n"; - if ($action != 'edit') - { + if ($action != 'edit') { // Reopen - if ($object->paye && $user->rights->tax->charges->creer) - { + if ($object->paye && $user->rights->tax->charges->creer) { print ""; } // Edit - if ($object->paye == 0 && $user->rights->tax->charges->creer) - { + if ($object->paye == 0 && $user->rights->tax->charges->creer) { print ""; } // Emit payment - if ($object->paye == 0 && ((price2num($object->amount) < 0 && price2num($resteapayer, 'MT') < 0) || (price2num($object->amount) > 0 && price2num($resteapayer, 'MT') > 0)) && $user->rights->tax->charges->creer) - { + if ($object->paye == 0 && ((price2num($object->amount) < 0 && price2num($resteapayer, 'MT') < 0) || (price2num($object->amount) > 0 && price2num($resteapayer, 'MT') > 0)) && $user->rights->tax->charges->creer) { print ""; } @@ -789,22 +746,18 @@ if ($id) (round($resteapayer) <= 0 && $object->amount > 0) || (round($resteapayer) >= 0 && $object->amount < 0) ) - && $user->rights->tax->charges->creer) - { + && $user->rights->tax->charges->creer) { print ""; } // Clone - if ($user->rights->tax->charges->creer) - { + if ($user->rights->tax->charges->creer) { print ""; } - if (!empty($user->rights->tax->charges->supprimer) && empty($totalpaye)) - { + if (!empty($user->rights->tax->charges->supprimer) && empty($totalpaye)) { print ''; - } - else { + } else { print ''; } } diff --git a/htdocs/compta/tva/class/paymentvat.class.php b/htdocs/compta/tva/class/paymentvat.class.php index 13369e596bc..ff1c8b46040 100644 --- a/htdocs/compta/tva/class/paymentvat.class.php +++ b/htdocs/compta/tva/class/paymentvat.class.php @@ -48,8 +48,8 @@ class PaymentVAT extends CommonObject public $picto = 'payment'; /** - * @var int ID - */ + * @var int ID + */ public $fk_tva; public $datec = ''; @@ -62,12 +62,12 @@ class PaymentVAT extends CommonObject */ public $total; - public $amount; // Total amount of payment - public $amounts = array(); // Array of amounts + public $amount; // Total amount of payment + public $amounts = array(); // Array of amounts - /** - * @var int ID - */ + /** + * @var int ID + */ public $fk_typepaiement; /** @@ -82,18 +82,18 @@ class PaymentVAT extends CommonObject public $num_payment; /** - * @var int ID - */ + * @var int ID + */ public $fk_bank; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_creat; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_modif; /** @@ -108,8 +108,8 @@ class PaymentVAT extends CommonObject /** * Create payment of social contribution into database. - * Use this->amounts to have list of lines for the payment - * + * Use this->amounts to have list of lines for the payment + * * @param User $user User making payment * @param int $closepaidcontrib 1=Also close payed contributions to paid, 0=Do nothing more * @return int <0 if KO, id of payment if OK @@ -120,45 +120,62 @@ class PaymentVAT extends CommonObject $error = 0; - $now = dol_now(); + $now = dol_now(); dol_syslog(get_class($this)."::create", LOG_DEBUG); // Validate parametres - if (!$this->datepaye) - { + if (!$this->datepaye) { $this->error = 'ErrorBadValueForParameterCreatePaymentVAT'; return -1; } // Clean parameters - if (isset($this->fk_tva)) $this->fk_tva = (int) $this->fk_tva; - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepaiement)) $this->fk_typepaiement = (int) $this->fk_typepaiement; - if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note)) $this->note = trim($this->note); - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + if (isset($this->fk_tva)) { + $this->fk_tva = (int) $this->fk_tva; + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepaiement)) { + $this->fk_typepaiement = (int) $this->fk_typepaiement; + } + if (isset($this->num_paiement)) { + $this->num_paiement = trim($this->num_paiement); // deprecated + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note)) { + $this->note = trim($this->note); + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } - $totalamount = 0; - foreach ($this->amounts as $key => $value) // How payment is dispatch - { - $newvalue = price2num($value, 'MT'); - $this->amounts[$key] = $newvalue; - $totalamount += $newvalue; - } - $totalamount = price2num($totalamount); + $totalamount = 0; + foreach ($this->amounts as $key => $value) { // How payment is dispatch + $newvalue = price2num($value, 'MT'); + $this->amounts[$key] = $newvalue; + $totalamount += $newvalue; + } + $totalamount = price2num($totalamount); - // Check parameters - if ($totalamount == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + // Check parameters + if ($totalamount == 0) { + return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + } $this->db->begin(); - if ($totalamount != 0) - { + if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_vat (fk_tva, datec, datep, amount,"; $sql .= " fk_typepaiement, num_paiement, note, fk_user_creat, fk_bank)"; $sql .= " VALUES ($this->chid, '".$this->db->idate($now)."',"; @@ -168,21 +185,17 @@ class PaymentVAT extends CommonObject $sql .= " 0)"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_vat"); // Insere tableau des montants / factures - foreach ($this->amounts as $key => $amount) - { + foreach ($this->amounts as $key => $amount) { $contribid = $key; - if (is_numeric($amount) && $amount <> 0) - { + if (is_numeric($amount) && $amount <> 0) { $amount = price2num($amount); // If we want to closed payed invoices - if ($closepaidcontrib) - { + if ($closepaidcontrib) { $contrib = new Tva($this->db); $contrib->fetch($contribid); $paiement = $contrib->getSommePaiement(); @@ -192,31 +205,30 @@ class PaymentVAT extends CommonObject $deposits = 0; $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT'); $remaintopay = price2num($contrib->amount - $paiement - $creditnotes - $deposits, 'MT'); - if ($remaintopay == 0) - { + if ($remaintopay == 0) { $result = $contrib->setPaid($user); + } else { + dol_syslog("Remain to pay for conrib ".$contribid." not null. We do nothing."); } - else dol_syslog("Remain to pay for conrib ".$contribid." not null. We do nothing."); } } } - } - else { + } else { $error++; } } $result = $this->call_trigger('PAYMENTVAT_CREATE', $user); - if ($result < 0) $error++; - - if ($totalamount != 0 && !$error) - { - $this->amount = $totalamount; - $this->total = $totalamount; // deprecated - $this->db->commit(); - return $this->id; + if ($result < 0) { + $error++; } - else { + + if ($totalamount != 0 && !$error) { + $this->amount = $totalamount; + $this->total = $totalamount; // deprecated + $this->db->commit(); + return $this->id; + } else { $this->error = $this->db->error(); $this->db->rollback(); return -1; @@ -254,10 +266,8 @@ class PaymentVAT extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -285,8 +295,7 @@ class PaymentVAT extends CommonObject $this->db->free($resql); return 1; - } - else { + } else { $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -307,15 +316,33 @@ class PaymentVAT extends CommonObject // Clean parameters - if (isset($this->fk_tva)) $this->fk_tva = (int) $this->fk_tva; - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepaiement)) $this->fk_typepaiement = (int) $this->fk_typepaiement; - if (isset($this->num_paiement)) $this->num_paiement = trim($this->num_paiement); // deprecated - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note)) $this->note = trim($this->note); - if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank; - if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat; - if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif; + if (isset($this->fk_tva)) { + $this->fk_tva = (int) $this->fk_tva; + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepaiement)) { + $this->fk_typepaiement = (int) $this->fk_typepaiement; + } + if (isset($this->num_paiement)) { + $this->num_paiement = trim($this->num_paiement); // deprecated + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note)) { + $this->note = trim($this->note); + } + if (isset($this->fk_bank)) { + $this->fk_bank = (int) $this->fk_bank; + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = (int) $this->fk_user_creat; + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = (int) $this->fk_user_modif; + } @@ -344,20 +371,19 @@ class PaymentVAT extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } - else { + } else { $this->db->commit(); return 1; } @@ -380,39 +406,36 @@ class PaymentVAT extends CommonObject $this->db->begin(); - if ($this->bank_line > 0) - { - $accline = new AccountLine($this->db); + if ($this->bank_line > 0) { + $accline = new AccountLine($this->db); $accline->fetch($this->bank_line); $result = $accline->delete(); if ($result < 0) { $this->errors[] = $accline->error; $error++; } - } + } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_vat"; $sql .= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } $this->db->rollback(); return -1 * $error; - } - else { + } else { $this->db->commit(); return 1; } @@ -448,8 +471,7 @@ class PaymentVAT extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $error++; } @@ -457,12 +479,10 @@ class PaymentVAT extends CommonObject unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; - } - else { + } else { $this->db->rollback(); return -1; } @@ -470,11 +490,11 @@ class PaymentVAT extends CommonObject /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void */ public function initAsSpecimen() { @@ -495,101 +515,97 @@ class PaymentVAT extends CommonObject } - /** - * Add record into bank for payment with links between this bank record and invoices of payment. - * All payment properties must have been set first like after a call to create(). - * - * @param User $user Object of user making payment - * @param string $mode 'payment_sc' - * @param string $label Label to use in bank record - * @param int $accountid Id of bank account to do link with - * @param string $emetteur_nom Name of transmitter - * @param string $emetteur_banque Name of bank - * @return int <0 if KO, >0 if OK - */ - public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) - { - global $conf; + /** + * Add record into bank for payment with links between this bank record and invoices of payment. + * All payment properties must have been set first like after a call to create(). + * + * @param User $user Object of user making payment + * @param string $mode 'payment_sc' + * @param string $label Label to use in bank record + * @param int $accountid Id of bank account to do link with + * @param string $emetteur_nom Name of transmitter + * @param string $emetteur_banque Name of bank + * @return int <0 if KO, >0 if OK + */ + public function addPaymentToBank($user, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque) + { + global $conf; // Clean data - $this->num_payment = trim($this->num_payment ? $this->num_payment : $this->num_paiement); + $this->num_payment = trim($this->num_payment ? $this->num_payment : $this->num_paiement); - $error = 0; + $error = 0; - if (!empty($conf->banque->enabled)) - { - include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + if (!empty($conf->banque->enabled)) { + include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $acc = new Account($this->db); - $acc->fetch($accountid); + $acc = new Account($this->db); + $acc->fetch($accountid); - $total = $this->total; - if ($mode == 'payment_vat') $total = -$total; + $total = $this->total; + if ($mode == 'payment_vat') { + $total = -$total; + } - // Insert payment into llx_bank - $bank_line_id = $acc->addline( - $this->datepaye, - $this->paiementtype, // Payment mode id or code ("CHQ or VIR for example") - $label, - $total, - $this->num_payment, - '', - $user, - $emetteur_nom, - $emetteur_banque - ); + // Insert payment into llx_bank + $bank_line_id = $acc->addline( + $this->datepaye, + $this->paiementtype, // Payment mode id or code ("CHQ or VIR for example") + $label, + $total, + $this->num_payment, + '', + $user, + $emetteur_nom, + $emetteur_banque + ); - // Mise a jour fk_bank dans llx_paiement. - // On connait ainsi le paiement qui a genere l'ecriture bancaire - if ($bank_line_id > 0) - { - $result = $this->update_fk_bank($bank_line_id); - if ($result <= 0) - { - $error++; - dol_print_error($this->db); - } + // Mise a jour fk_bank dans llx_paiement. + // On connait ainsi le paiement qui a genere l'ecriture bancaire + if ($bank_line_id > 0) { + $result = $this->update_fk_bank($bank_line_id); + if ($result <= 0) { + $error++; + dol_print_error($this->db); + } - // Add link 'payment', 'payment_supplier', 'payment_sc' in bank_url between payment and bank transaction - $url = ''; - if ($mode == 'payment_vat') $url = DOL_URL_ROOT.'/compta/payment_vat/card.php?id='; - if ($url) - { - $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); - if ($result <= 0) - { - $error++; - dol_print_error($this->db); - } - } + // Add link 'payment', 'payment_supplier', 'payment_sc' in bank_url between payment and bank transaction + $url = ''; + if ($mode == 'payment_vat') { + $url = DOL_URL_ROOT.'/compta/payment_vat/card.php?id='; + } + if ($url) { + $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); + if ($result <= 0) { + $error++; + dol_print_error($this->db); + } + } - // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment) - $linkaddedforthirdparty = array(); - foreach ($this->amounts as $key => $value) - { - if ($mode == 'payment_vat') - { - $tva = new Tva($this->db); - $tva->fetch($key); - $result = $acc->add_url_line($bank_line_id, $tva->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', '('.$tva->label.')', 'vat'); - if ($result <= 0) dol_print_error($this->db); - } - } - } - else { - $this->error = $acc->error; - $error++; - } - } + // Add link 'company' in bank_url between invoice and bank transaction (for each invoice concerned by payment) + $linkaddedforthirdparty = array(); + foreach ($this->amounts as $key => $value) { + if ($mode == 'payment_vat') { + $tva = new Tva($this->db); + $tva->fetch($key); + $result = $acc->add_url_line($bank_line_id, $tva->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', '('.$tva->label.')', 'vat'); + if ($result <= 0) { + dol_print_error($this->db); + } + } + } + } else { + $this->error = $acc->error; + $error++; + } + } - if (!$error) - { - return 1; - } - else { - return -1; - } - } + if (!$error) { + return 1; + } else { + return -1; + } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps @@ -606,11 +622,9 @@ class PaymentVAT extends CommonObject dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { return 1; - } - else { + } else { $this->error = $this->db->error(); return 0; } @@ -693,30 +707,41 @@ class PaymentVAT extends CommonObject $result = ''; - if (empty($this->ref)) $this->ref = $this->lib; + if (empty($this->ref)) { + $this->ref = $this->lib; + } $label = img_picto('', $this->picto).' '.$langs->trans("VATPayment").''; $label .= '
'.$langs->trans('Ref').': '.$this->ref; if (!empty($this->label)) { $labeltoshow = $this->label; $reg = array(); - if (preg_match('/^\((.*)\)$/i', $this->label, $reg)) - { + if (preg_match('/^\((.*)\)$/i', $this->label, $reg)) { // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1] == 'paiement') $reg[1] = 'Payment'; + if ($reg[1] == 'paiement') { + $reg[1] = 'Payment'; + } $labeltoshow = $langs->trans($reg[1]); } $label .= '
'.$langs->trans('Label').': '.$labeltoshow; } - if ($this->datep) $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->datep, 'day'); + if ($this->datep) { + $label .= '
'.$langs->trans('Date').': '.dol_print_date($this->datep, 'day'); + } if (!empty($this->id)) { $link = ''; $linkend = ''; - if ($withpicto) $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + } } return $result; diff --git a/htdocs/compta/tva/class/tva.class.php b/htdocs/compta/tva/class/tva.class.php index a39a00d8b01..f45112aedda 100644 --- a/htdocs/compta/tva/class/tva.class.php +++ b/htdocs/compta/tva/class/tva.class.php @@ -57,13 +57,13 @@ class Tva extends CommonObject public $num_payment; /** - * @var string label - */ - public $label; + * @var string label + */ + public $label; - /** - * @var int ID - */ + /** + * @var int ID + */ public $fk_bank; /** @@ -72,39 +72,39 @@ class Tva extends CommonObject public $accountid; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_creat; /** - * @var int ID - */ + * @var int ID + */ public $fk_user_modif; const STATUS_UNPAID = 0; const STATUS_PAID = 1; - /** + /** * Constructor * * @param DoliDB $db Database handler - */ - public function __construct($db) - { - $this->db = $db; - } + */ + public function __construct($db) + { + $this->db = $db; + } - /** - * Create in database - * - * @param User $user User that create - * @return int <0 if KO, >0 if OK - */ - public function create($user) - { - global $conf, $langs; + /** + * Create in database + * + * @param User $user User that create + * @return int <0 if KO, >0 if OK + */ + public function create($user) + { + global $conf, $langs; $error = 0; $now = dol_now(); @@ -135,7 +135,7 @@ class Tva extends CommonObject $sql .= "fk_typepayment,"; $sql .= "fk_user_creat,"; $sql .= "fk_user_modif"; - $sql .= ") VALUES ("; + $sql .= ") VALUES ("; $sql .= " '".$this->db->idate($now)."',"; $sql .= " '".$this->db->idate($this->datep)."',"; $sql .= " '".$this->db->idate($this->datev)."',"; @@ -148,44 +148,42 @@ class Tva extends CommonObject $sql .= " '".$this->db->escape($this->fk_user_modif)."'"; $sql .= ")"; - dol_syslog(get_class($this)."::create", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); + dol_syslog(get_class($this)."::create", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); - // Call trigger - $result = $this->call_trigger('TVA_CREATE', $user); - if ($result < 0) $error++; - // End call triggers + // Call trigger + $result = $this->call_trigger('TVA_CREATE', $user); + if ($result < 0) { + $error++; + } + // End call triggers - if (!$error) - { - $this->db->commit(); - return $this->id; - } - else { + if (!$error) { + $this->db->commit(); + return $this->id; + } else { $this->db->rollback(); return -1; - } - } - else { + } + } else { $this->error = "Error ".$this->db->lasterror(); $this->db->rollback(); return -1; - } - } + } + } - /** - * Update database - * - * @param User $user User that modify - * @param int $notrigger 0=no, 1=yes (no update trigger) - * @return int <0 if KO, >0 if OK - */ - public function update($user, $notrigger = 0) - { - global $conf, $langs; + /** + * Update database + * + * @param User $user User that modify + * @param int $notrigger 0=no, 1=yes (no update trigger) + * @return int <0 if KO, >0 if OK + */ + public function update($user, $notrigger = 0) + { + global $conf, $langs; $error = 0; @@ -202,7 +200,7 @@ class Tva extends CommonObject $this->db->begin(); // Update request - $sql = "UPDATE ".MAIN_DB_PREFIX."tva SET"; + $sql = "UPDATE ".MAIN_DB_PREFIX."tva SET"; $sql .= " tms='".$this->db->idate($this->tms)."',"; $sql .= " datep='".$this->db->idate($this->datep)."',"; $sql .= " datev='".$this->db->idate($this->datev)."',"; @@ -211,34 +209,32 @@ class Tva extends CommonObject $sql .= " note='".$this->db->escape($this->note)."',"; $sql .= " fk_user_creat=".$this->fk_user_creat.","; $sql .= " fk_user_modif=".($this->fk_user_modif > 0 ? $this->fk_user_modif : $user->id).""; - $sql .= " WHERE rowid=".$this->id; + $sql .= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::update", LOG_DEBUG); - $resql = $this->db->query($sql); - if (!$resql) - { - $this->error = "Error ".$this->db->lasterror(); - $error++; - } + dol_syslog(get_class($this)."::update", LOG_DEBUG); + $resql = $this->db->query($sql); + if (!$resql) { + $this->error = "Error ".$this->db->lasterror(); + $error++; + } - if (!$error && !$notrigger) - { - // Call trigger - $result = $this->call_trigger('TVA_MODIFY', $user); - if ($result < 0) $error++; - // End call triggers - } + if (!$error && !$notrigger) { + // Call trigger + $result = $this->call_trigger('TVA_MODIFY', $user); + if ($result < 0) { + $error++; + } + // End call triggers + } - if (!$error) - { - $this->db->commit(); - return 1; - } - else { - $this->db->rollback(); - return -1; - } - } + if (!$error) { + $this->db->commit(); + return 1; + } else { + $this->db->rollback(); + return -1; + } + } /** * Tag TVA as payed completely @@ -253,8 +249,11 @@ class Tva extends CommonObject $sql .= " paye = 1"; $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) return 1; - else return -1; + if ($resql) { + return 1; + } else { + return -1; + } } /** @@ -270,22 +269,25 @@ class Tva extends CommonObject $sql .= " paye = 0"; $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) return 1; - else return -1; + if ($resql) { + return 1; + } else { + return -1; + } } - /** - * Load object in memory from database - * - * @param int $id id object - * @param User $user User that load - * @return int <0 if KO, >0 if OK - */ - public function fetch($id, $user = null) - { - global $langs; - $sql = "SELECT"; + /** + * Load object in memory from database + * + * @param int $id id object + * @param User $user User that load + * @return int <0 if KO, >0 if OK + */ + public function fetch($id, $user = null) + { + global $langs; + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.tms,"; @@ -301,20 +303,18 @@ class Tva extends CommonObject $sql .= " t.fk_user_modif,"; $sql .= " t.fk_account"; - $sql .= " FROM ".MAIN_DB_PREFIX."tva as t"; + $sql .= " FROM ".MAIN_DB_PREFIX."tva as t"; //$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON t.fk_bank = b.rowid"; - $sql .= " WHERE t.rowid = ".$id; + $sql .= " WHERE t.rowid = ".$id; - dol_syslog(get_class($this)."::fetch", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { - $obj = $this->db->fetch_object($resql); + dol_syslog(get_class($this)."::fetch", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + if ($this->db->num_rows($resql)) { + $obj = $this->db->fetch_object($resql); - $this->id = $obj->rowid; - $this->ref = $obj->rowid; + $this->id = $obj->rowid; + $this->ref = $obj->rowid; $this->tms = $this->db->jdate($obj->tms); $this->datep = $this->db->jdate($obj->datep); $this->datev = $this->db->jdate($obj->datev); @@ -329,22 +329,21 @@ class Tva extends CommonObject $this->fk_account = $obj->fk_account; $this->fk_type = $obj->fk_type; $this->rappro = $obj->rappro; - } - $this->db->free($resql); + } + $this->db->free($resql); - return 1; - } - else { - $this->error = "Error ".$this->db->lasterror(); - return -1; - } - } + return 1; + } else { + $this->error = "Error ".$this->db->lasterror(); + return -1; + } + } - /** + /** * Delete object in database * - * @param User $user User that delete + * @param User $user User that delete * @return int <0 if KO, >0 if OK */ public function delete($user) @@ -355,16 +354,17 @@ class Tva extends CommonObject // Call trigger $result = $this->call_trigger('TVA_DELETE', $user); - if ($result < 0) return -1; + if ($result < 0) { + return -1; + } // End call triggers $sql = "DELETE FROM ".MAIN_DB_PREFIX."tva"; $sql .= " WHERE rowid=".$this->id; - dol_syslog(get_class($this)."::delete", LOG_DEBUG); + dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = "Error ".$this->db->lasterror(); return -1; } @@ -375,11 +375,11 @@ class Tva extends CommonObject /** - * Initialise an instance with random values. - * Used to build previews or test instances. - * id must be 0 if object instance is a specimen. - * - * @return void + * Initialise an instance with random values. + * Used to build previews or test instances. + * id must be 0 if object instance is a specimen. + * + * @return void */ public function initAsSpecimen() { @@ -397,244 +397,233 @@ class Tva extends CommonObject } - /** - * Balance of VAT - * - * @param int $year Year - * @return double Amount - */ - public function solde($year = 0) - { + /** + * Balance of VAT + * + * @param int $year Year + * @return double Amount + */ + public function solde($year = 0) + { - $reglee = $this->tva_sum_reglee($year); + $reglee = $this->tva_sum_reglee($year); - $payee = $this->tva_sum_payee($year); - $collectee = $this->tva_sum_collectee($year); + $payee = $this->tva_sum_payee($year); + $collectee = $this->tva_sum_collectee($year); - $solde = $reglee - ($collectee - $payee); + $solde = $reglee - ($collectee - $payee); - return $solde; - } + return $solde; + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Total of the VAT from invoices emitted by the thirdparty. - * - * @param int $year Year - * @return double Amount - */ - public function tva_sum_collectee($year = 0) - { + /** + * Total of the VAT from invoices emitted by the thirdparty. + * + * @param int $year Year + * @return double Amount + */ + public function tva_sum_collectee($year = 0) + { // phpcs:enable - $sql = "SELECT sum(f.tva) as amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."facture as f WHERE f.paye = 1"; - if ($year) - { + $sql = "SELECT sum(f.tva) as amount"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture as f WHERE f.paye = 1"; + if ($year) { $sql .= " AND f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; - } + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); $ret = $obj->amount; - $this->db->free($result); - return $ret; - } - else { - $this->db->free($result); + $this->db->free($result); + return $ret; + } else { + $this->db->free($result); return 0; - } - } - else { - print $this->db->lasterror(); - return -1; - } - } + } + } else { + print $this->db->lasterror(); + return -1; + } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * VAT payed - * - * @param int $year Year - * @return double Amount - */ - public function tva_sum_payee($year = 0) - { + /** + * VAT payed + * + * @param int $year Year + * @return double Amount + */ + public function tva_sum_payee($year = 0) + { // phpcs:enable - $sql = "SELECT sum(f.total_tva) as total_tva"; - $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; - if ($year) - { - $sql .= " WHERE f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; - } + $sql = "SELECT sum(f.total_tva) as total_tva"; + $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; + if ($year) { + $sql .= " WHERE f.datef >= '".$this->db->escape($year)."-01-01' AND f.datef <= '".$this->db->escape($year)."-12-31' "; + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $ret = $obj->total_tva; - $this->db->free($result); - return $ret; - } - else { - $this->db->free($result); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $ret = $obj->total_tva; + $this->db->free($result); + return $ret; + } else { + $this->db->free($result); return 0; - } - } - else { - print $this->db->lasterror(); - return -1; - } - } + } + } else { + print $this->db->lasterror(); + return -1; + } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** - * Total of the VAT payed - * - * @param int $year Year - * @return double Amount - */ - public function tva_sum_reglee($year = 0) - { + /** + * Total of the VAT payed + * + * @param int $year Year + * @return double Amount + */ + public function tva_sum_reglee($year = 0) + { // phpcs:enable - $sql = "SELECT sum(f.amount) as amount"; - $sql .= " FROM ".MAIN_DB_PREFIX."tva as f"; + $sql = "SELECT sum(f.amount) as amount"; + $sql .= " FROM ".MAIN_DB_PREFIX."tva as f"; - if ($year) - { + if ($year) { $sql .= " WHERE f.datev >= '".$this->db->escape($year)."-01-01' AND f.datev <= '".$this->db->escape($year)."-12-31' "; - } + } - $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { - $obj = $this->db->fetch_object($result); - $ret = $obj->amount; - $this->db->free($result); - return $ret; - } - else { - $this->db->free($result); + $result = $this->db->query($sql); + if ($result) { + if ($this->db->num_rows($result)) { + $obj = $this->db->fetch_object($result); + $ret = $obj->amount; + $this->db->free($result); + return $ret; + } else { + $this->db->free($result); return 0; - } - } - else { - print $this->db->lasterror(); - return -1; - } - } + } + } else { + print $this->db->lasterror(); + return -1; + } + } - /** - * Create in database - * + /** + * Create in database + * * @param User $user Object user that insert * @return int <0 if KO, rowid in tva table if OK - */ - public function addPayment($user) - { - global $conf, $langs; + */ + public function addPayment($user) + { + global $conf, $langs; - $this->db->begin(); + $this->db->begin(); - // Clean parameters - $this->amount = price2num(trim($this->amount)); - $this->label = trim($this->label); + // Clean parameters + $this->amount = price2num(trim($this->amount)); + $this->label = trim($this->label); $this->note = trim($this->note); $this->num_payment = trim($this->num_payment); $this->fk_bank = (int) $this->fk_bank; $this->fk_user_creat = (int) $this->fk_user_creat; $this->fk_user_modif = (int) $this->fk_user_modif; - if (empty($this->datec)) $this->datec = dol_now(); + if (empty($this->datec)) { + $this->datec = dol_now(); + } - // Check parameters - if (!$this->label) - { + // Check parameters + if (!$this->label) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Label")); return -3; } - if ($this->amount == '') - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); - return -4; - } - if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); - return -5; - } - if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) - { - $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); - return -5; - } + if ($this->amount == '') { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Amount")); + return -4; + } + if (!empty($conf->banque->enabled) && (empty($this->accountid) || $this->accountid <= 0)) { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Account")); + return -5; + } + if (!empty($conf->banque->enabled) && (empty($this->type_payment) || $this->type_payment <= 0)) { + $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")); + return -5; + } - // Insert into llx_tva - $sql = "INSERT INTO ".MAIN_DB_PREFIX."tva ("; - $sql .= "datec"; - $sql .= ", datep"; - $sql .= ", datev"; + // Insert into llx_tva + $sql = "INSERT INTO ".MAIN_DB_PREFIX."tva ("; + $sql .= "datec"; + $sql .= ", datep"; + $sql .= ", datev"; $sql .= ", amount"; $sql .= ", fk_typepayment"; $sql .= ", num_payment"; - if ($this->note) $sql .= ", note"; - if ($this->label) $sql .= ", label"; - $sql .= ", fk_user_creat"; + if ($this->note) { + $sql .= ", note"; + } + if ($this->label) { + $sql .= ", label"; + } + $sql .= ", fk_user_creat"; $sql .= ", fk_bank"; $sql .= ", entity"; $sql .= ") "; - $sql .= " VALUES ("; - $sql .= " '".$this->db->idate($this->datec)."'"; - $sql .= ", '".$this->db->idate($this->datep)."'"; - $sql .= ", '".$this->db->idate($this->datev)."'"; + $sql .= " VALUES ("; + $sql .= " '".$this->db->idate($this->datec)."'"; + $sql .= ", '".$this->db->idate($this->datep)."'"; + $sql .= ", '".$this->db->idate($this->datev)."'"; $sql .= ", ".$this->amount; - $sql .= ", '".$this->db->escape($this->type_payment)."'"; + $sql .= ", '".$this->db->escape($this->type_payment)."'"; $sql .= ", '".$this->db->escape($this->num_payment)."'"; - if ($this->note) $sql .= ", '".$this->db->escape($this->note)."'"; - if ($this->label) $sql .= ", '".$this->db->escape($this->label)."'"; - $sql .= ", '".$this->db->escape($user->id)."'"; + if ($this->note) { + $sql .= ", '".$this->db->escape($this->note)."'"; + } + if ($this->label) { + $sql .= ", '".$this->db->escape($this->label)."'"; + } + $sql .= ", '".$this->db->escape($user->id)."'"; $sql .= ", NULL"; $sql .= ", ".$conf->entity; - $sql .= ")"; + $sql .= ")"; dol_syslog(get_class($this)."::addPayment", LOG_DEBUG); - $result = $this->db->query($sql); - if ($result) - { - $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); // TODO should be called 'payment_vat' + $result = $this->db->query($sql); + if ($result) { + $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."tva"); // TODO should be called 'payment_vat' - // Call trigger - //XXX: Should be done just befor commit no ? - $result = $this->call_trigger('TVA_ADDPAYMENT', $user); - if ($result < 0) - { - $this->id = 0; - $ok = 0; - } - // End call triggers + // Call trigger + //XXX: Should be done just befor commit no ? + $result = $this->call_trigger('TVA_ADDPAYMENT', $user); + if ($result < 0) { + $this->id = 0; + $ok = 0; + } + // End call triggers - if ($this->id > 0) - { - $ok = 1; - if (!empty($conf->banque->enabled) && !empty($this->amount)) - { - // Insert into llx_bank - require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; + if ($this->id > 0) { + $ok = 1; + if (!empty($conf->banque->enabled) && !empty($this->amount)) { + // Insert into llx_bank + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; - $acc = new Account($this->db); + $acc = new Account($this->db); $result = $acc->fetch($this->accountid); - if ($result <= 0) dol_print_error($this->db); + if ($result <= 0) { + dol_print_error($this->db); + } if ($this->amount > 0) { $bank_line_id = $acc->addline($this->datep, $this->type_payment, $this->label, -abs($this->amount), $this->num_payment, '', $user); @@ -642,65 +631,56 @@ class Tva extends CommonObject $bank_line_id = $acc->addline($this->datep, $this->type_payment, $this->label, abs($this->amount), $this->num_payment, '', $user); } - // Update fk_bank into llx_tva. So we know vat line used to generate bank transaction - if ($bank_line_id > 0) - { - $this->update_fk_bank($bank_line_id); - } - else { + // Update fk_bank into llx_tva. So we know vat line used to generate bank transaction + if ($bank_line_id > 0) { + $this->update_fk_bank($bank_line_id); + } else { $this->error = $acc->error; $ok = 0; } - // Update links - $result = $acc->add_url_line($bank_line_id, $this->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', "(VATPayment)", "payment_vat"); - if ($result < 0) - { - $this->error = $acc->error; - $ok = 0; - } - } + // Update links + $result = $acc->add_url_line($bank_line_id, $this->id, DOL_URL_ROOT.'/compta/tva/card.php?id=', "(VATPayment)", "payment_vat"); + if ($result < 0) { + $this->error = $acc->error; + $ok = 0; + } + } - if ($ok) - { + if ($ok) { $this->db->commit(); return $this->id; - } - else { + } else { $this->db->rollback(); return -3; } - } - else { - $this->db->rollback(); - return -2; - } - } - else { - $this->error = $this->db->error(); - $this->db->rollback(); - return -1; - } - } + } else { + $this->db->rollback(); + return -2; + } + } else { + $this->error = $this->db->error(); + $this->db->rollback(); + return -1; + } + } // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps - /** + /** * Update link between payment tva and line generate into llx_bank - * - * @param int $id_bank Id bank account + * + * @param int $id_bank Id bank account * @return int <0 if KO, >0 if OK - */ + */ public function update_fk_bank($id_bank) { // phpcs:enable $sql = 'UPDATE '.MAIN_DB_PREFIX.'tva SET fk_bank = '.(int) $id_bank; $sql .= ' WHERE rowid = '.(int) $this->id; $result = $this->db->query($sql); - if ($result) - { + if ($result) { return 1; - } - else { + } else { dol_print_error($this->db); return -1; } @@ -711,8 +691,8 @@ class Tva extends CommonObject * * @param int $withpicto 0=No picto, 1=Include picto into link, 2=Only picto * @param string $option link option - * @param int $notooltip 1=Disable tooltip - * @param string $morecss More CSS + * @param int $notooltip 1=Disable tooltip + * @param string $morecss More CSS * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking * @return string Chaine with URL */ @@ -720,83 +700,92 @@ class Tva extends CommonObject { global $langs, $conf; - if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips + if (!empty($conf->dol_no_mouse_hover)) { + $notooltip = 1; // Force disable tooltips + } $result = ''; $label = ''.$langs->trans("ShowVatPayment").''; $label .= '
'; $label .= ''.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->label)) + if (!empty($this->label)) { $label .= '
'.$langs->trans('Label').': '.$this->label; + } - $url = DOL_URL_ROOT.'/compta/tva/card.php?id='.$this->id; + $url = DOL_URL_ROOT.'/compta/tva/card.php?id='.$this->id; - if ($option != 'nolink') - { - // Add param to save lastsearch_values or not - $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; - } + if ($option != 'nolink') { + // Add param to save lastsearch_values or not + $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } + } - $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { - $label = $langs->trans("ShowMyObject"); - $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; - } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; - } - else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + $linkclose = ''; + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $label = $langs->trans("ShowMyObject"); + $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; + } + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); + } - $linkstart = ''; - $linkend = ''; + $linkstart = ''; + $linkend = ''; $picto = 'payment'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; return $result; } /** - * Return amount of payments already done - * - * @return int Amount of payment already done, <0 if KO - */ - public function getSommePaiement() - { - $table = 'payment_vat'; - $field = 'fk_tva'; + * Return amount of payments already done + * + * @return int Amount of payment already done, <0 if KO + */ + public function getSommePaiement() + { + $table = 'payment_vat'; + $field = 'fk_tva'; - $sql = 'SELECT sum(amount) as amount'; - $sql .= ' FROM '.MAIN_DB_PREFIX.$table; - $sql .= ' WHERE '.$field.' = '.$this->id; + $sql = 'SELECT sum(amount) as amount'; + $sql .= ' FROM '.MAIN_DB_PREFIX.$table; + $sql .= ' WHERE '.$field.' = '.$this->id; - dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); - $resql = $this->db->query($sql); - if ($resql) - { - $amount = 0; + dol_syslog(get_class($this)."::getSommePaiement", LOG_DEBUG); + $resql = $this->db->query($sql); + if ($resql) { + $amount = 0; - $obj = $this->db->fetch_object($resql); - if ($obj) $amount = $obj->amount ? $obj->amount : 0; + $obj = $this->db->fetch_object($resql); + if ($obj) { + $amount = $obj->amount ? $obj->amount : 0; + } - $this->db->free($resql); - return $amount; - } - else { - return -1; - } - } + $this->db->free($resql); + return $amount; + } else { + return -1; + } + } /** * Informations of vat payment object @@ -812,10 +801,8 @@ class Tva extends CommonObject dol_syslog(get_class($this)."::info", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -838,8 +825,7 @@ class Tva extends CommonObject } $this->db->free($result); - } - else { + } else { dol_print_error($this->db); } } @@ -877,21 +863,28 @@ class Tva extends CommonObject $this->labelStatus = array(); $this->labelStatusShort = array(); - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_UNPAID] = $langs->trans('BillStatusNotPaid'); $this->labelStatus[self::STATUS_PAID] = $langs->trans('BillStatusPaid'); - if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) { + $this->labelStatus[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + } $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans('BillStatusNotPaid'); $this->labelStatusShort[self::STATUS_PAID] = $langs->trans('BillStatusPaid'); - if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) { + $this->labelStatusShort[self::STATUS_UNPAID] = $langs->trans("BillStatusStarted"); + } } $statusType = 'status1'; - if ($status == 0 && $alreadypaid <> 0) $statusType = 'status3'; - if ($status == 1) $statusType = 'status6'; + if ($status == 0 && $alreadypaid <> 0) { + $statusType = 'status3'; + } + if ($status == 1) { + $statusType = 'status6'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } diff --git a/htdocs/compta/tva/clients.php b/htdocs/compta/tva/clients.php index d4acecf063d..e0801ba1db2 100644 --- a/htdocs/compta/tva/clients.php +++ b/htdocs/compta/tva/clients.php @@ -46,12 +46,13 @@ $langs->loadLangs(array("other", "compta", "banks", "bills", "companies", "produ $now = dol_now(); $current_date = dol_getdate($now); -if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) $conf->global->SOCIETE_FISCAL_MONTH_START = 1; +if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) { + $conf->global->SOCIETE_FISCAL_MONTH_START = 1; +} // Date range $year = GETPOST("year", "int"); -if (empty($year)) -{ +if (empty($year)) { $year_current = $current_date['year']; $year_start = $year_current; } else { @@ -61,12 +62,12 @@ if (empty($year)) $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); // Set default period if not defined -if (empty($date_start) || empty($date_end)) // We define date_start and date_end -{ +if (empty($date_start) || empty($date_end)) { // We define date_start and date_end $q = GETPOST("q", "int"); - if (empty($q)) - { - if (GETPOST("month", 'int')) { $date_start = dol_get_first_day($year_start, GETPOST("month", 'int'), false); $date_end = dol_get_last_day($year_start, GETPOST("month", 'int'), false); } else { + if (empty($q)) { + if (GETPOST("month", 'int')) { + $date_start = dol_get_first_day($year_start, GETPOST("month", 'int'), false); $date_end = dol_get_last_day($year_start, GETPOST("month", 'int'), false); + } else { if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { // quaterly vat, we take last past complete quarter $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -3 - (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) % 3), 'm'); $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; @@ -88,25 +89,41 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end } } } else { - if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); } - if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); } - if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); } - if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); } + if ($q == 1) { + $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + } + if ($q == 2) { + $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + } + if ($q == 3) { + $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + } + if ($q == 4) { + $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + } } } $min = price2num(GETPOST("min", "alpha")); -if (empty($min)) $min = 0; +if (empty($min)) { + $min = 0; +} // Define modetax (0 or 1) // 0=normal, 1=option vat for services is on debit, 2=option on payments for products $modetax = $conf->global->TAX_MODE; -if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int'); -if (empty($modetax)) $modetax = 0; +if (GETPOSTISSET("modetax")) { + $modetax = GETPOST("modetax", 'int'); +} +if (empty($modetax)) { + $modetax = 0; +} // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); @@ -128,9 +145,10 @@ $user_static = new User($db); $morequerystring = ''; $listofparams = array('date_startmonth', 'date_startyear', 'date_startday', 'date_endmonth', 'date_endyear', 'date_endday'); -foreach ($listofparams as $param) -{ - if (GETPOST($param) != '') $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); +foreach ($listofparams as $param) { + if (GETPOST($param) != '') { + $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); + } } $special_report = false; @@ -149,9 +167,15 @@ $fsearch .= ''; // Show report header $name = $langs->trans("VATReportByThirdParties"); $calcmode = ''; -if ($modetax == 0) $calcmode = $langs->trans('OptionVATDefault'); -if ($modetax == 1) $calcmode = $langs->trans('OptionVATDebitOption'); -if ($modetax == 2) $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +if ($modetax == 0) { + $calcmode = $langs->trans('OptionVATDefault'); +} +if ($modetax == 1) { + $calcmode = $langs->trans('OptionVATDebitOption'); +} +if ($modetax == 2) { + $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +} $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRules", DOL_URL_ROOT.'/admin/taxes.php').')'; // Set period $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); @@ -173,19 +197,28 @@ if ($nextquarter < 4) { } $builddate = dol_now(); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description .= $langs->trans("RulesVATDueProducts"); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description .= $langs->trans("RulesVATInProducts"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description .= '
'.$langs->trans("RulesVATDueServices"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description .= '
'.$langs->trans("RulesVATInServices"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') { + $description .= $langs->trans("RulesVATDueProducts"); +} +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') { + $description .= $langs->trans("RulesVATInProducts"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') { + $description .= '
'.$langs->trans("RulesVATDueServices"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + $description .= '
'.$langs->trans("RulesVATInServices"); +} if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $description .= '
'.$langs->trans("DepositsAreNotIncluded"); } -if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description .= '
'.$langs->trans("ThisIsAnEstimatedValue"); +if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) { + $description .= '
'.$langs->trans("ThisIsAnEstimatedValue"); +} //$periodlink=($year_start?"".img_previous()." ".img_next()."":""); $description .= ($description ? '
' : '').$fsearch; -if (!empty($conf->global->TAX_REPORT_EXTRA_REPORT)) -{ +if (!empty($conf->global->TAX_REPORT_EXTRA_REPORT)) { $description .= '
'; $description .= ' '; $description .= $langs->trans('SimpleReport'); @@ -229,8 +262,7 @@ $columns = 5; $x_coll = tax_by_thirdparty('vat', $db, 0, $date_start, $date_end, $modetax, 'sell'); $x_paye = tax_by_thirdparty('vat', $db, 0, $date_start, $date_end, $modetax, 'buy'); -if (!is_array($x_coll) || !is_array($x_paye)) -{ +if (!is_array($x_coll) || !is_array($x_paye)) { $langs->load("errors"); if ($x_coll == -1) { print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").''; @@ -242,15 +274,14 @@ if (!is_array($x_coll) || !is_array($x_paye)) } else { $x_both = array(); //now, from these two arrays, get another array with one rate per line - foreach (array_keys($x_coll) as $my_coll_thirdpartyid) - { + foreach (array_keys($x_coll) as $my_coll_thirdpartyid) { $x_both[$my_coll_thirdpartyid]['coll']['totalht'] = $x_coll[$my_coll_thirdpartyid]['totalht']; $x_both[$my_coll_thirdpartyid]['coll']['vat'] = $x_coll[$my_coll_thirdpartyid]['vat']; $x_both[$my_coll_thirdpartyid]['paye']['totalht'] = 0; $x_both[$my_coll_thirdpartyid]['paye']['vat'] = 0; $x_both[$my_coll_thirdpartyid]['coll']['links'] = ''; $x_both[$my_coll_thirdpartyid]['coll']['detail'] = array(); - foreach ($x_coll[$my_coll_thirdpartyid]['facid'] as $id=>$dummy) { + foreach ($x_coll[$my_coll_thirdpartyid]['facid'] as $id => $dummy) { $invoice_customer->id = $x_coll[$my_coll_thirdpartyid]['facid'][$id]; $invoice_customer->ref = $x_coll[$my_coll_thirdpartyid]['facnum'][$id]; $invoice_customer->type = $x_coll[$my_coll_thirdpartyid]['type'][$id]; @@ -289,11 +320,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_both[$my_paye_thirdpartyid]['paye']['links'] = ''; $x_both[$my_paye_thirdpartyid]['paye']['detail'] = array(); - foreach ($x_paye[$my_paye_thirdpartyid]['facid'] as $id=>$dummy) - { + foreach ($x_paye[$my_paye_thirdpartyid]['facid'] as $id => $dummy) { // ExpenseReport - if ($x_paye[$my_paye_thirdpartyid]['ptype'][$id] == 'ExpenseReportPayment') - { + if ($x_paye[$my_paye_thirdpartyid]['ptype'][$id] == 'ExpenseReportPayment') { $expensereport->id = $x_paye[$my_paye_thirdpartyid]['facid'][$id]; $expensereport->ref = $x_paye[$my_paye_thirdpartyid]['facnum'][$id]; $expensereport->type = $x_paye[$my_paye_thirdpartyid]['type'][$id]; @@ -356,7 +385,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_paye_ht = 0; $span = $columns; - if ($modetax != 1) $span += 2; + if ($modetax != 1) { + $span += 2; + } //print ''..')'; @@ -364,12 +395,14 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''.$elementcust.''; print ''.$langs->trans("DateInvoice").''; - if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''.$langs->trans("DatePayment").''; - else print ''; + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + print ''.$langs->trans("DatePayment").''; + } else { + print ''; + } print ''.$namerate.''; print ''.$productcust.''; - if ($modetax != 1) - { + if ($modetax != 1) { print ''.$amountcust.''; print ''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'; } @@ -392,10 +425,8 @@ if (!is_array($x_coll) || !is_array($x_paye)) $subtot_coll_total_ht = 0; $subtot_coll_vat = 0; - if ($min == 0 || ($min > 0 && $x_both[$thirdparty_id]['coll']['totalht'] > $min)) - { - if (is_array($x_both[$thirdparty_id]['coll']['detail'])) - { + if ($min == 0 || ($min > 0 && $x_both[$thirdparty_id]['coll']['totalht'] > $min)) { + if (is_array($x_both[$thirdparty_id]['coll']['detail'])) { // VAT Rate print ""; print ''; @@ -542,8 +573,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) } } - if (count($x_coll) == 0) // Show a total ine if nothing shown - { + if (count($x_coll) == 0) { // Show a total ine if nothing shown print ''; print ''; print ''.$langs->trans("Total").':'; @@ -563,8 +593,11 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''.$elementsup.''; print ''.$langs->trans("DateInvoice").''; - if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''.$langs->trans("DatePayment").''; - else print ''; + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') { + print ''.$langs->trans("DatePayment").''; + } else { + print ''; + } print ''.$namesup.''; print ''.$productsup.''; if ($modetax != 1) { @@ -575,8 +608,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''.$vatsup.''; print ''."\n"; - foreach (array_keys($x_paye) as $thirdparty_id) - { + foreach (array_keys($x_paye) as $thirdparty_id) { $subtot_paye_total_ht = 0; $subtot_paye_vat = 0; @@ -673,18 +705,15 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Payment $ratiopaymentinvoice = 1; - if ($modetax != 1) - { + if ($modetax != 1) { print ''; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) - { + if ($fields['payment_amount'] && $fields['ftotal_ttc']) { $paymentfourn_static->id = $fields['payment_id']; print $paymentfourn_static->getNomUrl(2); } if (($type == 0 && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) - { + || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { print $langs->trans("NA"); } else { if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { diff --git a/htdocs/compta/tva/document.php b/htdocs/compta/tva/document.php index addaf50d990..38d88fb3d12 100644 --- a/htdocs/compta/tva/document.php +++ b/htdocs/compta/tva/document.php @@ -34,8 +34,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/vat.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } @@ -48,7 +47,9 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', 'vat', 'charges'); @@ -63,12 +64,18 @@ if (empty($page) || $page == -1) { $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} $object = new Tva($db); -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} $upload_dir = $conf->tax->dir_output.'/vat/'.dol_sanitizeFileName($object->ref); $modulepart = 'tax-vat'; @@ -80,12 +87,12 @@ $modulepart = 'tax-vat'; include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; -if ($action == 'setlib' && $user->rights->tax->charges->creer) -{ +if ($action == 'setlib' && $user->rights->tax->charges->creer) { $object->fetch($id); $result = $object->setValueFrom('label', GETPOST('lib', 'alpha'), '', '', 'text', '', $user, 'TAX_MODIFY'); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } @@ -94,14 +101,15 @@ if ($action == 'setlib' && $user->rights->tax->charges->creer) */ $form = new Form($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $title = $langs->trans("VATPayment").' - '.$langs->trans("Documents"); $help_url = 'EN:Module_Taxes_and_social_contributions|FR:Module Taxes et dividendes|ES:Módulo Impuestos y cargas sociales (IVA, impuestos)'; llxHeader("", $title, $help_url); -if ($object->id) -{ +if ($object->id) { $alreadypayed = $object->getSommePaiement(); $head = vat_prepare_head($object); @@ -126,8 +134,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/compta/tva/index.php b/htdocs/compta/tva/index.php index 081023cd2e8..76eed6b1bf8 100644 --- a/htdocs/compta/tva/index.php +++ b/htdocs/compta/tva/index.php @@ -39,12 +39,13 @@ $langs->loadLangs(array("other", "compta", "banks", "bills", "companies", "produ $form = new Form($db); $now = dol_now(); $current_date = dol_getdate($now); -if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) $conf->global->SOCIETE_FISCAL_MONTH_START = 1; +if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) { + $conf->global->SOCIETE_FISCAL_MONTH_START = 1; +} // Date range $year = GETPOST("year", "int"); -if (empty($year)) -{ +if (empty($year)) { $year_current = $current_date['year']; $year_start = $year_current; } else { @@ -54,18 +55,16 @@ if (empty($year)) $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); // Set default period if not defined -if (empty($date_start) || empty($date_end)) // We define date_start and date_end -{ +if (empty($date_start) || empty($date_end)) { // We define date_start and date_end $q = GETPOST("q", "int"); - if (empty($q)) - { - if (GETPOST("month", "int")) { $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } - else { + if (empty($q)) { + if (GETPOST("month", "int")) { + $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); + } else { if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { // quaterly vat, we take last past complete quarter $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -3 - (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) % 3), 'm'); $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; - } - elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { // yearly vat + } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 3) { // yearly vat if ($current_date['mon'] < $conf->global->SOCIETE_FISCAL_MONTH_START) { if (($conf->global->SOCIETE_FISCAL_MONTH_START - $current_date['mon']) > 6) { // If period started from less than 6 years, we show past year $year_start--; @@ -77,30 +76,42 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end } $date_start = dol_get_first_day($year_start, $conf->global->SOCIETE_FISCAL_MONTH_START, false); $date_end = dol_time_plus_duree($date_start, 1, 'y') - 1; - } - elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) { // monthly vat, we take last past complete month + } elseif ($conf->global->MAIN_INFO_VAT_RETURN == 1) { // monthly vat, we take last past complete month $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -1, 'm'); $date_end = dol_time_plus_duree($date_start, 1, 'm') - 1; } } - } - else { - if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); } - if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); } - if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); } - if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); } + } else { + if ($q == 1) { + $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + } + if ($q == 2) { + $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + } + if ($q == 3) { + $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + } + if ($q == 4) { + $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + } } } // Define modetax (0 or 1) // 0=normal, 1=option vat for services is on debit, 2=option on payments for products $modetax = $conf->global->TAX_MODE; -if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int'); -if (empty($modetax)) $modetax = 0; +if (GETPOSTISSET("modetax")) { + $modetax = GETPOST("modetax", 'int'); +} +if (empty($modetax)) { + $modetax = 0; +} // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); @@ -114,102 +125,95 @@ $result = restrictedArea($user, 'tax', '', '', 'charges'); */ function pt($db, $sql, $date) { - global $conf, $bc, $langs, $form; + global $conf, $bc, $langs, $form; - $result = $db->query($sql); - if ($result) { - $num = $db->num_rows($result); - $i = 0; - $total = 0; - print ''; + $result = $db->query($sql); + if ($result) { + $num = $db->num_rows($result); + $i = 0; + $total = 0; + print '
'; - print ''; - print ''; - print ''; - print ''; - print "\n"; + print ''; + print ''; + print ''; + print ''; + print "\n"; - $totalclaimed = 0; - $totalpaid = 0; - $amountclaimed = 0; - $amountpaid = 0; - $previousmonth = ''; - $previousmode = ''; - $mode = ''; + $totalclaimed = 0; + $totalpaid = 0; + $amountclaimed = 0; + $amountpaid = 0; + $previousmonth = ''; + $previousmode = ''; + $mode = ''; - while ($i < $num) { - $obj = $db->fetch_object($result); - $mode = $obj->mode; + while ($i < $num) { + $obj = $db->fetch_object($result); + $mode = $obj->mode; - //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode; - if ($obj->mode == 'claimed' && !empty($previousmode)) - { - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; + //print $obj->dm.' '.$obj->mode.' '.$previousmonth.' '.$previousmode; + if ($obj->mode == 'claimed' && !empty($previousmode)) { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; - $amountclaimed = 0; - $amountpaid = 0; - } + $amountclaimed = 0; + $amountpaid = 0; + } - if ($obj->mode == 'claimed') - { - $amountclaimed = $obj->mm; - $totalclaimed = $totalclaimed + $amountclaimed; - } - if ($obj->mode == 'paid') - { - $amountpaid = $obj->mm; - $totalpaid = $totalpaid + $amountpaid; - } + if ($obj->mode == 'claimed') { + $amountclaimed = $obj->mm; + $totalclaimed = $totalclaimed + $amountclaimed; + } + if ($obj->mode == 'paid') { + $amountpaid = $obj->mm; + $totalpaid = $totalpaid + $amountpaid; + } - if ($obj->mode == 'paid') - { - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; - $amountclaimed = 0; - $amountpaid = 0; - $previousmode = ''; - $previousmonth = ''; - } - else { - $previousmode = $obj->mode; - $previousmonth = $obj->dm; - } + if ($obj->mode == 'paid') { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; + $amountclaimed = 0; + $amountpaid = 0; + $previousmode = ''; + $previousmonth = ''; + } else { + $previousmode = $obj->mode; + $previousmonth = $obj->dm; + } - $i++; - } + $i++; + } - if ($mode == 'claimed' && !empty($previousmode)) - { - print ''; - print '\n"; - print '\n"; - print '\n"; - print "\n"; + if ($mode == 'claimed' && !empty($previousmode)) { + print ''; + print '\n"; + print '\n"; + print '\n"; + print "\n"; - $amountclaimed = 0; - $amountpaid = 0; - } + $amountclaimed = 0; + $amountpaid = 0; + } - print ''; - print ''; - print ''; - print ''; - print ""; + print ''; + print ''; + print ''; + print ''; + print ""; - print "
'.$date.''.$langs->trans("ClaimedForThisPeriod").''.$langs->trans("PaidDuringThisPeriod").$form->textwithpicto('', $langs->trans('PaidDuringThisPeriodDesc'), 1).'
'.$date.''.$langs->trans("ClaimedForThisPeriod").''.$langs->trans("PaidDuringThisPeriod").$form->textwithpicto('', $langs->trans('PaidDuringThisPeriodDesc'), 1).'
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$obj->dm."'.price($amountclaimed)."'.price($amountpaid)."
'.$obj->dm."'.price($amountclaimed)."'.price($amountpaid)."
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$previousmonth."'.price($amountclaimed)."'.price($amountpaid)."
'.$langs->trans("Total").''.price($totalclaimed).''.price($totalpaid).'
'.$langs->trans("Total").''.price($totalclaimed).''.price($totalpaid).'
"; + print ""; - $db->free($result); - } - else { - dol_print_error($db); - } + $db->free($result); + } else { + dol_print_error($db); + } } @@ -229,20 +233,36 @@ $description = $fsearch; // Show report header $name = $langs->trans("VATReportByMonth"); $calcmode = ''; -if ($modetax == 0) $calcmode = $langs->trans('OptionVATDefault'); -if ($modetax == 1) $calcmode = $langs->trans('OptionVATDebitOption'); -if ($modetax == 2) $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +if ($modetax == 0) { + $calcmode = $langs->trans('OptionVATDefault'); +} +if ($modetax == 1) { + $calcmode = $langs->trans('OptionVATDebitOption'); +} +if ($modetax == 2) { + $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +} $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRules", DOL_URL_ROOT.'/admin/taxes.php').')'; $description .= $langs->trans("VATSummary").'
'; -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description .= $langs->trans("RulesVATDueProducts"); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description .= $langs->trans("RulesVATInProducts"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description .= '
'.$langs->trans("RulesVATDueServices"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description .= '
'.$langs->trans("RulesVATInServices"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') { + $description .= $langs->trans("RulesVATDueProducts"); +} +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') { + $description .= $langs->trans("RulesVATInProducts"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') { + $description .= '
'.$langs->trans("RulesVATDueServices"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + $description .= '
'.$langs->trans("RulesVATInServices"); +} if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $description .= '
'.$langs->trans("DepositsAreNotIncluded"); } -if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description .= '
'.$langs->trans("ThisIsAnEstimatedValue"); +if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) { + $description .= '
'.$langs->trans("ThisIsAnEstimatedValue"); +} $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); @@ -284,11 +304,14 @@ $mend = $tmp['mon']; $total = 0; $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; $i = 0; $mcursor = 0; -while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mcursor is to avoid too large loop -{ +while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) { // $mcursor is to avoid too large loop //$m = $conf->global->SOCIETE_FISCAL_MONTH_START + ($mcursor % 12); - if ($m == 13) $y++; - if ($m > 12) $m -= 12; + if ($m == 13) { + $y++; + } + if ($m > 12) { + $m -= 12; + } $mcursor++; $x_coll = tax_by_rate('vat', $db, $y, 0, 0, 0, $modetax, 'sell', $m); @@ -296,15 +319,14 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc $x_both = array(); //now, from these two arrays, get another array with one rate per line - foreach (array_keys($x_coll) as $my_coll_rate) - { + foreach (array_keys($x_coll) as $my_coll_rate) { $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; $x_both[$my_coll_rate]['paye']['totalht'] = 0; $x_both[$my_coll_rate]['paye']['vat'] = 0; $x_both[$my_coll_rate]['coll']['links'] = ''; $x_both[$my_coll_rate]['coll']['detail'] = array(); - foreach ($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) { + foreach ($x_coll[$my_coll_rate]['facid'] as $id => $dummy) { //$invoice_customer->id=$x_coll[$my_coll_rate]['facid'][$id]; //$invoice_customer->ref=$x_coll[$my_coll_rate]['facnum'][$id]; //$invoice_customer->type=$x_coll[$my_coll_rate]['type'][$id]; @@ -343,11 +365,9 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc $x_both[$my_paye_rate]['paye']['links'] = ''; $x_both[$my_paye_rate]['paye']['detail'] = array(); - foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) - { + foreach ($x_paye[$my_paye_rate]['facid'] as $id => $dummy) { // ExpenseReport - if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') - { + if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') { //$expensereport->id=$x_paye[$my_paye_rate]['facid'][$id]; //$expensereport->ref=$x_paye[$my_paye_rate]['facnum'][$id]; //$expensereport->type=$x_paye[$my_paye_rate]['type'][$id]; @@ -369,8 +389,7 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc 'vat' =>$x_paye[$my_paye_rate]['vat_list'][$id], //'link' =>$expensereport->getNomUrl(1) ); - } - else { + } else { //$invoice_supplier->id=$x_paye[$my_paye_rate]['facid'][$id]; //$invoice_supplier->ref=$x_paye[$my_paye_rate]['facnum'][$id]; //$invoice_supplier->type=$x_paye[$my_paye_rate]['type'][$id]; @@ -400,144 +419,133 @@ while ((($y < $yend) || ($y == $yend && $m <= $mend)) && $mcursor < 1000) // $mc } //now we have an array (x_both) indexed by rates for coll and paye - $action = "tva"; - $object = array(&$x_coll, &$x_paye, &$x_both); - $parameters["mode"] = $modetax; - $parameters["year"] = $y; - $parameters["month"] = $m; - $parameters["type"] = 'vat'; + $action = "tva"; + $object = array(&$x_coll, &$x_paye, &$x_both); + $parameters["mode"] = $modetax; + $parameters["year"] = $y; + $parameters["month"] = $m; + $parameters["type"] = 'vat'; - // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array - $hookmanager->initHooks(array('externalbalance')); - $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks + // Initialize technical object to manage hooks of expenses. Note that conf->hooks_modules contains array array + $hookmanager->initHooks(array('externalbalance')); + $reshook = $hookmanager->executeHooks('addVatLine', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!is_array($x_coll) && $coll_listbuy == -1) - { - $langs->load("errors"); - print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").''; - break; - } - if (!is_array($x_paye) && $coll_listbuy == -2) - { - print ''.$langs->trans("FeatureNotYetAvailable").''; - break; - } + if (!is_array($x_coll) && $coll_listbuy == -1) { + $langs->load("errors"); + print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").''; + break; + } + if (!is_array($x_paye) && $coll_listbuy == -2) { + print ''.$langs->trans("FeatureNotYetAvailable").''; + break; + } - print ''; - print ''.dol_print_date(dol_mktime(0, 0, 0, $m, 1, $y), "%b %Y").''; + print ''; + print ''.dol_print_date(dol_mktime(0, 0, 0, $m, 1, $y), "%b %Y").''; - $x_coll_sum = 0; - foreach (array_keys($x_coll) as $rate) - { - $subtot_coll_total_ht = 0; - $subtot_coll_vat = 0; + $x_coll_sum = 0; + foreach (array_keys($x_coll) as $rate) { + $subtot_coll_total_ht = 0; + $subtot_coll_vat = 0; - foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) - { - // Payment - $ratiopaymentinvoice = 1; - if ($modetax != 1) - { - // Define type - // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. - $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (!empty($fields['ddate_start'])) { - $type = 1; - } - if (!empty($fields['ddate_end'])) { - $type = 1; - } + foreach ($x_both[$rate]['coll']['detail'] as $index => $fields) { + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } - if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) - { - //print $langs->trans("NA"); - } else { - if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { - $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); - } - } - } - //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); - $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - $subtot_coll_total_ht += $temp_ht; - $subtot_coll_vat += $temp_vat; - $x_coll_sum += $temp_vat; - } - } - print ''.price(price2num($x_coll_sum, 'MT')).''; + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } + } + } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + $subtot_coll_total_ht += $temp_ht; + $subtot_coll_vat += $temp_vat; + $x_coll_sum += $temp_vat; + } + } + print ''.price(price2num($x_coll_sum, 'MT')).''; - $x_paye_sum = 0; - foreach (array_keys($x_paye) as $rate) - { - $subtot_paye_total_ht = 0; - $subtot_paye_vat = 0; + $x_paye_sum = 0; + foreach (array_keys($x_paye) as $rate) { + $subtot_paye_total_ht = 0; + $subtot_paye_vat = 0; - foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) - { - // Payment - $ratiopaymentinvoice = 1; - if ($modetax != 1) - { - // Define type - // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. - $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); - // Try to enhance type detection using date_start and date_end for free lines where type - // was not saved. - if (!empty($fields['ddate_start'])) { - $type = 1; - } - if (!empty($fields['ddate_end'])) { - $type = 1; - } + foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) { + // Payment + $ratiopaymentinvoice = 1; + if ($modetax != 1) { + // Define type + // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. + $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); + // Try to enhance type detection using date_start and date_end for free lines where type + // was not saved. + if (!empty($fields['ddate_start'])) { + $type = 1; + } + if (!empty($fields['ddate_end'])) { + $type = 1; + } - if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) - { - //print $langs->trans("NA"); - } else { - if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { - $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); - } - } - } - //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); - $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; - $temp_vat = $fields['vat'] * $ratiopaymentinvoice; - $subtot_paye_total_ht += $temp_ht; - $subtot_paye_vat += $temp_vat; - $x_paye_sum += $temp_vat; - } - } - print ''.price(price2num($x_paye_sum, 'MT')).''; + if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { + //print $langs->trans("NA"); + } else { + if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { + $ratiopaymentinvoice = ($fields['payment_amount'] / $fields['ftotal_ttc']); + } + } + } + //var_dump('type='.$type.' '.$fields['totalht'].' '.$ratiopaymentinvoice); + $temp_ht = $fields['totalht'] * $ratiopaymentinvoice; + $temp_vat = $fields['vat'] * $ratiopaymentinvoice; + $subtot_paye_total_ht += $temp_ht; + $subtot_paye_vat += $temp_vat; + $x_paye_sum += $temp_vat; + } + } + print ''.price(price2num($x_paye_sum, 'MT')).''; - $subtotalcoll = $subtotalcoll + $x_coll_sum; - $subtotalpaye = $subtotalpaye + $x_paye_sum; + $subtotalcoll = $subtotalcoll + $x_coll_sum; + $subtotalpaye = $subtotalpaye + $x_paye_sum; - $diff = $x_coll_sum - $x_paye_sum; - $total = $total + $diff; - $subtotal = price2num($subtotal + $diff, 'MT'); + $diff = $x_coll_sum - $x_paye_sum; + $total = $total + $diff; + $subtotal = price2num($subtotal + $diff, 'MT'); - print ''.price(price2num($diff, 'MT')).''."\n"; - print " \n"; - print "\n"; + print ''.price(price2num($diff, 'MT')).''."\n"; + print " \n"; + print "\n"; - $i++; $m++; - if ($i > 2) - { - print ''; - print ''.$langs->trans("SubTotal").':'; - print ''.price(price2num($subtotalcoll, 'MT')).''; - print ''.price(price2num($subtotalpaye, 'MT')).''; - print ''.price(price2num($subtotal, 'MT')).''; - print ' '; - $i = 0; - $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; - } + $i++; $m++; + if ($i > 2) { + print ''; + print ''.$langs->trans("SubTotal").':'; + print ''.price(price2num($subtotalcoll, 'MT')).''; + print ''.price(price2num($subtotalpaye, 'MT')).''; + print ''.price(price2num($subtotal, 'MT')).''; + print ' '; + $i = 0; + $subtotalcoll = 0; $subtotalpaye = 0; $subtotal = 0; + } } print ''.$langs->trans("TotalToPay").':'.price(price2num($total, 'MT')).''; print " \n"; @@ -579,45 +587,44 @@ $sql .= " ORDER BY dm ASC, mode ASC"; pt($db, $sql, $langs->trans("Month")); -if (!empty($conf->global->MAIN_FEATURES_LEVEL)) -{ +if (!empty($conf->global->MAIN_FEATURES_LEVEL)) { print '
'; /* - * Recap - */ + * Recap + */ - print load_fiche_titre($langs->trans("VATBalance"), '', ''); // need to add translation + print load_fiche_titre($langs->trans("VATBalance"), '', ''); // need to add translation - $sql1 = "SELECT SUM(amount) as mm"; - $sql1 .= " FROM ".MAIN_DB_PREFIX."tva as f"; - $sql1 .= " WHERE f.entity = ".$conf->entity; - $sql1 .= " AND f.datev >= '".$db->idate($date_start)."'"; - $sql1 .= " AND f.datev <= '".$db->idate($date_end)."'"; + $sql1 = "SELECT SUM(amount) as mm"; + $sql1 .= " FROM ".MAIN_DB_PREFIX."tva as f"; + $sql1 .= " WHERE f.entity = ".$conf->entity; + $sql1 .= " AND f.datev >= '".$db->idate($date_start)."'"; + $sql1 .= " AND f.datev <= '".$db->idate($date_end)."'"; - $result = $db->query($sql1); - if ($result) { - $obj = $db->fetch_object($result); - print ''; + $result = $db->query($sql1); + if ($result) { + $obj = $db->fetch_object($result); + print '
'; - print ""; - print ''; - print ''; - print "\n"; + print ""; + print ''; + print ''; + print "\n"; - print ""; - print ''; - print '\n"; - print "\n"; + print ""; + print ''; + print '\n"; + print "\n"; - $restopay = $total - $obj->mm; - print ""; - print ''; - print ''; - print "\n"; + $restopay = $total - $obj->mm; + print ""; + print ''; + print ''; + print "\n"; - print '
'.$langs->trans("VATDue").''.price(price2num($total, 'MT')).'
'.$langs->trans("VATDue").''.price(price2num($total, 'MT')).'
'.$langs->trans("VATPaid").''.price(price2num($obj->mm, 'MT'))."
'.$langs->trans("VATPaid").''.price(price2num($obj->mm, 'MT'))."
'.$langs->trans("RemainToPay").''.price(price2num($restopay, 'MT')).'
'.$langs->trans("RemainToPay").''.price(price2num($restopay, 'MT')).'
'; - } + print ''; + } } print '
'; diff --git a/htdocs/compta/tva/info.php b/htdocs/compta/tva/info.php index 45799c8e1f5..fb3d0c62d86 100644 --- a/htdocs/compta/tva/info.php +++ b/htdocs/compta/tva/info.php @@ -34,7 +34,9 @@ $action = GETPOST('action', 'aZ09'); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); $object = new Tva($db); @@ -45,12 +47,12 @@ $object = new Tva($db); * Actions */ -if ($action == 'setlib' && $user->rights->tax->charges->creer) -{ +if ($action == 'setlib' && $user->rights->tax->charges->creer) { $object->fetch($id); $result = $object->setValueFrom('label', GETPOST('lib', 'alpha'), '', '', 'text', '', $user, 'TAX_MODIFY'); - if ($result < 0) + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); + } } diff --git a/htdocs/compta/tva/list.php b/htdocs/compta/tva/list.php index dd5118bc656..c7146023aab 100644 --- a/htdocs/compta/tva/list.php +++ b/htdocs/compta/tva/list.php @@ -30,7 +30,9 @@ require '../../main.inc.php'; // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); require_once DOL_DOCUMENT_ROOT.'/compta/tva/class/tva.class.php'; @@ -65,13 +67,19 @@ $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 +if (empty($page) || $page == -1) { + $page = 0; // If $page is not defined, or '' or -1 +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 't.datev'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 't.datev'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} $arrayfields = array( 't.rowid' =>array('checked'=>1, 'position'=>10, 'label'=>"Ref",), @@ -94,14 +102,15 @@ $object = new Tva($db); $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 ($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')) // Both test are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $search_ref = ''; $search_label = ''; $search_dateend_start = ''; @@ -137,16 +146,36 @@ $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as pst ON t.fk_typepayment = ps $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_vat as ptva ON ptva.fk_tva = t.rowid"; $sql .= ' WHERE t.entity IN ('.getEntity($object->element).')'; -if (!empty($search_ref)) $sql .= natural_search('t.rowid', $search_ref); -if (!empty($search_label)) $sql .= natural_search('t.label', $search_label); -if (!empty($search_dateend_start)) $sql .= ' AND t.datev >= "'.$db->idate($search_dateend_start).'"'; -if (!empty($search_dateend_end)) $sql .= ' AND t.datev <= "'.$db->idate($search_dateend_end).'"'; -if (!empty($search_datepayment_start)) $sql .= ' AND t.datep >= "'.$db->idate($search_datepayment_start).'"'; -if (!empty($search_datepayment_end)) $sql .= ' AND t.datep <= "'.$db->idate($search_datepayment_end).'"'; -if (!empty($search_type) && $search_type > 0) $sql .= ' AND t.fk_typepayment='.$search_type; -if (!empty($search_account) && $search_account > 0) $sql .= ' AND b.fk_account='.$search_account; -if (!empty($search_amount)) $sql .= natural_search('t.amount', price2num(trim($search_amount)), 1); -if ($search_status != '' && $search_status >= 0) $sql .= " AND t.paye = ".$db->escape($search_status); +if (!empty($search_ref)) { + $sql .= natural_search('t.rowid', $search_ref); +} +if (!empty($search_label)) { + $sql .= natural_search('t.label', $search_label); +} +if (!empty($search_dateend_start)) { + $sql .= ' AND t.datev >= "'.$db->idate($search_dateend_start).'"'; +} +if (!empty($search_dateend_end)) { + $sql .= ' AND t.datev <= "'.$db->idate($search_dateend_end).'"'; +} +if (!empty($search_datepayment_start)) { + $sql .= ' AND t.datep >= "'.$db->idate($search_datepayment_start).'"'; +} +if (!empty($search_datepayment_end)) { + $sql .= ' AND t.datep <= "'.$db->idate($search_datepayment_end).'"'; +} +if (!empty($search_type) && $search_type > 0) { + $sql .= ' AND t.fk_typepayment='.$search_type; +} +if (!empty($search_account) && $search_account > 0) { + $sql .= ' AND b.fk_account='.$search_account; +} +if (!empty($search_amount)) { + $sql .= natural_search('t.amount', price2num(trim($search_amount)), 1); +} +if ($search_status != '' && $search_status >= 0) { + $sql .= " AND t.paye = ".$db->escape($search_status); +} $sql .= " GROUP BY t.rowid, t.amount, t.label, t.datev, t.datep, t.paye, t.fk_typepayment, t.num_payment, pst.code"; $sql .= $db->order($sortfield, $sortorder); @@ -166,8 +195,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $sql .= $db->plimit($limit + 1, $offset); $result = $db->query($sql); -if (!$result) -{ +if (!$result) { dol_print_error($db); llxFooter(); $db->close(); @@ -177,32 +205,78 @@ if (!$result) $num = $db->num_rows($result); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER['PHP_SELF']) $param .= '&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); +if (!empty($contextpage) && $contextpage != $_SERVER['PHP_SELF']) { + $param .= '&contextpage='.$contextpage; +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} -if (!empty($search_ref)) $param .= '&search_ref="'.$search_ref.'"'; -if (!empty($search_label)) $param .= '&search_label="'.$search_label.'"'; -if (!empty($search_dateend_start)) $param .= '&search_dateend_startyear='.GETPOST('search_dateend_startyear', 'int'); -if (!empty($search_dateend_start)) $param .= '&search_dateend_startmonth='.GETPOST('search_dateend_startmonth', 'int'); -if (!empty($search_dateend_start)) $param .= '&search_dateend_startday='.GETPOST('search_dateend_startday', 'int'); -if (!empty($search_dateend_end)) $param .= '&search_dateend_endyear='.GETPOST('search_dateend_endyear', 'int'); -if (!empty($search_dateend_end)) $param .= '&search_dateend_endmonth='.GETPOST('search_dateend_endmonth', 'int'); -if (!empty($search_dateend_end)) $param .= '&search_dateend_endday='.GETPOST('search_dateend_endday', 'int'); -if (!empty($search_datepayment_start)) $param .= '&search_datepayment_startyear='.GETPOST('search_datepayment_startyear', 'int'); -if (!empty($search_datepayment_start)) $param .= '&search_datepayment_startmonth='.GETPOST('search_datepayment_startmonth', 'int'); -if (!empty($search_datepayment_start)) $param .= '&search_datepayment_startday='.GETPOST('search_datepayment_startday', 'int'); -if (!empty($search_datepayment_end)) $param .= '&search_datepayment_endyear='.GETPOST('search_datepayment_endyear', 'int'); -if (!empty($search_datepayment_end)) $param .= '&search_datepayment_endmonth='.GETPOST('search_datepayment_endmonth', 'int'); -if (!empty($search_datepayment_end)) $param .= '&search_datepayment_endday='.GETPOST('search_datepayment_endday', 'int'); -if (!empty($search_type) && $search_type > 0) $param .= '&search_type='.$search_type; -if (!empty($search_cheque)) $param .= '&search_cheque="'.$search_cheque.'"'; -if (!empty($search_account) && $search_account > 0) $param .= '&search_account='.$search_account; -if (!empty($search_amount)) $param .= '&search_amount="'.$search_amount.'"'; -if ($search_status != '' && $search_status != '-1') $param .= '&search_status='.urlencode($search_status); +if (!empty($search_ref)) { + $param .= '&search_ref="'.$search_ref.'"'; +} +if (!empty($search_label)) { + $param .= '&search_label="'.$search_label.'"'; +} +if (!empty($search_dateend_start)) { + $param .= '&search_dateend_startyear='.GETPOST('search_dateend_startyear', 'int'); +} +if (!empty($search_dateend_start)) { + $param .= '&search_dateend_startmonth='.GETPOST('search_dateend_startmonth', 'int'); +} +if (!empty($search_dateend_start)) { + $param .= '&search_dateend_startday='.GETPOST('search_dateend_startday', 'int'); +} +if (!empty($search_dateend_end)) { + $param .= '&search_dateend_endyear='.GETPOST('search_dateend_endyear', 'int'); +} +if (!empty($search_dateend_end)) { + $param .= '&search_dateend_endmonth='.GETPOST('search_dateend_endmonth', 'int'); +} +if (!empty($search_dateend_end)) { + $param .= '&search_dateend_endday='.GETPOST('search_dateend_endday', 'int'); +} +if (!empty($search_datepayment_start)) { + $param .= '&search_datepayment_startyear='.GETPOST('search_datepayment_startyear', 'int'); +} +if (!empty($search_datepayment_start)) { + $param .= '&search_datepayment_startmonth='.GETPOST('search_datepayment_startmonth', 'int'); +} +if (!empty($search_datepayment_start)) { + $param .= '&search_datepayment_startday='.GETPOST('search_datepayment_startday', 'int'); +} +if (!empty($search_datepayment_end)) { + $param .= '&search_datepayment_endyear='.GETPOST('search_datepayment_endyear', 'int'); +} +if (!empty($search_datepayment_end)) { + $param .= '&search_datepayment_endmonth='.GETPOST('search_datepayment_endmonth', 'int'); +} +if (!empty($search_datepayment_end)) { + $param .= '&search_datepayment_endday='.GETPOST('search_datepayment_endday', 'int'); +} +if (!empty($search_type) && $search_type > 0) { + $param .= '&search_type='.$search_type; +} +if (!empty($search_cheque)) { + $param .= '&search_cheque="'.$search_cheque.'"'; +} +if (!empty($search_account) && $search_account > 0) { + $param .= '&search_account='.$search_account; +} +if (!empty($search_amount)) { + $param .= '&search_amount="'.$search_amount.'"'; +} +if ($search_status != '' && $search_status != '-1') { + $param .= '&search_status='.urlencode($search_status); +} print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -211,13 +285,17 @@ print ''; print ''; $url = DOL_URL_ROOT.'/compta/tva/card.php?action=create'; -if (!empty($socid)) $url .= '&socid='.$socid; +if (!empty($socid)) { + $url .= '&socid='.$socid; +} $newcardbutton = dolGetButtonTitle($langs->trans('NewVATPayment', ($ltt + 1)), '', 'fa fa-plus-circle', $url, '', $user->rights->tax->charges->creer); print_barre_liste($langs->trans("VATDeclarations"), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'title_accountancy', 0, $newcardbutton, '', $limit, 0, 0, 1); $varpage = empty($contextpage) ? $_SERVER['PHP_SELF'] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields -if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +} print '
'; print ''; @@ -303,13 +381,27 @@ 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['t.rowid']['checked'])) print_liste_field_titre($arrayfields['t.rowid']['label'], $_SERVER['PHP_SELF'], 't.rowid', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['t.label']['checked'])) print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER['PHP_SELF'], 't.label', '', $param, 'align="left"', $sortfield, $sortorder); -if (!empty($arrayfields['t.datev']['checked'])) print_liste_field_titre($arrayfields['t.datev']['label'], $_SERVER['PHP_SELF'], 't.datev', '', $param, 'align="center"', $sortfield, $sortorder); -if (!empty($arrayfields['t.fk_typepayment']['checked'])) print_liste_field_titre($arrayfields['t.fk_typepayment']['label'], $_SERVER['PHP_SELF'], 't.fk_typepayment', '', $param, '', $sortfield, $sortorder, 'left '); -if (!empty($arrayfields['t.amount']['checked'])) print_liste_field_titre($arrayfields['t.amount']['label'], $_SERVER['PHP_SELF'], 't.amount', '', $param, '', $sortfield, $sortorder, 'right '); -if (!empty($arrayfields['t.status']['checked'])) print_liste_field_titre($arrayfields['t.status']['label'], $_SERVER["PHP_SELF"], "t.paye", "", $param, 'class="right"', $sortfield, $sortorder); +if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { + print_liste_field_titre('#', $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.rowid']['checked'])) { + print_liste_field_titre($arrayfields['t.rowid']['label'], $_SERVER['PHP_SELF'], 't.rowid', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.label']['checked'])) { + print_liste_field_titre($arrayfields['t.label']['label'], $_SERVER['PHP_SELF'], 't.label', '', $param, 'align="left"', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.datev']['checked'])) { + print_liste_field_titre($arrayfields['t.datev']['label'], $_SERVER['PHP_SELF'], 't.datev', '', $param, 'align="center"', $sortfield, $sortorder); +} +if (!empty($arrayfields['t.fk_typepayment']['checked'])) { + print_liste_field_titre($arrayfields['t.fk_typepayment']['label'], $_SERVER['PHP_SELF'], 't.fk_typepayment', '', $param, '', $sortfield, $sortorder, 'left '); +} +if (!empty($arrayfields['t.amount']['checked'])) { + print_liste_field_titre($arrayfields['t.amount']['label'], $_SERVER['PHP_SELF'], 't.amount', '', $param, '', $sortfield, $sortorder, 'right '); +} +if (!empty($arrayfields['t.status']['checked'])) { + print_liste_field_titre($arrayfields['t.status']['label'], $_SERVER["PHP_SELF"], "t.paye", "", $param, 'class="right"', $sortfield, $sortorder); +} // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); @@ -333,25 +425,33 @@ while ($i < min($num, $limit)) { // No if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref if (!empty($arrayfields['t.rowid']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Label if (!empty($arrayfields['t.label']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date end period if (!empty($arrayfields['t.datev']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date payment @@ -361,10 +461,11 @@ while ($i < min($num, $limit)) { }*/ // Type - if (!empty($arrayfields['t.fk_typepayment']['checked'])) - { + if (!empty($arrayfields['t.fk_typepayment']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Account @@ -390,15 +491,21 @@ while ($i < min($num, $limit)) { if (!empty($arrayfields['t.amount']['checked'])) { $total = $total + $obj->amount; print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } $totalarray['pos'][$totalarray['nbfield']] = 'amount'; $totalarray['val']['amount'] += $obj->amount; } if (!empty($arrayfields['t.status']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; - if (!empty($arrayfields['t.amount']['checked'])) $totalarray['pos'][$totalarray['nbfield']] = ''; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($arrayfields['t.amount']['checked'])) { + $totalarray['pos'][$totalarray['nbfield']] = ''; + } } // Buttons diff --git a/htdocs/compta/tva/payments.php b/htdocs/compta/tva/payments.php index 0cdf7e7086b..73e2dae0e05 100644 --- a/htdocs/compta/tva/payments.php +++ b/htdocs/compta/tva/payments.php @@ -39,24 +39,34 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; $langs->loadLangs(array('compta', 'bills')); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax|salaries', '', '', 'charges|'); $mode = GETPOST("mode", 'alpha'); $year = GETPOST("year", 'int'); $filtre = GETPOST("filtre", 'alpha'); -if (!$year && $mode != 'tvaonly') { $year = date("Y", time()); } +if (!$year && $mode != 'tvaonly') { + $year = date("Y", time()); +} $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 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = "ptva.datep"; -if (!$sortorder) $sortorder = "DESC"; +if (!$sortfield) { + $sortfield = "ptva.datep"; +} +if (!$sortorder) { + $sortorder = "DESC"; +} /* @@ -73,14 +83,24 @@ llxHeader('', $langs->trans("VATExpensesArea")); $title = $langs->trans("VATPayments"); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; -if ($sortfield) $param .= '&sortfield='.$sortfield; -if ($sortorder) $param .= '&sortorder='.$sortorder; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; +} +if ($sortfield) { + $param .= '&sortfield='.$sortfield; +} +if ($sortorder) { + $param .= '&sortorder='.$sortorder; +} print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -90,10 +110,11 @@ print ''; print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $center, $num, $totalnboflines, 'title_accountancy', 0, '', '', $limit); -if ($year) $param .= '&year='.$year; +if ($year) { + $param .= '&year='.$year; +} -if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) -{ +if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) { print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '
'.(($offset * $limit) + $i).''.$tva_static->getNomUrl(1).''.dol_trunc($obj->label, 40).''.dol_print_date($db->jdate($obj->datev), 'day').''.$langs->trans("PaymentTypeShort".$obj->payment_code).'' . price($obj->amount) . '' . $tva_static->LibStatut($obj->paye, 5, $obj->alreadypayed) . '
'; print ''; @@ -120,8 +141,7 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON ptva.fk_typepaiement = pct.id"; $sql .= " WHERE ptva.fk_tva = tva.rowid"; $sql .= " AND tva.entity = ".$conf->entity; - if ($year > 0) - { + if ($year > 0) { $sql .= " AND ("; // Si period renseignee on l'utilise comme critere de date, sinon on prend date echeance, // ceci afin d'etre compatible avec les cas ou la periode n'etait pas obligatoire @@ -133,22 +153,22 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) || preg_match('/^tva\./', $sortfield) || preg_match('/^ptva\./', $sortfield) || preg_match('/^pct\./', $sortfield) - || preg_match('/^bank\./', $sortfield)) $sql .= $db->order($sortfield, $sortorder); + || preg_match('/^bank\./', $sortfield)) { + $sql .= $db->order($sortfield, $sortorder); + } //$sql.= $db->plimit($limit+1,$offset); //print $sql; dol_syslog("compta/tva/payments.php: select payment", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; $total = 0; $totalnb = 0; $totalpaye = 0; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $payment_vat_static->id = $obj->pid; @@ -159,11 +179,13 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print '\n"; // Date payment print ''; - // Type payment - print ''; - // Account + // Type payment + print ''; + // Account print ''; // Paid print ''; print ''; @@ -194,16 +218,15 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) $totalpaye = $totalpaye + $obj->totalpaye; $i++; } - print ''; - print ''; // A total here has no sense - //print ''; - print ''; + print ''; + print ''; // A total here has no sense + //print ''; print ''; print ''; - print '"; + print ''; + print '"; print ""; - } - else { + } else { dol_print_error($db); } print '
'.$payment_vat_static->getNomUrl(1)."'.dol_print_date($db->jdate($obj->datep), 'day').''; - if ($obj->payment_code) print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; - print $obj->num_payment.''; + if ($obj->payment_code) { + print $langs->trans("PaymentTypeShort".$obj->payment_code).' '; + } + print $obj->num_payment.''; $account = new Account($db); $account->fetch($obj->fk_account); @@ -185,7 +207,9 @@ if (!empty($conf->tax->enabled) && $user->rights->tax->charges->lire) print ''.price($obj->total).''; - if ($obj->totalpaye) print price($obj->totalpaye); + if ($obj->totalpaye) { + print price($obj->totalpaye); + } print '
'.$langs->trans("Total").'  
'.$langs->trans("Total").'   '.price($totalpaye)." '.price($totalpaye)."
'; diff --git a/htdocs/compta/tva/quadri_detail.php b/htdocs/compta/tva/quadri_detail.php index ba12b08b3b0..04f90ba02f9 100644 --- a/htdocs/compta/tva/quadri_detail.php +++ b/htdocs/compta/tva/quadri_detail.php @@ -46,12 +46,13 @@ $langs->loadLangs(array("other", "compta", "banks", "bills", "companies", "produ $now = dol_now(); $current_date = dol_getdate($now); -if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) $conf->global->SOCIETE_FISCAL_MONTH_START = 1; +if (empty($conf->global->SOCIETE_FISCAL_MONTH_START)) { + $conf->global->SOCIETE_FISCAL_MONTH_START = 1; +} // Date range $year = GETPOST("year", "int"); -if (empty($year)) -{ +if (empty($year)) { $year_current = $current_date['year']; $year_start = $year_current; } else { @@ -61,12 +62,12 @@ if (empty($year)) $date_start = dol_mktime(0, 0, 0, GETPOST("date_startmonth"), GETPOST("date_startday"), GETPOST("date_startyear")); $date_end = dol_mktime(23, 59, 59, GETPOST("date_endmonth"), GETPOST("date_endday"), GETPOST("date_endyear")); // Set default period if not defined -if (empty($date_start) || empty($date_end)) // We define date_start and date_end -{ +if (empty($date_start) || empty($date_end)) { // We define date_start and date_end $q = GETPOST("q", "int"); - if (empty($q)) - { - if (GETPOST("month", "int")) { $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } else { + if (empty($q)) { + if (GETPOST("month", "int")) { + $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); + } else { if (empty($conf->global->MAIN_INFO_VAT_RETURN) || $conf->global->MAIN_INFO_VAT_RETURN == 2) { // quaterly vat, we take last past complete quarter $date_start = dol_time_plus_duree(dol_get_first_day($year_start, $current_date['mon'], false), -3 - (($current_date['mon'] - $conf->global->SOCIETE_FISCAL_MONTH_START) % 3), 'm'); $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; @@ -88,25 +89,41 @@ if (empty($date_start) || empty($date_end)) // We define date_start and date_end } } } else { - if ($q == 1) { $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); } - if ($q == 2) { $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); } - if ($q == 3) { $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); } - if ($q == 4) { $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); } + if ($q == 1) { + $date_start = dol_get_first_day($year_start, 1, false); $date_end = dol_get_last_day($year_start, 3, false); + } + if ($q == 2) { + $date_start = dol_get_first_day($year_start, 4, false); $date_end = dol_get_last_day($year_start, 6, false); + } + if ($q == 3) { + $date_start = dol_get_first_day($year_start, 7, false); $date_end = dol_get_last_day($year_start, 9, false); + } + if ($q == 4) { + $date_start = dol_get_first_day($year_start, 10, false); $date_end = dol_get_last_day($year_start, 12, false); + } } } $min = price2num(GETPOST("min", "alpha")); -if (empty($min)) $min = 0; +if (empty($min)) { + $min = 0; +} // Define modetax (0 or 1) // 0=normal, 1=option vat for services is on debit, 2=option on payments for products $modetax = $conf->global->TAX_MODE; -if (GETPOSTISSET("modetax")) $modetax = GETPOST("modetax", 'int'); -if (empty($modetax)) $modetax = 0; +if (GETPOSTISSET("modetax")) { + $modetax = GETPOST("modetax", 'int'); +} +if (empty($modetax)) { + $modetax = 0; +} // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'tax', '', '', 'charges'); @@ -127,9 +144,10 @@ $paymentexpensereport_static = new PaymentExpenseReport($db); $morequerystring = ''; $listofparams = array('date_startmonth', 'date_startyear', 'date_startday', 'date_endmonth', 'date_endyear', 'date_endday'); -foreach ($listofparams as $param) -{ - if (GETPOST($param) != '') $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); +foreach ($listofparams as $param) { + if (GETPOST($param) != '') { + $morequerystring .= ($morequerystring ? '&' : '').$param.'='.GETPOST($param); + } } $title = $langs->trans("VATReport")." ".dol_print_date($date_start)." -> ".dol_print_date($date_end); @@ -149,9 +167,15 @@ $fsearch .= ''; // Show report header $name = $langs->trans("VATReportByRates"); $calcmode = ''; -if ($modetax == 0) $calcmode = $langs->trans('OptionVATDefault'); -if ($modetax == 1) $calcmode = $langs->trans('OptionVATDebitOption'); -if ($modetax == 2) $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +if ($modetax == 0) { + $calcmode = $langs->trans('OptionVATDefault'); +} +if ($modetax == 1) { + $calcmode = $langs->trans('OptionVATDebitOption'); +} +if ($modetax == 2) { + $calcmode = $langs->trans('OptionPaymentForProductAndServices'); +} $calcmode .= ' ('.$langs->trans("TaxModuleSetupToModifyRules", DOL_URL_ROOT.'/admin/taxes.php').')'; // Set period $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); @@ -173,14 +197,24 @@ if ($nextquarter < 4) { $description .= $fsearch; $builddate = dol_now(); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') $description .= $langs->trans("RulesVATDueProducts"); -if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') $description .= $langs->trans("RulesVATInProducts"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') $description .= '
'.$langs->trans("RulesVATDueServices"); -if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') $description .= '
'.$langs->trans("RulesVATInServices"); +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') { + $description .= $langs->trans("RulesVATDueProducts"); +} +if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment') { + $description .= $langs->trans("RulesVATInProducts"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'invoice') { + $description .= '
'.$langs->trans("RulesVATDueServices"); +} +if ($conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + $description .= '
'.$langs->trans("RulesVATInServices"); +} if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { $description .= '
'.$langs->trans("DepositsAreNotIncluded"); } -if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) $description .= '
'.$langs->trans("ThisIsAnEstimatedValue"); +if (!empty($conf->global->MAIN_MODULE_ACCOUNTING)) { + $description .= '
'.$langs->trans("ThisIsAnEstimatedValue"); +} // Customers invoices $elementcust = $langs->trans("CustomersInvoices"); @@ -225,8 +259,7 @@ $columns = 5; $x_coll = tax_by_rate('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'sell'); $x_paye = tax_by_rate('vat', $db, 0, 0, $date_start, $date_end, $modetax, 'buy'); -if (!is_array($x_coll) || !is_array($x_paye)) -{ +if (!is_array($x_coll) || !is_array($x_paye)) { $langs->load("errors"); if ($x_coll == -1) { print ''.$langs->trans("ErrorNoAccountancyModuleLoaded").''; @@ -238,15 +271,14 @@ if (!is_array($x_coll) || !is_array($x_paye)) } else { $x_both = array(); //now, from these two arrays, get another array with one rate per line - foreach (array_keys($x_coll) as $my_coll_rate) - { + foreach (array_keys($x_coll) as $my_coll_rate) { $x_both[$my_coll_rate]['coll']['totalht'] = $x_coll[$my_coll_rate]['totalht']; $x_both[$my_coll_rate]['coll']['vat'] = $x_coll[$my_coll_rate]['vat']; $x_both[$my_coll_rate]['paye']['totalht'] = 0; $x_both[$my_coll_rate]['paye']['vat'] = 0; $x_both[$my_coll_rate]['coll']['links'] = ''; $x_both[$my_coll_rate]['coll']['detail'] = array(); - foreach ($x_coll[$my_coll_rate]['facid'] as $id=>$dummy) { + foreach ($x_coll[$my_coll_rate]['facid'] as $id => $dummy) { $invoice_customer->id = $x_coll[$my_coll_rate]['facid'][$id]; $invoice_customer->ref = $x_coll[$my_coll_rate]['facnum'][$id]; $invoice_customer->type = $x_coll[$my_coll_rate]['type'][$id]; @@ -284,11 +316,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_both[$my_paye_rate]['paye']['links'] = ''; $x_both[$my_paye_rate]['paye']['detail'] = array(); - foreach ($x_paye[$my_paye_rate]['facid'] as $id=>$dummy) - { + foreach ($x_paye[$my_paye_rate]['facid'] as $id => $dummy) { // ExpenseReport - if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') - { + if ($x_paye[$my_paye_rate]['ptype'][$id] == 'ExpenseReportPayment') { $expensereport->id = $x_paye[$my_paye_rate]['facid'][$id]; $expensereport->ref = $x_paye[$my_paye_rate]['facnum'][$id]; $expensereport->type = $x_paye[$my_paye_rate]['type'][$id]; @@ -349,7 +379,9 @@ if (!is_array($x_coll) || !is_array($x_paye)) $x_paye_ht = 0; $span = $columns; - if ($modetax != 1) $span += 2; + if ($modetax != 1) { + $span += 2; + } //print ''..')'; @@ -357,12 +389,14 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''.$elementcust.''; print ''.$langs->trans("DateInvoice").''; - if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''.$langs->trans("DatePayment").''; - else print ''; + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + print ''.$langs->trans("DatePayment").''; + } else { + print ''; + } print ''.$namecust.''; print ''.$productcust.''; - if ($modetax != 1) - { + if ($modetax != 1) { print ''.$amountcust.''; print ''.$langs->trans("Payment").' ('.$langs->trans("PercentOfInvoice").')'; } @@ -385,8 +419,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) $subtot_coll_total_ht = 0; $subtot_coll_vat = 0; - if (is_array($x_both[$rate]['coll']['detail'])) - { + if (is_array($x_both[$rate]['coll']['detail'])) { // VAT Rate print ""; print ''.$langs->trans("Rate").': '.vatrate($rate).'%'; @@ -415,16 +448,18 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''.dol_print_date($fields['datef'], 'day').''; // Payment date - if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') print ''.dol_print_date($fields['datep'], 'day').''; - else print ''; + if ($conf->global->TAX_MODE_SELL_PRODUCT == 'payment' || $conf->global->TAX_MODE_SELL_SERVICE == 'payment') { + print ''.dol_print_date($fields['datep'], 'day').''; + } else { + print ''; + } // Company name print ''.$fields['company_link'].''; // Description print ''; - if ($fields['pid']) - { + if ($fields['pid']) { $product_static->id = $fields['pid']; $product_static->ref = $fields['pref']; $product_static->type = $fields['dtype']; // We force with the type of line to have type how line is registered @@ -455,12 +490,10 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; // Total HT - if ($modetax != 1) - { + if ($modetax != 1) { print ''; print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) - { + if (price2num($fields['ftotal_ttc'])) { //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; $ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']); //print ' ('.round($ratiolineinvoice*100,2).'%)'; @@ -470,18 +503,15 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Payment $ratiopaymentinvoice = 1; - if ($modetax != 1) - { + if ($modetax != 1) { print ''; //print $fields['totalht']."-".$fields['payment_amount']."-".$fields['ftotal_ttc']; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) - { + if ($fields['payment_amount'] && $fields['ftotal_ttc']) { $payment_static->id = $fields['payment_id']; print $payment_static->getNomUrl(2); } if (($type == 0 && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) - { + || ($type == 1 && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice')) { print $langs->trans("NA"); } else { if (isset($fields['payment_amount']) && price2num($fields['ftotal_ttc'])) { @@ -527,8 +557,7 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; } - if (count($x_coll) == 0) // Show a total line if nothing shown - { + if (count($x_coll) == 0) { // Show a total line if nothing shown print ''; print ''; print ''.$langs->trans("Total").':'; @@ -548,8 +577,11 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; print ''.$elementsup.''; print ''.$langs->trans("DateInvoice").''; - if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''.$langs->trans("DatePayment").''; - else print ''; + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') { + print ''.$langs->trans("DatePayment").''; + } else { + print ''; + } print ''.$namesup.''; print ''.$productsup.''; if ($modetax != 1) { @@ -560,18 +592,16 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''.$vatsup.''; print ''."\n"; - foreach (array_keys($x_paye) as $rate) - { + foreach (array_keys($x_paye) as $rate) { $subtot_paye_total_ht = 0; $subtot_paye_vat = 0; - if (is_array($x_both[$rate]['paye']['detail'])) - { + if (is_array($x_both[$rate]['paye']['detail'])) { print ""; print ''.$langs->trans("Rate").': '.vatrate($rate).'%'; print ''."\n"; - foreach ($x_both[$rate]['paye']['detail'] as $index=>$fields) { + foreach ($x_both[$rate]['paye']['detail'] as $index => $fields) { // Define type // We MUST use dtype (type in line). We can use something else, only if dtype is really unknown. $type = (isset($fields['dtype']) ? $fields['dtype'] : $fields['ptype']); @@ -594,16 +624,18 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''.dol_print_date($fields['datef'], 'day').''; // Payment date - if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') print ''.dol_print_date($fields['datep'], 'day').''; - else print ''; + if ($conf->global->TAX_MODE_BUY_PRODUCT == 'payment' || $conf->global->TAX_MODE_BUY_SERVICE == 'payment') { + print ''.dol_print_date($fields['datep'], 'day').''; + } else { + print ''; + } // Company name print ''.$fields['company_link'].''; // Description print ''; - if ($fields['pid']) - { + if ($fields['pid']) { $product_static->id = $fields['pid']; $product_static->ref = $fields['pref']; $product_static->type = $fields['dtype']; // We force with the type of line to have type how line is registered @@ -634,12 +666,10 @@ if (!is_array($x_coll) || !is_array($x_paye)) print ''; // Total HT - if ($modetax != 1) - { + if ($modetax != 1) { print ''; print price($fields['totalht']); - if (price2num($fields['ftotal_ttc'])) - { + if (price2num($fields['ftotal_ttc'])) { //print $fields['dtotal_ttc']."/".$fields['ftotal_ttc']." - "; $ratiolineinvoice = ($fields['dtotal_ttc'] / $fields['ftotal_ttc']); //print ' ('.round($ratiolineinvoice*100,2).'%)'; @@ -649,18 +679,15 @@ if (!is_array($x_coll) || !is_array($x_paye)) // Payment $ratiopaymentinvoice = 1; - if ($modetax != 1) - { + if ($modetax != 1) { print ''; - if ($fields['payment_amount'] && $fields['ftotal_ttc']) - { + if ($fields['payment_amount'] && $fields['ftotal_ttc']) { $paymentfourn_static->id = $fields['payment_id']; print $paymentfourn_static->getNomUrl(2); } if (($type == 0 && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice') - || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) - { + || ($type == 1 && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { print $langs->trans("NA"); } else { if (isset($fields['payment_amount']) && $fields['ftotal_ttc']) { From 3b6d01ffaeaed9d0111772af98f3aa84ba43eeff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 21:16:15 +0100 Subject: [PATCH 21/64] code syntax contact directory --- htdocs/contact/agenda.php | 128 +-- .../actions_contactcard_common.class.php | 116 +-- .../default/tpl/contactcard_create.tpl.php | 3 +- .../default/tpl/contactcard_edit.tpl.php | 3 +- .../default/tpl/contactcard_view.tpl.php | 11 +- htdocs/contact/card.php | 454 +++++------ htdocs/contact/class/contact.class.php | 486 ++++++----- htdocs/contact/consumption.php | 269 ++++--- htdocs/contact/document.php | 81 +- htdocs/contact/info.php | 7 +- htdocs/contact/ldap.php | 32 +- htdocs/contact/list.php | 761 +++++++++++------- htdocs/contact/note.php | 29 +- htdocs/contact/perso.php | 128 +-- htdocs/contact/vcard.php | 49 +- 15 files changed, 1432 insertions(+), 1125 deletions(-) diff --git a/htdocs/contact/agenda.php b/htdocs/contact/agenda.php index 2aeb2e4e2a1..ca496540a47 100644 --- a/htdocs/contact/agenda.php +++ b/htdocs/contact/agenda.php @@ -65,36 +65,44 @@ $extrafields->fetch_name_optionals_label($object->table_element); $object->getCanvas($id); $objcanvas = null; $canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas")); -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('contact', 'contactcard', $canvas); } -if (GETPOST('actioncode', 'array')) -{ +if (GETPOST('actioncode', 'array')) { $actioncode = GETPOST('actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + if (!count($actioncode)) { + $actioncode = '0'; + } } else { $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); } $search_agenda_label = GETPOST('search_agenda_label'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', 0); // If we create a contact with no company (shared contacts), no check on write permission $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 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'a.datep, a.id'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'a.datep, a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('contactagenda', 'globalcard')); @@ -106,20 +114,19 @@ $hookmanager->initHooks(array('contactagenda', 'globalcard')); $parameters = array('id'=>$id, 'objcanvas'=>$objcanvas); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // Purge search criteria - 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 - { + 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 $actioncode = ''; $search_agenda_label = ''; } @@ -133,29 +140,30 @@ if (empty($reshook)) $form = new Form($db); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) { + $title = $object->lastname; +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($socid > 0) -{ +if ($socid > 0) { $objsoc = new Societe($db); $objsoc->fetch($socid); } -if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) -{ +if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // ----------------------------------------- // When used with CANVAS // ----------------------------------------- - if (empty($object->error) && $id) - { - $object = new Contact($db); - $result = $object->fetch($id); - if ($result <= 0) dol_print_error('', $object->error); - } - $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates + if (empty($object->error) && $id) { + $object = new Contact($db); + $result = $object->fetch($id); + if ($result <= 0) { + dol_print_error('', $object->error); + } + } + $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates $objcanvas->display_canvas($action); // Show template } else { // ----------------------------------------- @@ -163,26 +171,27 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // ----------------------------------------- // Confirm deleting contact - if ($user->rights->societe->contact->supprimer) - { - if ($action == 'delete') - { + if ($user->rights->societe->contact->supprimer) { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage ? '&backtopage='.$backtopage : ''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1); } } /* - * Onglets - */ + * Onglets + */ $head = array(); - if ($id > 0) - { + if ($id > 0) { // Si edition contact deja existant $object = new Contact($db); $res = $object->fetch($id, $user); - if ($res < 0) { dol_print_error($db, $object->error); exit; } + if ($res < 0) { + dol_print_error($db, $object->error); exit; + } $res = $object->fetch_optionals(); - if ($res < 0) { dol_print_error($db, $object->error); exit; } + if ($res < 0) { + dol_print_error($db, $object->error); exit; + } // Show tabs $head = contact_prepare_head($object); @@ -190,13 +199,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); } - if (!empty($id) && $action != 'edit' && $action != 'create') - { + if (!empty($id) && $action != 'edit' && $action != 'create') { $objsoc = new Societe($db); /* - * Fiche en mode visualisation - */ + * Fiche en mode visualisation + */ dol_htmloutput_errors($error, $errors); @@ -205,14 +213,16 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
'; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
'; @@ -238,29 +248,31 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $out = ''; $permok = $user->rights->agenda->myactions->create; - if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) - { - if (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') $out .= '&originid='.$objthirdparty->id.($objthirdparty->id > 0 ? '&socid='.$objthirdparty->id : ''); + if ((!empty($objthirdparty->id) || !empty($objcon->id)) && $permok) { + if (is_object($objthirdparty) && get_class($objthirdparty) == 'Societe') { + $out .= '&originid='.$objthirdparty->id.($objthirdparty->id > 0 ? '&socid='.$objthirdparty->id : ''); + } $out .= (!empty($objcon->id) ? '&contactid='.$objcon->id : '').'&origin=contact&originid='.$object->id.'&percentage=-1&backtopage='.urlencode($_SERVER['PHP_SELF'].($objcon->id > 0 ? '?id='.$objcon->id : '')); $out .= '&datep='.urlencode(dol_print_date(dol_now(), 'dayhourlog')); } $newcardbutton = ''; - if (!empty($conf->agenda->enabled)) - { - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { $newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out); } } - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { - print '
'; + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { + print '
'; $param = '&id='.$id; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; + } print load_fiche_titre($langs->trans("ActionsOnContact"), $newcardbutton, ''); //print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $morehtmlcenter, 0, -1, '', '', '', '', 0, 1, 1); diff --git a/htdocs/contact/canvas/actions_contactcard_common.class.php b/htdocs/contact/canvas/actions_contactcard_common.class.php index f6f6fa0b45e..a32263cd65e 100644 --- a/htdocs/contact/canvas/actions_contactcard_common.class.php +++ b/htdocs/contact/canvas/actions_contactcard_common.class.php @@ -64,14 +64,16 @@ abstract class ActionsContactCardCommon { /*$ret = $this->getInstanceDao(); - if (is_object($this->object) && method_exists($this->object,'fetch')) - { - if (! empty($id)) $this->object->fetch($id); - } - else - {*/ + if (is_object($this->object) && method_exists($this->object,'fetch')) + { + if (! empty($id)) $this->object->fetch($id); + } + else + {*/ $object = new Contact($this->db); - if (!empty($id)) $object->fetch($id); + if (!empty($id)) { + $object->fetch($id); + } $this->object = $object; //} } @@ -90,20 +92,19 @@ abstract class ActionsContactCardCommon global $conf, $langs, $user, $canvas; global $form, $formcompany, $objsoc; - if ($action == 'add' || $action == 'update') $this->assign_post(); + if ($action == 'add' || $action == 'update') { + $this->assign_post(); + } - foreach ($this->object as $key => $value) - { + foreach ($this->object as $key => $value) { $this->tpl[$key] = $value; } $this->tpl['error'] = $this->error; $this->tpl['errors'] = $this->errors; - if ($action == 'create' || $action == 'edit') - { - if ($conf->use_javascript_ajax) - { + if ($action == 'create' || $action == 'edit') { + if ($conf->use_javascript_ajax) { $this->tpl['ajax_selectcountry'] = "\n".''."\n"; } - if (is_object($objsoc) && $objsoc->id > 0) - { + if (is_object($objsoc) && $objsoc->id > 0) { $this->tpl['company'] = $objsoc->getNomUrl(1); $this->tpl['company_id'] = $objsoc->id; } else { @@ -127,14 +127,25 @@ abstract class ActionsContactCardCommon $this->tpl['select_civility'] = $formcompany->select_civility($this->object->civility_id); // Predefined with third party - if ((isset($objsoc->typent_code) && $objsoc->typent_code == 'TE_PRIVATE') || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) - { - if (dol_strlen(trim($this->object->address)) == 0) $this->tpl['address'] = $objsoc->address; - if (dol_strlen(trim($this->object->zip)) == 0) $this->object->zip = $objsoc->zip; - if (dol_strlen(trim($this->object->town)) == 0) $this->object->town = $objsoc->town; - if (dol_strlen(trim($this->object->phone_pro)) == 0) $this->object->phone_pro = $objsoc->phone; - if (dol_strlen(trim($this->object->fax)) == 0) $this->object->fax = $objsoc->fax; - if (dol_strlen(trim($this->object->email)) == 0) $this->object->email = $objsoc->email; + if ((isset($objsoc->typent_code) && $objsoc->typent_code == 'TE_PRIVATE') || !empty($conf->global->CONTACT_USE_COMPANY_ADDRESS)) { + if (dol_strlen(trim($this->object->address)) == 0) { + $this->tpl['address'] = $objsoc->address; + } + if (dol_strlen(trim($this->object->zip)) == 0) { + $this->object->zip = $objsoc->zip; + } + if (dol_strlen(trim($this->object->town)) == 0) { + $this->object->town = $objsoc->town; + } + if (dol_strlen(trim($this->object->phone_pro)) == 0) { + $this->object->phone_pro = $objsoc->phone; + } + if (dol_strlen(trim($this->object->fax)) == 0) { + $this->object->fax = $objsoc->fax; + } + if (dol_strlen(trim($this->object->email)) == 0) { + $this->object->email = $objsoc->email; + } } // Zip @@ -143,28 +154,33 @@ abstract class ActionsContactCardCommon // Town $this->tpl['select_town'] = $formcompany->select_ziptown($this->object->town, 'town', array('zipcode', 'selectcountry_id', 'state_id')); - if (dol_strlen(trim($this->object->country_id)) == 0) $this->object->country_id = $objsoc->country_id; + if (dol_strlen(trim($this->object->country_id)) == 0) { + $this->object->country_id = $objsoc->country_id; + } // Country $this->tpl['select_country'] = $form->select_country($this->object->country_id, 'country_id'); $countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; - if ($user->admin) $this->tpl['info_admin'] = info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + if ($user->admin) { + $this->tpl['info_admin'] = info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"), 1); + } // State - if ($this->object->country_id) $this->tpl['select_state'] = $formcompany->select_state($this->object->state_id, $this->object->country_code); - else $this->tpl['select_state'] = $countrynotdefined; + if ($this->object->country_id) { + $this->tpl['select_state'] = $formcompany->select_state($this->object->state_id, $this->object->country_code); + } else { + $this->tpl['select_state'] = $countrynotdefined; + } // Public or private $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); $this->tpl['select_visibility'] = $form->selectarray('priv', $selectarray, $this->object->priv, 0); } - if ($action == 'view' || $action == 'edit' || $action == 'delete') - { + if ($action == 'view' || $action == 'edit' || $action == 'delete') { // Emailing - if (!empty($conf->mailing->enabled)) - { + if (!empty($conf->mailing->enabled)) { $langs->load("mails"); $this->tpl['nb_emailing'] = $this->object->getNbOfEMailings(); } @@ -175,46 +191,41 @@ abstract class ActionsContactCardCommon $this->object->load_ref_elements(); - if (!empty($conf->commande->enabled)) - { + if (!empty($conf->commande->enabled)) { $this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForOrders"); $this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_commande ? $this->object->ref_commande : $langs->trans("NoContactForAnyOrder"); $i++; } - if (!empty($conf->propal->enabled)) - { + if (!empty($conf->propal->enabled)) { $this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForProposals"); $this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_propal ? $this->object->ref_propal : $langs->trans("NoContactForAnyProposal"); $i++; } - if (!empty($conf->contrat->enabled)) - { + if (!empty($conf->contrat->enabled)) { $this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForContracts"); $this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_contrat ? $this->object->ref_contrat : $langs->trans("NoContactForAnyContract"); $i++; } - if (!empty($conf->facture->enabled)) - { + if (!empty($conf->facture->enabled)) { $this->tpl['contact_element'][$i]['linked_element_label'] = $langs->trans("ContactForInvoices"); $this->tpl['contact_element'][$i]['linked_element_value'] = $this->object->ref_facturation ? $this->object->ref_facturation : $langs->trans("NoContactForAnyInvoice"); $i++; } // Dolibarr user - if ($this->object->user_id) - { + if ($this->object->user_id) { $dolibarr_user = new User($this->db); $result = $dolibarr_user->fetch($this->object->user_id); $this->tpl['dolibarr_user'] = $dolibarr_user->getLoginUrl(1); - } else $this->tpl['dolibarr_user'] = $langs->trans("NoDolibarrAccess"); + } else { + $this->tpl['dolibarr_user'] = $langs->trans("NoDolibarrAccess"); + } } - if ($action == 'view' || $action == 'delete') - { + if ($action == 'view' || $action == 'delete') { $this->tpl['showrefnav'] = $form->showrefnav($this->object, 'id'); - if ($this->object->socid > 0) - { + if ($this->object->socid > 0) { $objsoc = new Societe($this->db); $objsoc->fetch($this->object->socid); @@ -243,14 +254,13 @@ abstract class ActionsContactCardCommon $this->tpl['note'] = nl2br($this->object->note); } - if ($action == 'create_user') - { + if ($action == 'create_user') { // Full firstname and lastname separated with a dot : firstname.lastname include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $login = dol_buildlogin($this->object->lastname, $this->object->firstname); - $generated_password = getRandomPassword(false); + $generated_password = getRandomPassword(false); $password = $generated_password; // Create a form array @@ -297,12 +307,10 @@ abstract class ActionsContactCardCommon $this->object->canvas = $_POST["canvas"]; // We set country_id, and country_code label of the chosen country - if ($this->object->country_id) - { + if ($this->object->country_id) { $sql = "SELECT code, label FROM ".MAIN_DB_PREFIX."c_country WHERE rowid = ".$this->object->country_id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); } else { dol_print_error($this->db); diff --git a/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php index 98a66e499b9..bd5cf24e195 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_create.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } diff --git a/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php index 2c82a868ed4..41fbdb5def9 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_edit.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } diff --git a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php index 43fd48e3ef0..c624eca4026 100644 --- a/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php +++ b/htdocs/contact/canvas/default/tpl/contactcard_view.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -30,8 +29,12 @@ echo $this->control->tpl['showhead']; dol_htmloutput_errors($this->control->tpl['error'], $this->control->tpl['errors']); -if (!empty($this->control->tpl['action_create_user'])) echo $this->control->tpl['action_create_user']; -if (!empty($this->control->tpl['action_delete'])) echo $this->control->tpl['action_delete']; ?> +if (!empty($this->control->tpl['action_create_user'])) { + echo $this->control->tpl['action_create_user']; +} +if (!empty($this->control->tpl['action_delete'])) { + echo $this->control->tpl['action_delete']; +} ?> diff --git a/htdocs/contact/card.php b/htdocs/contact/card.php index 3866405bee8..0def459d444 100644 --- a/htdocs/contact/card.php +++ b/htdocs/contact/card.php @@ -71,24 +71,26 @@ $socialnetworks = getArrayOfSocialNetworks(); $object->getCanvas($id); $objcanvas = null; $canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas")); -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('contact', 'contactcard', $canvas); } // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', 0); // If we create a contact with no company (shared contacts), no check on write permission // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('contactcard', 'globalcard')); -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} -if (!($object->id > 0) && $action == 'view') -{ +if (!($object->id > 0) && $action == 'view') { $langs->load("errors"); print($langs->trans('ErrorRecordNotFound')); exit; @@ -100,36 +102,32 @@ if (!($object->id > 0) && $action == 'view') $parameters = array('id'=>$id, 'objcanvas'=>$objcanvas); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // Creation utilisateur depuis contact - if ($action == 'confirm_create_user' && $confirm == 'yes' && $user->rights->user->user->creer) - { + if ($action == 'confirm_create_user' && $confirm == 'yes' && $user->rights->user->user->creer) { // Recuperation contact actuel $result = $object->fetch($id); - if ($result > 0) - { + if ($result > 0) { $db->begin(); // Creation user $nuser = new User($db); $result = $nuser->create_from_contact($object, GETPOST("login")); // Do not use GETPOST(alpha) - if ($result > 0) - { + if ($result > 0) { $result2 = $nuser->setPassword($user, GETPOST("password"), 0, 0, 1); // Do not use GETPOST(alpha) - if ($result2) - { + if ($result2) { $db->commit(); } else { $error = $nuser->error; $errors = $nuser->errors; @@ -146,11 +144,9 @@ if (empty($reshook)) // Confirmation desactivation - if ($action == 'disable') - { + if ($action == 'disable') { $object->fetch($id); - if ($object->setstatus(0) < 0) - { + if ($object->setstatus(0) < 0) { setEventMessages($object->error, $object->errors, 'errors'); } else { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); @@ -159,11 +155,9 @@ if (empty($reshook)) } // Confirmation activation - if ($action == 'enable') - { + if ($action == 'enable') { $object->fetch($id); - if ($object->setstatus(1) < 0) - { + if ($object->setstatus(1) < 0) { setEventMessages($object->error, $object->errors, 'errors'); } else { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); @@ -172,11 +166,12 @@ if (empty($reshook)) } // Add contact - if ($action == 'add' && $user->rights->societe->contact->creer) - { + if ($action == 'add' && $user->rights->societe->contact->creer) { $db->begin(); - if ($canvas) $object->canvas = $canvas; + if ($canvas) { + $object->canvas = $canvas; + } $object->entity = (GETPOSTISSET('entity') ?GETPOST('entity', 'int') : $conf->entity); $object->socid = GETPOST("socid", 'int'); @@ -221,8 +216,7 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) - { + if ($ret < 0) { $error++; $action = 'create'; } @@ -233,8 +227,7 @@ if (empty($reshook)) $action = 'create'; } - if (!empty($object->email) && !isValidEMail($object->email)) - { + if (!empty($object->email) && !isValidEMail($object->email)) { $langs->load("errors"); $error++; $errors[] = $langs->trans("ErrorBadEMail", GETPOST('email', 'alpha')); @@ -279,11 +272,13 @@ if (empty($reshook)) } } - if (empty($error) && $id > 0) - { + if (empty($error) && $id > 0) { $db->commit(); - if (!empty($backtopage)) $url = $backtopage; - else $url = 'card.php?id='.$id; + if (!empty($backtopage)) { + $url = $backtopage; + } else { + $url = 'card.php?id='.$id; + } header("Location: ".$url); exit; } else { @@ -291,8 +286,7 @@ if (empty($reshook)) } } - if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->contact->supprimer) - { + if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->societe->contact->supprimer) { $result = $object->fetch($id); $object->oldcopy = clone $object; @@ -313,10 +307,8 @@ if (empty($reshook)) } } - if ($action == 'update' && empty($cancel) && $user->rights->societe->contact->creer) - { - if (!GETPOST("lastname", 'alpha')) - { + if ($action == 'update' && empty($cancel) && $user->rights->societe->contact->creer) { + if (!GETPOST("lastname", 'alpha')) { $error++; $errors = array($langs->trans("ErrorFieldRequired", $langs->transnoentities("Name").' / '.$langs->transnoentities("Label"))); $action = 'edit'; } @@ -327,16 +319,14 @@ if (empty($reshook)) $action = 'edit'; } - if (!empty(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL)) && !isValidEMail(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL))) - { + if (!empty(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL)) && !isValidEMail(GETPOST('email', 'custom', 0, FILTER_SANITIZE_EMAIL))) { $langs->load("errors"); $error++; $errors[] = $langs->trans("ErrorBadEMail", GETPOST('email', 'alpha')); $action = 'edit'; } - if (!$error) - { + if (!$error) { $contactid = GETPOST("contactid", 'int'); $object->fetch($contactid); $object->fetchRoles($contactid); @@ -344,27 +334,22 @@ if (empty($reshook)) // Photo save $dir = $conf->societe->multidir_output[$object->entity]."/contact/".$object->id."/photos"; $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); - if (GETPOST('deletephoto') && $object->photo) - { + if (GETPOST('deletephoto') && $object->photo) { $fileimg = $dir.'/'.$object->photo; $dirthumbs = $dir.'/thumbs'; dol_delete_file($fileimg); dol_delete_dir_recursive($dirthumbs); $object->photo = ''; } - if ($file_OK) - { - if (image_format_supported($_FILES['photo']['name']) > 0) - { + if ($file_OK) { + if (image_format_supported($_FILES['photo']['name']) > 0) { dol_mkdir($dir); - if (@is_dir($dir)) - { + if (@is_dir($dir)) { $newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']); $result = dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1); - if (!$result > 0) - { + if (!$result > 0) { $errors[] = "ErrorFailedToSaveFile"; } else { $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); @@ -377,8 +362,7 @@ if (empty($reshook)) $errors[] = "ErrorBadImageFormat"; } } else { - switch ($_FILES['photo']['error']) - { + switch ($_FILES['photo']['error']) { case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form $errors[] = "ErrorFileSizeTooLarge"; @@ -433,10 +417,11 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { $result = $object->update($contactid, $user); if ($result > 0) { @@ -445,8 +430,7 @@ if (empty($reshook)) $object->setCategories($categories); // Update mass emailing flag into table mailing_unsubscribe - if (GETPOSTISSET('no_email') && $object->email) - { + if (GETPOSTISSET('no_email') && $object->email) { $no_email = GETPOST('no_email', 'int'); $result=$object->setNoEmail($no_email); if ($result<0) { @@ -465,31 +449,31 @@ if (empty($reshook)) } } - if (!$error && empty($errors)) - { - if (!empty($backtopage)) - { - header("Location: ".$backtopage); - exit; - } + if (!$error && empty($errors)) { + if (!empty($backtopage)) { + header("Location: ".$backtopage); + exit; + } } } - if ($action == 'setprospectcontactlevel' && $user->rights->societe->contact->creer) - { + if ($action == 'setprospectcontactlevel' && $user->rights->societe->contact->creer) { $object->fetch($id); $object->fk_prospectlevel = GETPOST('prospect_contact_level_id', 'alpha'); $result = $object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // set communication status - if ($action == 'setstcomm') - { + if ($action == 'setstcomm') { $object->fetch($id); $object->stcomm_id = dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcommcontact'); $result = $object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Actions to send emails @@ -506,7 +490,9 @@ if (empty($reshook)) $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) { + $title = $object->lastname; +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); @@ -515,24 +501,23 @@ $formcompany = new FormCompany($db); $countrynotdefined = $langs->trans("ErrorSetACountryFirst").' ('.$langs->trans("SeeAbove").')'; -if ($socid > 0) -{ +if ($socid > 0) { $objsoc = new Societe($db); $objsoc->fetch($socid); } -if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) -{ +if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) { // ----------------------------------------- // When used with CANVAS // ----------------------------------------- - if (empty($object->error) && $id) - { - $object = new Contact($db); - $result = $object->fetch($id); - if ($result <= 0) dol_print_error('', $object->error); - } - $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates + if (empty($object->error) && $id) { + $object = new Contact($db); + $result = $object->fetch($id); + if ($result <= 0) { + dol_print_error('', $object->error); + } + } + $objcanvas->assign_values($action, $object->id, $object->ref); // Set value for templates $objcanvas->display_canvas($action); // Show template } else { // ----------------------------------------- @@ -540,20 +525,17 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // ----------------------------------------- // Confirm deleting contact - if ($user->rights->societe->contact->supprimer) - { - if ($action == 'delete') - { + if ($user->rights->societe->contact->supprimer) { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$id.($backtopage ? '&backtopage='.$backtopage : ''), $langs->trans("DeleteContact"), $langs->trans("ConfirmDeleteContact"), "confirm_delete", '', 0, 1); } } /* - * Onglets - */ + * Onglets + */ $head = array(); - if ($id > 0) - { + if ($id > 0) { // Si edition contact deja existant $object = new Contact($db); $res = $object->fetch($id, $user); @@ -569,21 +551,18 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); } - if ($user->rights->societe->contact->creer) - { - if ($action == 'create') - { + if ($user->rights->societe->contact->creer) { + if ($action == 'create') { /* - * Fiche en mode creation - */ + * Fiche en mode creation + */ $object->canvas = $canvas; $object->state_id = GETPOST("state_id"); // We set country_id, country_code and label for the selected country $object->country_id = $_POST["country_id"] ?GETPOST("country_id") : (empty($objsoc->country_id) ? $mysoc->country_id : $objsoc->country_id); - if ($object->country_id) - { + if ($object->country_id) { $tmparray = getCountry($object->country_id, 'all'); $object->country_code = $tmparray['code']; $object->country = $tmparray['label']; @@ -596,8 +575,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Show errors dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors); - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print "\n".''."\n"; } - if (!GETPOSTISSET("no_email") && !empty($object->email)) - { + if (!GETPOSTISSET("no_email") && !empty($object->email)) { $result=$object->getNoEmail(); if ($result<0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -829,8 +820,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $parameters = array('socid' => $socid, 'objsoc' => $objsoc, 'colspan' => ' colspan="3"', 'cols' => 3); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } @@ -846,8 +836,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Date To Birth print ''; print ''; } - if (!empty($conf->propal->enabled)) - { + if (!empty($conf->propal->enabled)) { print ''; } - if (!empty($conf->contrat->enabled)) - { + if (!empty($conf->contrat->enabled)) { print ''; } - if (!empty($conf->facture->enabled)) - { + if (!empty($conf->facture->enabled)) { print ''; @@ -1182,12 +1160,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Login Dolibarr print ''; // Photo @@ -1199,7 +1178,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print "
\n"; } print '
'; $form = new Form($db); - if ($object->birthday) - { + if ($object->birthday) { print $form->selectDate($object->birthday, 'birthday', 0, 0, 0, "perso", 1, 0); } else { print $form->selectDate('', 'birthday', 0, 0, 1, "perso", 1, 0); @@ -855,8 +844,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ': '; - if ($object->birthday_alert) - { + if ($object->birthday_alert) { print ''; } else { print ''; @@ -870,8 +858,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '
'; print ''; - if (!empty($backtopage)) - { + if (!empty($backtopage)) { print '     '; print ''; } else { @@ -883,12 +870,11 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ""; } elseif ($action == 'edit' && !empty($id)) { /* - * Fiche en mode edition - */ + * Fiche en mode edition + */ // We set country_id, and country_code label of the chosen country - if (GETPOSTISSET("country_id") || $object->country_id) - { + if (GETPOSTISSET("country_id") || $object->country_id) { $tmparray = getCountry($object->country_id, 'all'); $object->country_code = $tmparray['code']; $object->country = $tmparray['label']; @@ -900,8 +886,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Show errors dol_htmloutput_errors(is_numeric($error) ? '' : $error, $errors); - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print "\n".''."\n"; } - if (!GETPOSTISSET("no_email") && !empty($object->email)) - { + if (!GETPOSTISSET("no_email") && !empty($object->email)) { $result=$object->getNoEmail(); if ($result<0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -1145,36 +1128,31 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $parameters = array('colspan' => ' colspan="3"', 'cols'=> '3'); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit', $parameters); } $object->load_ref_elements(); - if (!empty($conf->commande->enabled)) - { + if (!empty($conf->commande->enabled)) { print '
'.$langs->trans("ContactForOrders").''; print $object->ref_commande ? $object->ref_commande : $langs->trans("NoContactForAnyOrder"); print '
'.$langs->trans("ContactForProposals").''; print $object->ref_propal ? $object->ref_propal : $langs->trans("NoContactForAnyProposal"); print '
'.$langs->trans("ContactForContracts").''; print $object->ref_contrat ? $object->ref_contrat : $langs->trans("NoContactForAnyContract"); print '
'.$langs->trans("ContactForInvoices").''; print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice"); print '
'.$langs->trans("DolibarrLogin").''; - if ($object->user_id) - { + if ($object->user_id) { $dolibarr_user = new User($db); $result = $dolibarr_user->fetch($object->user_id); print $dolibarr_user->getLoginUrl(1); - } else print $langs->trans("NoDolibarrAccess"); + } else { + print $langs->trans("NoDolibarrAccess"); + } print '
'; - if ($object->photo) print ''; + if ($object->photo) { + print ''; + } //print ''; print ''; print '
'.$langs->trans("Delete").'

'.$langs->trans("Delete").'

'.$langs->trans("PhotoFile").'
'; @@ -1226,8 +1207,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $action = 'presend'; } - if (!empty($id) && $action != 'edit' && $action != 'create') - { + if (!empty($id) && $action != 'edit' && $action != 'create') { $objsoc = new Societe($db); // View mode @@ -1237,15 +1217,13 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print dol_get_fiche_head($head, 'card', $title, -1, 'contact'); - if ($action == 'create_user') - { + if ($action == 'create_user') { // Full firstname and lastname separated with a dot : firstname.lastname include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $login = dol_buildlogin($object->lastname, $object->firstname); $generated_password = ''; - if (!$ldap_sid) // TODO ldap_sid ? - { + if (!$ldap_sid) { // TODO ldap_sid ? require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $generated_password = getRandomPassword(false); } @@ -1258,10 +1236,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) //array('label' => $form->textwithpicto($langs->trans("Type"),$langs->trans("InternalExternalDesc")), 'type' => 'select', 'name' => 'intern', 'default' => 1, 'values' => array(0=>$langs->trans('Internal'),1=>$langs->trans('External'))) ); $text = $langs->trans("ConfirmCreateContact").'
'; - if (!empty($conf->societe->enabled)) - { - if ($object->socid > 0) $text .= $langs->trans("UserWillBeExternalUser"); - else $text .= $langs->trans("UserWillBeInternalUser"); + if (!empty($conf->societe->enabled)) { + if ($object->socid > 0) { + $text .= $langs->trans("UserWillBeExternalUser"); + } else { + $text .= $langs->trans("UserWillBeInternalUser"); + } } print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CreateDolibarrLogin"), $text, "confirm_create_user", $formquestion, 'yes'); } @@ -1269,13 +1249,15 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
'; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1, 'contact'); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1, 'contact'); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
'; @@ -1297,16 +1279,14 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''.$langs->trans("PostOrFunction").''.$object->poste.''; // Email - if (!empty($conf->mailing->enabled)) - { + if (!empty($conf->mailing->enabled)) { $langs->load("mails"); print ''.$langs->trans("NbOfEMailingsSend").''; print ''.$object->getNbOfEMailings().''; } // Unsubscribe opt-out - if (!empty($conf->mailing->enabled)) - { + if (!empty($conf->mailing->enabled)) { $result=$object->getNoEmail(); if ($result<0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -1324,8 +1304,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->fetch_thirdparty(); if (!empty($conf->global->THIRDPARTY_ENABLE_PROSPECTION_ON_ALTERNATIVE_ADRESSES)) { - if ($object->thirdparty->client == 2 || $object->thirdparty->client == 3) - { + if ($object->thirdparty->client == 2 || $object->thirdparty->client == 3) { print '
'; print '
'; @@ -1336,7 +1315,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print ''; + if ($action != 'editlevel' && $user->rights->societe->contact->creer) { + print ''; + } print '
'; print $langs->trans('ProspectLevel'); print ''; - if ($action != 'editlevel' && $user->rights->societe->contact->creer) print 'id.'">'.img_edit($langs->trans('Modify'), 1).'id.'">'.img_edit($langs->trans('Modify'), 1).'
'; print ''; if ($action == 'editlevel') { @@ -1354,8 +1335,12 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) print '
'; foreach ($object->cacheprospectstatus as $key => $val) { $titlealt = 'default'; - if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label']; - if ($object->stcomm_id != $val['id']) print ''.img_action($titlealt, $val['code'], $val['picto']).''; + if (!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 '
'; @@ -1391,45 +1376,48 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $object->load_ref_elements(); - if (!empty($conf->propal->enabled)) - { + if (!empty($conf->propal->enabled)) { print ''.$langs->trans("ContactForProposals").''; print $object->ref_propal ? $object->ref_propal : $langs->trans("NoContactForAnyProposal"); print ''; } - if (!empty($conf->commande->enabled) || !empty($conf->expedition->enabled)) - { + if (!empty($conf->commande->enabled) || !empty($conf->expedition->enabled)) { print ''; - if (!empty($conf->expedition->enabled)) { print $langs->trans("ContactForOrdersOrShipments"); } else print $langs->trans("ContactForOrders"); + if (!empty($conf->expedition->enabled)) { + print $langs->trans("ContactForOrdersOrShipments"); + } else { + print $langs->trans("ContactForOrders"); + } print ''; $none = $langs->trans("NoContactForAnyOrder"); - if (!empty($conf->expedition->enabled)) { $none = $langs->trans("NoContactForAnyOrderOrShipments"); } + if (!empty($conf->expedition->enabled)) { + $none = $langs->trans("NoContactForAnyOrderOrShipments"); + } print $object->ref_commande ? $object->ref_commande : $none; print ''; } - if (!empty($conf->contrat->enabled)) - { + if (!empty($conf->contrat->enabled)) { print ''.$langs->trans("ContactForContracts").''; print $object->ref_contrat ? $object->ref_contrat : $langs->trans("NoContactForAnyContract"); print ''; } - if (!empty($conf->facture->enabled)) - { + if (!empty($conf->facture->enabled)) { print ''.$langs->trans("ContactForInvoices").''; print $object->ref_facturation ? $object->ref_facturation : $langs->trans("NoContactForAnyInvoice"); print ''; } print ''.$langs->trans("DolibarrLogin").''; - if ($object->user_id) - { + if ($object->user_id) { $dolibarr_user = new User($db); $result = $dolibarr_user->fetch($object->user_id); print $dolibarr_user->getLoginUrl(1); - } else print $langs->trans("NoDolibarrAccess"); + } else { + print $langs->trans("NoDolibarrAccess"); + } print ''; print ''; @@ -1452,11 +1440,9 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook) && $action != 'presend') - { + if (empty($reshook) && $action != 'presend') { if (empty($user->socid)) { - if (!empty($object->email)) - { + if (!empty($object->email)) { $langs->load("mails"); print ''; } else { @@ -1465,30 +1451,25 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) } } - if ($user->rights->societe->contact->creer) - { + if ($user->rights->societe->contact->creer) { print ''.$langs->trans('Modify').''; } - if (!$object->user_id && $user->rights->user->user->creer) - { + if (!$object->user_id && $user->rights->user->user->creer) { print ''.$langs->trans("CreateDolibarrLogin").''; } // Activer - if ($object->statut == 0 && $user->rights->societe->contact->creer) - { + if ($object->statut == 0 && $user->rights->societe->contact->creer) { print ''.$langs->trans("Reactivate").''; } // Desactiver - if ($object->statut == 1 && $user->rights->societe->contact->creer) - { + if ($object->statut == 1 && $user->rights->societe->contact->creer) { print ''.$langs->trans("DisableUser").''; } // Delete - if ($user->rights->societe->contact->supprimer) - { + if ($user->rights->societe->contact->supprimer) { print ''.$langs->trans('Delete').''; } } @@ -1500,8 +1481,7 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '
'; print '
'; diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 1d2cb3355a5..62d0d444c3e 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -473,40 +473,35 @@ class Contact extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."socpeople"); - if (!$error) - { + if (!$error) { $result = $this->update($this->id, $user, 1, 'add'); // This include updateRoles(), ... - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $this->db->lasterror(); } } - if (!$error) - { + if (!$error) { $result = $this->update_perso($this->id, $user, 1); // TODO Remove function update_perso, should be same than update - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $this->db->lasterror(); } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('CONTACT_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -558,13 +553,20 @@ class Contact extends CommonObject $this->town = (empty($this->town) ? '' : trim($this->town)); $this->setUpperOrLowerCase(); $this->country_id = ($this->country_id > 0 ? $this->country_id : $this->country_id); - if (empty($this->statut)) $this->statut = 0; - if (empty($this->civility_code) && !is_numeric($this->civility_id)) $this->civility_code = $this->civility_id; // For backward compatibility + if (empty($this->statut)) { + $this->statut = 0; + } + if (empty($this->civility_code) && !is_numeric($this->civility_id)) { + $this->civility_code = $this->civility_id; // For backward compatibility + } $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET "; - if ($this->socid > 0) $sql .= " fk_soc='".$this->db->escape($this->socid)."',"; - elseif ($this->socid == -1) $sql .= " fk_soc=null,"; + if ($this->socid > 0) { + $sql .= " fk_soc='".$this->db->escape($this->socid)."',"; + } elseif ($this->socid == -1) { + $sql .= " fk_soc=null,"; + } $sql .= " civility='".$this->db->escape($this->civility_code)."'"; $sql .= ", lastname='".$this->db->escape($this->lastname)."'"; $sql .= ", firstname='".$this->db->escape($this->firstname)."'"; @@ -586,8 +588,7 @@ class Contact extends CommonObject $sql .= ", phone_mobile = ".(isset($this->phone_mobile) ? "'".$this->db->escape($this->phone_mobile)."'" : "null"); $sql .= ", priv = '".$this->db->escape($this->priv)."'"; $sql .= ", fk_prospectcontactlevel = '".$this->db->escape($this->fk_prospectlevel)."'"; - if (isset($this->stcomm_id)) - { + if (isset($this->stcomm_id)) { $sql .= ", fk_stcommcontact = ".($this->stcomm_id > 0 || $this->stcomm_id == -1 ? $this->stcomm_id : "0"); } $sql .= ", statut = ".$this->db->escape($this->statut); @@ -598,8 +599,7 @@ class Contact extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { unset($this->country_code); unset($this->country); unset($this->state_code); @@ -608,25 +608,21 @@ class Contact extends CommonObject $action = 'update'; // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } if (!$error) { $result = $this->updateRoles(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && $this->user_id > 0) - { + if (!$error && $this->user_id > 0) { // If contact is linked to a user $tmpobj = new User($this->db); $tmpobj->fetch($this->user_id); @@ -685,14 +681,18 @@ class Contact extends CommonObject // } if ($usermustbemodified) { $result = $tmpobj->update($user, 0, 1, 1, 1); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } } } if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTACT_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -759,34 +759,69 @@ class Contact extends CommonObject $this->fullname = $this->getFullName($langs); // Fields - if ($this->fullname && !empty($conf->global->LDAP_CONTACT_FIELD_FULLNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FULLNAME] = $this->fullname; - if ($this->lastname && !empty($conf->global->LDAP_CONTACT_FIELD_NAME)) $info[$conf->global->LDAP_CONTACT_FIELD_NAME] = $this->lastname; - if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname; + if ($this->fullname && !empty($conf->global->LDAP_CONTACT_FIELD_FULLNAME)) { + $info[$conf->global->LDAP_CONTACT_FIELD_FULLNAME] = $this->fullname; + } + if ($this->lastname && !empty($conf->global->LDAP_CONTACT_FIELD_NAME)) { + $info[$conf->global->LDAP_CONTACT_FIELD_NAME] = $this->lastname; + } + if ($this->firstname && !empty($conf->global->LDAP_CONTACT_FIELD_FIRSTNAME)) { + $info[$conf->global->LDAP_CONTACT_FIELD_FIRSTNAME] = $this->firstname; + } - if ($this->poste) $info["title"] = $this->poste; + if ($this->poste) { + $info["title"] = $this->poste; + } if ($this->socid > 0) { $soc = new Societe($this->db); $soc->fetch($this->socid); $info[$conf->global->LDAP_CONTACT_FIELD_COMPANY] = $soc->name; - if ($soc->client == 1) $info["businessCategory"] = "Customers"; - if ($soc->client == 2) $info["businessCategory"] = "Prospects"; - if ($soc->fournisseur == 1) $info["businessCategory"] = "Suppliers"; + if ($soc->client == 1) { + $info["businessCategory"] = "Customers"; + } + if ($soc->client == 2) { + $info["businessCategory"] = "Prospects"; + } + if ($soc->fournisseur == 1) { + $info["businessCategory"] = "Suppliers"; + } + } + if ($this->address && !empty($conf->global->LDAP_CONTACT_FIELD_ADDRESS)) { + $info[$conf->global->LDAP_CONTACT_FIELD_ADDRESS] = $this->address; + } + if ($this->zip && !empty($conf->global->LDAP_CONTACT_FIELD_ZIP)) { + $info[$conf->global->LDAP_CONTACT_FIELD_ZIP] = $this->zip; + } + if ($this->town && !empty($conf->global->LDAP_CONTACT_FIELD_TOWN)) { + $info[$conf->global->LDAP_CONTACT_FIELD_TOWN] = $this->town; + } + if ($this->country_code && !empty($conf->global->LDAP_CONTACT_FIELD_COUNTRY)) { + $info[$conf->global->LDAP_CONTACT_FIELD_COUNTRY] = $this->country_code; + } + if ($this->phone_pro && !empty($conf->global->LDAP_CONTACT_FIELD_PHONE)) { + $info[$conf->global->LDAP_CONTACT_FIELD_PHONE] = $this->phone_pro; + } + if ($this->phone_perso && !empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) { + $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso; + } + if ($this->phone_mobile && !empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) { + $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile; + } + if ($this->fax && !empty($conf->global->LDAP_CONTACT_FIELD_FAX)) { + $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax; + } + if ($this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE)) { + $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype; + } + if ($this->note_private && !empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) { + $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); + } + if ($this->email && !empty($conf->global->LDAP_CONTACT_FIELD_MAIL)) { + $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email; } - if ($this->address && !empty($conf->global->LDAP_CONTACT_FIELD_ADDRESS)) $info[$conf->global->LDAP_CONTACT_FIELD_ADDRESS] = $this->address; - if ($this->zip && !empty($conf->global->LDAP_CONTACT_FIELD_ZIP)) $info[$conf->global->LDAP_CONTACT_FIELD_ZIP] = $this->zip; - if ($this->town && !empty($conf->global->LDAP_CONTACT_FIELD_TOWN)) $info[$conf->global->LDAP_CONTACT_FIELD_TOWN] = $this->town; - if ($this->country_code && !empty($conf->global->LDAP_CONTACT_FIELD_COUNTRY)) $info[$conf->global->LDAP_CONTACT_FIELD_COUNTRY] = $this->country_code; - if ($this->phone_pro && !empty($conf->global->LDAP_CONTACT_FIELD_PHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_PHONE] = $this->phone_pro; - if ($this->phone_perso && !empty($conf->global->LDAP_CONTACT_FIELD_HOMEPHONE)) $info[$conf->global->LDAP_CONTACT_FIELD_HOMEPHONE] = $this->phone_perso; - if ($this->phone_mobile && !empty($conf->global->LDAP_CONTACT_FIELD_MOBILE)) $info[$conf->global->LDAP_CONTACT_FIELD_MOBILE] = $this->phone_mobile; - if ($this->fax && !empty($conf->global->LDAP_CONTACT_FIELD_FAX)) $info[$conf->global->LDAP_CONTACT_FIELD_FAX] = $this->fax; - if ($this->skype && !empty($conf->global->LDAP_CONTACT_FIELD_SKYPE)) $info[$conf->global->LDAP_CONTACT_FIELD_SKYPE] = $this->skype; - if ($this->note_private && !empty($conf->global->LDAP_CONTACT_FIELD_DESCRIPTION)) $info[$conf->global->LDAP_CONTACT_FIELD_DESCRIPTION] = dol_string_nohtmltag($this->note_private, 2); - if ($this->email && !empty($conf->global->LDAP_CONTACT_FIELD_MAIL)) $info[$conf->global->LDAP_CONTACT_FIELD_MAIL] = $this->email; - if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') - { + if ($conf->global->LDAP_SERVER_TYPE == 'egroupware') { $info["objectclass"][4] = "phpgwContact"; // compatibilite egroupware $info['uidnumber'] = $this->id; @@ -805,8 +840,12 @@ class Contact extends CommonObject $info["phpgwContactOwner"] = $this->egroupware_id; - if ($this->email) $info["rfc822Mailbox"] = $this->email; - if ($this->phone_mobile) $info["phpgwCellTelephoneNumber"] = $this->phone_mobile; + if ($this->email) { + $info["rfc822Mailbox"] = $this->email; + } + if ($this->phone_mobile) { + $info["phpgwCellTelephoneNumber"] = $this->phone_mobile; + } } return $info; @@ -834,13 +873,14 @@ class Contact extends CommonObject $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET"; $sql .= " birthday=".($this->birthday ? "'".$this->db->idate($this->birthday)."'" : "null"); $sql .= ", photo = ".($this->photo ? "'".$this->db->escape($this->photo)."'" : "null"); - if ($user) $sql .= ", fk_user_modif=".$user->id; + if ($user) { + $sql .= ", fk_user_modif=".$user->id; + } $sql .= " WHERE rowid=".$this->db->escape($id); dol_syslog(get_class($this)."::update_perso this->birthday=".$this->birthday." -", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = $this->db->lasterror(); } @@ -875,7 +915,9 @@ class Contact extends CommonObject if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTACT_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -906,8 +948,7 @@ class Contact extends CommonObject dol_syslog(get_class($this)."::fetch id=".$id." ref_ext=".$ref_ext." email=".$email, LOG_DEBUG); - if (empty($id) && empty($ref_ext) && empty($email)) - { + if (empty($id) && empty($ref_ext) && empty($email)) { $this->error = 'BadParameter'; return -1; } @@ -936,8 +977,9 @@ class Contact extends CommonObject $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON c.rowid = u.fk_socpeople"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcommcontact as st ON c.fk_stcommcontact = st.id'; - if ($id) $sql .= " WHERE c.rowid = ".((int) $id); - else { + if ($id) { + $sql .= " WHERE c.rowid = ".((int) $id); + } else { $sql .= " WHERE c.entity IN (".getEntity($this->element).")"; if ($ref_ext) { $sql .= " AND c.ref_ext = '".$this->db->escape($ref_ext)."'"; @@ -948,17 +990,14 @@ class Contact extends CommonObject } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 1) - { + if ($num > 1) { $this->error = 'Fetch found several records. Rename one of contact to avoid duplicate.'; dol_syslog($this->error, LOG_ERR); return 2; - } elseif ($num) // $num = 1 - { + } elseif ($num) { // $num = 1 $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -1030,10 +1069,8 @@ class Contact extends CommonObject $sql .= " WHERE u.fk_socpeople = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $uobj = $this->db->fetch_object($resql); $this->user_id = $uobj->rowid; @@ -1049,17 +1086,14 @@ class Contact extends CommonObject $this->fetch_optionals(); // Load also alerts of this user - if ($user) - { + if ($user) { $sql = "SELECT fk_user"; $sql .= " FROM ".MAIN_DB_PREFIX."user_alert"; $sql .= " WHERE fk_user = ".$user->id." AND fk_contact = ".$this->db->escape($id); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->birthday_alert = 1; @@ -1102,11 +1136,9 @@ class Contact extends CommonObject { unset($this->gender); - if (in_array($this->civility_id, array('MR')) || in_array($this->civility_code, array('MR'))) - { + if (in_array($this->civility_id, array('MR')) || in_array($this->civility_code, array('MR'))) { $this->gender = 'man'; - } elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE'))) - { + } elseif (in_array($this->civility_id, array('MME', 'MLE')) || in_array($this->civility_code, array('MME', 'MLE'))) { $this->gender = 'woman'; } } @@ -1135,16 +1167,18 @@ class Contact extends CommonObject dol_syslog(get_class($this)."::load_ref_elements", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { - if ($obj->nb) - { - if ($obj->element == 'facture') $this->ref_facturation = $obj->nb; - elseif ($obj->element == 'contrat') $this->ref_contrat = $obj->nb; - elseif ($obj->element == 'commande') $this->ref_commande = $obj->nb; - elseif ($obj->element == 'propal') $this->ref_propal = $obj->nb; + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { + if ($obj->nb) { + if ($obj->element == 'facture') { + $this->ref_facturation = $obj->nb; + } elseif ($obj->element == 'contrat') { + $this->ref_contrat = $obj->nb; + } elseif ($obj->element == 'commande') { + $this->ref_commande = $obj->nb; + } elseif ($obj->element == 'propal') { + $this->ref_propal = $obj->nb; + } } } $this->db->free($resql); @@ -1169,8 +1203,7 @@ class Contact extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { // Get all rowid of element_contact linked to a type that is link to llx_socpeople $sql = "SELECT ec.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."element_contact ec,"; @@ -1180,21 +1213,18 @@ class Contact extends CommonObject $sql .= " AND tc.source='external'"; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num && !$error) - { + while ($i < $num && !$error) { $obj = $this->db->fetch_object($resql); $sqldel = "DELETE FROM ".MAIN_DB_PREFIX."element_contact"; $sqldel .= " WHERE rowid = ".$obj->rowid; dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sqldel); - if (!$result) - { + if (!$result) { $error++; $this->error = $this->db->error().' sql='.$sqldel; } @@ -1207,56 +1237,48 @@ class Contact extends CommonObject } } - if (!$error) - { + if (!$error) { // Remove Roles $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error .= $this->db->lasterror(); $errorflag = -1; } } - if (!$error) - { + if (!$error) { // Remove Roles $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_socpeople = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error .= $this->db->lasterror(); $errorflag = -1; } } - if (!$error) - { + if (!$error) { // Remove category $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_contact WHERE fk_socpeople = ".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error .= $this->db->lasterror(); $errorflag = -1; } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople"; $sql .= " WHERE rowid=".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $error++; $this->error = $this->db->error().' sql='.$sql; } @@ -1266,19 +1288,21 @@ class Contact extends CommonObject if (!$error) { // For avoid conflicts if trigger used $result = $this->deleteExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTACT_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1303,10 +1327,8 @@ class Contact extends CommonObject $sql .= " WHERE c.rowid = ".$this->db->escape($id); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -1346,8 +1368,7 @@ class Contact extends CommonObject $sql .= " AND m.entity IN (".getEntity($this->element).") AND mc.statut NOT IN (-1,0)"; // -1 error, 0 not sent, 1 sent with success $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $nb = $obj->nb; @@ -1377,8 +1398,7 @@ class Contact extends CommonObject $result = ''; $label = ''; - if (!empty($this->photo) && class_exists('Form')) - { + if (!empty($this->photo) && class_exists('Form')) { $label .= '
'; $label .= Form::showphoto('contact', $this, 0, 40, 0, '', 'mini', 0); // Important, we must force height so image will have height tags and if image is inside a tooltip, the tooltip manager can calculate height and position correctly the tooltip. $label .= '
'; @@ -1388,67 +1408,83 @@ class Contact extends CommonObject $label .= ' '.$this->getLibStatut(4); $label .= '
'.$langs->trans("Name").': '.$this->getFullName($langs); //if ($this->civility_id) $label.= '
' . $langs->trans("Civility") . ': '.$this->civility_id; // TODO Translate cibilty_id code - if (!empty($this->poste)) $label .= '
'.$langs->trans("Poste").': '.$this->poste; + if (!empty($this->poste)) { + $label .= '
'.$langs->trans("Poste").': '.$this->poste; + } $label .= '
'.$langs->trans("EMail").': '.$this->email; $phonelist = array(); $country_code = empty($this->country_code) ? '': $this->country_code; - if ($this->phone_pro) $phonelist[] = dol_print_phone($this->phone_pro, $country_code, $this->id, 0, '', ' ', 'phone'); - if ($this->phone_mobile) $phonelist[] = dol_print_phone($this->phone_mobile, $country_code, $this->id, 0, '', ' ', 'mobile'); - if ($this->phone_perso) $phonelist[] = dol_print_phone($this->phone_perso, $country_code, $this->id, 0, '', ' ', 'phone'); + if ($this->phone_pro) { + $phonelist[] = dol_print_phone($this->phone_pro, $country_code, $this->id, 0, '', ' ', 'phone'); + } + if ($this->phone_mobile) { + $phonelist[] = dol_print_phone($this->phone_mobile, $country_code, $this->id, 0, '', ' ', 'mobile'); + } + if ($this->phone_perso) { + $phonelist[] = dol_print_phone($this->phone_perso, $country_code, $this->id, 0, '', ' ', 'phone'); + } $label .= '
'.$langs->trans("Phone").': '.implode(' ', $phonelist); $label .= '
'.$langs->trans("Address").': '.dol_format_address($this, 1, ' ', $langs); $url = DOL_URL_ROOT.'/contact/card.php?id='.$this->id; - if ($option !== 'nolink') - { + if ($option !== 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } } $url .= $moreparam; $linkclose = ""; if (empty($notooltip)) { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowContact"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } - $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; - $linkclose .= ' class="classfortooltip"'; + $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; + $linkclose .= ' class="classfortooltip"'; - /* - $hookmanager->initHooks(array('contactdao')); - $parameters=array('id'=>$this->id); - $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $linkclose = $hookmanager->resPrint; - */ + /* + $hookmanager->initHooks(array('contactdao')); + $parameters=array('id'=>$this->id); + $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks + if ($reshook > 0) $linkclose = $hookmanager->resPrint; + */ } $linkstart = ''; $linkend = ''; - if ($option == 'xxx') - { + if ($option == 'xxx') { $linkstart = ''; $linkend = ''; } $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($maxlen ?dol_trunc($this->getFullName($langs), $maxlen) : $this->getFullName($langs)); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= ($maxlen ?dol_trunc($this->getFullName($langs), $maxlen) : $this->getFullName($langs)); + } $result .= $linkend; global $action; $hookmanager->initHooks(array('contactdao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -1463,7 +1499,9 @@ class Contact extends CommonObject global $langs; $code = ($this->civility_code ? $this->civility_code : (!empty($this->civility_id) ? $this->civility : (!empty($this->civilite) ? $this->civilite : ''))); - if (empty($code)) return ''; + if (empty($code)) { + return ''; + } $langs->load("dict"); return $langs->getLabelFromKey($this->db, "Civility".$code, "c_civility", "code", "label", $code); @@ -1507,7 +1545,9 @@ class Contact extends CommonObject ); $statusType = 'status4'; - if ($status == 0 || $status == 5) $statusType = 'status5'; + if ($status == 0 || $status == 5) { + $statusType = 'status5'; + } $label = $langs->trans($labelStatus[$status]); $labelshort = $langs->trans($labelStatusShort[$status]); @@ -1527,8 +1567,11 @@ class Contact extends CommonObject { // phpcs:enable global $langs; - if ($status == '1') return $langs->trans('ContactPrivate'); - else return $langs->trans('ContactPublic'); + if ($status == '1') { + return $langs->trans('ContactPrivate'); + } else { + return $langs->trans('ContactPublic'); + } } @@ -1547,7 +1590,9 @@ class Contact extends CommonObject $resql = $this->db->query($sql); if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) $socid = $obj->rowid; + if ($obj) { + $socid = $obj->rowid; + } } // Initialise parameters @@ -1592,8 +1637,11 @@ class Contact extends CommonObject $error = 0; // Check parameters - if ($this->statut == $status) return 0; - else $this->statut = $status; + if ($this->statut == $status) { + return 0; + } else { + $this->statut = $status; + } $this->db->begin(); @@ -1604,16 +1652,16 @@ class Contact extends CommonObject $result = $this->db->query($sql); dol_syslog(get_class($this)."::setstatus", LOG_DEBUG); - if ($result) - { + if ($result) { // Call trigger $result = $this->call_trigger('CONTACT_ENABLEDISABLE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if ($error) - { + if ($error) { $this->db->rollback(); return -$error; } else { @@ -1725,12 +1773,10 @@ class Contact extends CommonObject dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $tab[] = array('fk_socpeople'=>$obj->id, 'type_contact'=>$obj->fk_c_type_contact); @@ -1758,7 +1804,9 @@ class Contact extends CommonObject $error = 0; - if (!isset($this->roles)) return; // Avoid to loose roles when property not set + if (!isset($this->roles)) { + return; // Avoid to loose roles when property not set + } $this->db->begin(); @@ -1800,8 +1848,7 @@ class Contact extends CommonObject $sql .= ")"; $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->errors[] = $this->db->lasterror().' sql='.$sql; $error++; } @@ -1830,12 +1877,13 @@ class Contact extends CommonObject global $langs; $sql = "SELECT id, code, libelle as label, picto FROM ".MAIN_DB_PREFIX."c_stcommcontact"; - if ($active >= 0) $sql .= " WHERE active = ".$active; + if ($active >= 0) { + $sql .= " WHERE active = ".$active; + } $resql = $this->db->query($sql); $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $this->cacheprospectstatus[$obj->id] = array('id' => $obj->id, 'code' => $obj->code, 'label' => ($langs->trans("ST_".strtoupper($obj->code)) == "ST_".strtoupper($obj->code)) ? $obj->label : $langs->trans("ST_".strtoupper($obj->code)), 'picto' => $obj->picto); $i++; @@ -1865,8 +1913,7 @@ class Contact extends CommonObject $lib = $langs->trans("ProspectLevel".$fk_prospectlevel); // If lib not found in language file, we get label from cache/databse - if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) - { + if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel)) { $lib = $langs->getLabelFromKey($this->db, $fk_prospectlevel, 'c_prospectlevel', 'code', 'label'); } return $lib; @@ -1915,36 +1962,48 @@ class Contact extends CommonObject global $langs; $langs->load('customers'); - if ($mode == 2) - { - if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1"); - elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0"); - elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1"); - elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2"); - elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3"); - else { + if ($mode == 2) { + if ($statut == '-1' || $statut == 'ST_NO') { + return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1"); + } elseif ($statut == '0' || $statut == 'ST_NEVER') { + return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0"); + } elseif ($statut == '1' || $statut == 'ST_TODO') { + return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1"); + } elseif ($statut == '2' || $statut == 'ST_PEND') { + return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2"); + } elseif ($statut == '3' || $statut == 'ST_DONE') { + return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3"); + } else { return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label); } } - if ($mode == 3) - { - if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto); - elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto); - elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto); - elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto); - elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto); - else { + if ($mode == 3) { + if ($statut == '-1' || $statut == 'ST_NO') { + return img_action($langs->trans("StatusProspect-1"), -1, $picto); + } elseif ($statut == '0' || $statut == 'ST_NEVER') { + return img_action($langs->trans("StatusProspect0"), 0, $picto); + } elseif ($statut == '1' || $statut == 'ST_TODO') { + return img_action($langs->trans("StatusProspect1"), 1, $picto); + } elseif ($statut == '2' || $statut == 'ST_PEND') { + return img_action($langs->trans("StatusProspect2"), 2, $picto); + } elseif ($statut == '3' || $statut == 'ST_DONE') { + return img_action($langs->trans("StatusProspect3"), 3, $picto); + } else { return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto); } } - if ($mode == 4) - { - if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1"); - elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0"); - elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1"); - elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2"); - elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3"); - else { + if ($mode == 4) { + if ($statut == '-1' || $statut == 'ST_NO') { + return img_action($langs->trans("StatusProspect-1"), -1, $picto).' '.$langs->trans("StatusProspect-1"); + } elseif ($statut == '0' || $statut == 'ST_NEVER') { + return img_action($langs->trans("StatusProspect0"), 0, $picto).' '.$langs->trans("StatusProspect0"); + } elseif ($statut == '1' || $statut == 'ST_TODO') { + return img_action($langs->trans("StatusProspect1"), 1, $picto).' '.$langs->trans("StatusProspect1"); + } elseif ($statut == '2' || $statut == 'ST_PEND') { + return img_action($langs->trans("StatusProspect2"), 2, $picto).' '.$langs->trans("StatusProspect2"); + } elseif ($statut == '3' || $statut == 'ST_DONE') { + return img_action($langs->trans("StatusProspect3"), 3, $picto).' '.$langs->trans("StatusProspect3"); + } else { return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0, $picto).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label); } } @@ -1964,24 +2023,19 @@ class Contact extends CommonObject $error = 0; // Update mass emailing flag into table mailing_unsubscribe - if ($this->email) - { + if ($this->email) { $this->db->begin(); - if ($no_email) - { + if ($no_email) { $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing', 0).") AND email = '".$this->db->escape($this->email)."'"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $noemail = $obj->nb; - if (empty($noemail)) - { + if (empty($noemail)) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."mailing_unsubscribe(email, entity, date_creat) VALUES ('".$this->db->escape($this->email)."', ".$this->db->escape(getEntity('mailing', 0)).", '".$this->db->idate(dol_now())."')"; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = $this->db->lasterror(); $this->errors[] = $this->error; @@ -1995,8 +2049,7 @@ class Contact extends CommonObject } else { $sql = "DELETE FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE email = '".$this->db->escape($this->email)."' AND entity = ".$this->db->escape(getEntity('mailing', 0)); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = $this->db->lasterror(); $this->errors[] = $this->error; @@ -2024,8 +2077,7 @@ class Contact extends CommonObject */ public function getNoEmail() { - if ($this->email) - { + if ($this->email) { $sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."mailing_unsubscribe WHERE entity IN (".getEntity('mailing').") AND email = '".$this->db->escape($this->email)."'"; $resql = $this->db->query($sql); if ($resql) { diff --git a/htdocs/contact/consumption.php b/htdocs/contact/consumption.php index da00374cc2a..1e0f5b06094 100644 --- a/htdocs/contact/consumption.php +++ b/htdocs/contact/consumption.php @@ -37,8 +37,12 @@ $id = GETPOST('id', 'int'); $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); -if ($id > 0) $object->fetch($id); -if (empty($object->thirdparty)) $object->fetch_thirdparty(); +if ($id > 0) { + $object->fetch($id); +} +if (empty($object->thirdparty)) { + $object->fetch_thirdparty(); +} $socid = $object->thirdparty->id; // Sort & Order fields @@ -46,12 +50,18 @@ $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 +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 = 'dateprint'; +if (!$sortorder) { + $sortorder = 'DESC'; +} +if (!$sortfield) { + $sortfield = 'dateprint'; +} // Search fields $sref = GETPOST("sref"); @@ -60,8 +70,7 @@ $month = GETPOST('month', 'int'); $year = GETPOST('year', 'int'); // Clean up on purge search criteria ? -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $sref = ''; $sprod_fulldescr = ''; $year = ''; @@ -84,7 +93,9 @@ $hookmanager->initHooks(array('consumptioncontact')); $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} /* @@ -99,8 +110,7 @@ $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("C $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if (empty($id)) -{ +if (empty($id)) { dol_print_error($db); exit; } @@ -111,13 +121,15 @@ print dol_get_fiche_head($head, 'consumption', $langs->trans("ContactsAddresses" $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
'; -if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) -{ +if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc->fetch($socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1, 'contact'); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1, 'contact'); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
'; @@ -133,22 +145,34 @@ print ''.$langs->trans("UserTitle").''; print $object->getCivilityLabel(); print ''; -if ($object->thirdparty->client) -{ +if ($object->thirdparty->client) { $thirdTypeArray['customer'] = $langs->trans("customer"); - if ($conf->propal->enabled && $user->rights->propal->lire) $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); - if ($conf->commande->enabled && $user->rights->commande->lire) $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); - if ($conf->facture->enabled && $user->rights->facture->lire) $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); - if ($conf->contrat->enabled && $user->rights->contrat->lire) $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + if ($conf->propal->enabled && $user->rights->propal->lire) { + $elementTypeArray['propal'] = $langs->transnoentitiesnoconv('Proposals'); + } + if ($conf->commande->enabled && $user->rights->commande->lire) { + $elementTypeArray['order'] = $langs->transnoentitiesnoconv('Orders'); + } + if ($conf->facture->enabled && $user->rights->facture->lire) { + $elementTypeArray['invoice'] = $langs->transnoentitiesnoconv('Invoices'); + } + if ($conf->contrat->enabled && $user->rights->contrat->lire) { + $elementTypeArray['contract'] = $langs->transnoentitiesnoconv('Contracts'); + } } -if ($conf->ficheinter->enabled && $user->rights->ficheinter->lire) $elementTypeArray['fichinter'] = $langs->transnoentitiesnoconv('Interventions'); +if ($conf->ficheinter->enabled && $user->rights->ficheinter->lire) { + $elementTypeArray['fichinter'] = $langs->transnoentitiesnoconv('Interventions'); +} -if ($object->thirdparty->fournisseur) -{ +if ($object->thirdparty->fournisseur) { $thirdTypeArray['supplier'] = $langs->trans("supplier"); - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) $elementTypeArray['supplier_invoice'] = $langs->transnoentitiesnoconv('SuppliersInvoices'); - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) $elementTypeArray['supplier_order'] = $langs->transnoentitiesnoconv('SuppliersOrders'); + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { + $elementTypeArray['supplier_invoice'] = $langs->transnoentitiesnoconv('SuppliersInvoices'); + } + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) { + $elementTypeArray['supplier_order'] = $langs->transnoentitiesnoconv('SuppliersOrders'); + } // There no contact type for supplier proposals // if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $user->rights->supplier_proposal->lire) $elementTypeArray['supplier_proposal']=$langs->transnoentitiesnoconv('SupplierProposals'); @@ -166,8 +190,7 @@ print '
'; print ''; $sql_select = ''; -if ($type_element == 'fichinter') -{ // Customer : show products from invoices +if ($type_element == 'fichinter') { // Customer : show products from invoices require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; $documentstatic = new Fichinter($db); $sql_select = 'SELECT f.rowid as doc_id, f.ref as doc_number, \'1\' as doc_type, f.datec as dateprint, f.fk_statut as status, tc.libelle as type_contact_label, '; @@ -178,8 +201,7 @@ if ($type_element == 'fichinter') $where = ' WHERE f.entity IN ('.getEntity('ficheinter').')'; $dateprint = 'f.datec'; $doc_number = 'f.ref'; -} elseif ($type_element == 'invoice') -{ // Customer : show products from invoices +} elseif ($type_element == 'invoice') { // Customer : show products from invoices require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $documentstatic = new Facture($db); $sql_select = 'SELECT f.rowid as doc_id, f.ref as doc_number, f.type as doc_type, f.datef as dateprint, f.fk_statut as status, f.paye as paid, tc.libelle as type_contact_label, '; @@ -192,8 +214,7 @@ if ($type_element == 'fichinter') $dateprint = 'f.datef'; $doc_number = 'f.ref'; $thirdTypeSelect = 'customer'; -} elseif ($type_element == 'propal') -{ +} elseif ($type_element == 'propal') { require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $documentstatic = new Propal($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.datep as dateprint, c.fk_statut as status, tc.libelle as type_contact_label, '; @@ -206,8 +227,7 @@ if ($type_element == 'fichinter') $datePrint = 'c.datep'; $doc_number = 'c.ref'; $thirdTypeSelect = 'customer'; -} elseif ($type_element == 'order') -{ +} elseif ($type_element == 'order') { require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php'; $documentstatic = new Commande($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_commande as dateprint, c.fk_statut as status, tc.libelle as type_contact_label, '; @@ -220,8 +240,7 @@ if ($type_element == 'fichinter') $dateprint = 'c.date_commande'; $doc_number = 'c.ref'; $thirdTypeSelect = 'customer'; -} elseif ($type_element == 'supplier_invoice') -{ // Supplier : Show products from invoices. +} elseif ($type_element == 'supplier_invoice') { // Supplier : Show products from invoices. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; $documentstatic = new FactureFournisseur($db); $sql_select = 'SELECT f.rowid as doc_id, f.ref as doc_number, \'1\' as doc_type, f.datef as dateprint, f.fk_statut as status, f.paye as paid, tc.libelle as type_contact_label, '; @@ -234,22 +253,19 @@ if ($type_element == 'fichinter') $dateprint = 'f.datef'; $doc_number = 'f.ref'; $thirdTypeSelect = 'supplier'; -} -//elseif ($type_element == 'supplier_proposal') -//{ -// require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; -// $documentstatic=new SupplierProposal($db); -// $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_valid as dateprint, c.fk_statut as status, '; -// $tables_from = MAIN_DB_PREFIX."supplier_proposal as c,".MAIN_DB_PREFIX."supplier_proposaldet as d"; -// $where = " WHERE c.fk_soc = s.rowid AND s.rowid = ".$socid; -// $where.= " AND d.fk_supplier_proposal = c.rowid"; -// $where.= " AND c.entity = ".$conf->entity; -// $dateprint = 'c.date_valid'; -// $doc_number='c.ref'; -// $thirdTypeSelect='supplier'; -//} -elseif ($type_element == 'supplier_order') -{ // Supplier : Show products from orders. + //} elseif ($type_element == 'supplier_proposal') { + // require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; + // $documentstatic=new SupplierProposal($db); + // $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_valid as dateprint, c.fk_statut as status, '; + // $tables_from = MAIN_DB_PREFIX."supplier_proposal as c,".MAIN_DB_PREFIX."supplier_proposaldet as d"; + // $where = " WHERE c.fk_soc = s.rowid AND s.rowid = ".$socid; + // $where.= " AND d.fk_supplier_proposal = c.rowid"; + // $where.= " AND c.entity = ".$conf->entity; + // $dateprint = 'c.date_valid'; + // $doc_number='c.ref'; + // $thirdTypeSelect='supplier'; + //} +} elseif ($type_element == 'supplier_order') { // Supplier : Show products from orders. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php'; $documentstatic = new CommandeFournisseur($db); $sql_select = 'SELECT c.rowid as doc_id, c.ref as doc_number, \'1\' as doc_type, c.date_valid as dateprint, c.fk_statut as status, tc.libelle as type_contact_label, '; @@ -262,8 +278,7 @@ elseif ($type_element == 'supplier_order') $dateprint = 'c.date_valid'; $doc_number = 'c.ref'; $thirdTypeSelect = 'supplier'; -} elseif ($type_element == 'contract') -{ // Order +} elseif ($type_element == 'contract') { // Order require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; $documentstatic = new Contrat($db); $documentstaticline = new ContratLigne($db); @@ -282,26 +297,40 @@ elseif ($type_element == 'supplier_order') $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook -if (!empty($sql_select)) -{ +if (!empty($sql_select)) { $sql = $sql_select; $sql .= ' d.description as description'; - if ($type_element != 'fichinter' && $type_element != 'contract' && $type_element != 'supplier_proposal') $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_start, d.date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; - if ($type_element == 'supplier_proposal') $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; - if ($type_element == 'contract') $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_ouverture as date_start, d.date_cloture as date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; - if ($type_element != 'fichinter') $sql .= ' p.ref as ref, p.rowid as prod_id, p.rowid as fk_product, p.fk_product_type as prod_type, p.fk_product_type as fk_product_type, p.entity as pentity'; + if ($type_element != 'fichinter' && $type_element != 'contract' && $type_element != 'supplier_proposal') { + $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_start, d.date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + } + if ($type_element == 'supplier_proposal') { + $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + } + if ($type_element == 'contract') { + $sql .= ', d.label, d.fk_product as product_id, d.fk_product as fk_product, d.info_bits, d.date_ouverture as date_start, d.date_cloture as date_end, d.qty, d.qty as prod_qty, d.total_ht as total_ht, '; + } + if ($type_element != 'fichinter') { + $sql .= ' p.ref as ref, p.rowid as prod_id, p.rowid as fk_product, p.fk_product_type as prod_type, p.fk_product_type as fk_product_type, p.entity as pentity'; + } $sql .= " "; - if ($type_element != 'fichinter') $sql .= ", p.ref as prod_ref, p.label as product_label"; + if ($type_element != 'fichinter') { + $sql .= ", p.ref as prod_ref, p.label as product_label"; + } $sql .= " FROM "/*.MAIN_DB_PREFIX."societe as s, "*/.$tables_from; // if ($type_element != 'fichinter') $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON d.fk_product = p.rowid '; $sql .= $where; $sql .= dolSqlDateFilter($dateprint, 0, $month, $year); - if ($sref) $sql .= " AND ".$doc_number." LIKE '%".$db->escape($sref)."%'"; - if ($sprod_fulldescr) - { + if ($sref) { + $sql .= " AND ".$doc_number." LIKE '%".$db->escape($sref)."%'"; + } + if ($sprod_fulldescr) { $sql .= " AND (d.description LIKE '%".$db->escape($sprod_fulldescr)."%'"; - if (GETPOST('type_element') != 'fichinter') $sql .= " OR p.ref LIKE '%".$db->escape($sprod_fulldescr)."%'"; - if (GETPOST('type_element') != 'fichinter') $sql .= " OR p.label LIKE '%".$db->escape($sprod_fulldescr)."%'"; + if (GETPOST('type_element') != 'fichinter') { + $sql .= " OR p.ref LIKE '%".$db->escape($sprod_fulldescr)."%'"; + } + if (GETPOST('type_element') != 'fichinter') { + $sql .= " OR p.label LIKE '%".$db->escape($sprod_fulldescr)."%'"; + } $sql .= ")"; } $sql .= $db->order($sortfield, $sortorder); @@ -332,21 +361,36 @@ $param .= "&type_element=".urlencode($type_element); $total_qty = 0; -if ($sql_select) -{ +if ($sql_select) { $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $num = $db->num_rows($resql); $param = "&socid=".urlencode($socid)."&type_element=".urlencode($type_element); - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sprod_fulldescr) $param .= "&sprod_fulldescr=".urlencode($sprod_fulldescr); - if ($sref) $param .= "&sref=".urlencode($sref); - if ($month) $param .= "&month=".urlencode($month); - if ($year) $param .= "&year=".urlencode($year); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($sprod_fulldescr) { + $param .= "&sprod_fulldescr=".urlencode($sprod_fulldescr); + } + if ($sref) { + $param .= "&sref=".urlencode($sref); + } + if ($month) { + $param .= "&month=".urlencode($month); + } + if ($year) { + $param .= "&year=".urlencode($year); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } print_barre_liste($langs->trans('ProductsIntoElements').' '.$typeElementString.' '.$button, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $totalnboflines, '', 0, '', '', $limit); @@ -393,8 +437,7 @@ if ($sql_select) $i = 0; - while (($objp = $db->fetch_object($resql)) && $i < min($num, $limit)) - { + while (($objp = $db->fetch_object($resql)) && $i < min($num, $limit)) { $documentstatic->id = $objp->doc_id; $documentstatic->ref = $objp->doc_number; $documentstatic->type = $objp->doc_type; @@ -405,7 +448,9 @@ if ($sql_select) $documentstatic->paye = $objp->paid; $documentstatic->paid = $objp->paid; - if (is_object($documentstaticline)) $documentstaticline->statut = $objp->status; + if (is_object($documentstaticline)) { + $documentstaticline->statut = $objp->status; + } print ''; print ''; @@ -415,8 +460,7 @@ if ($sql_select) // Status print ''; - if ($type_element == 'contract') - { + if ($type_element == 'contract') { print $documentstaticline->getLibStatut(2); } else { print $documentstatic->getLibStatut(2); @@ -429,8 +473,7 @@ if ($sql_select) $text = ''; $description = ''; $type = 0; // Code to show product duplicated from commonobject->printObjectLine - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { $product_static = new Product($db); $product_static->type = $objp->fk_product_type; @@ -441,20 +484,21 @@ if ($sql_select) } // Product - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $prod = new Product($db); $prod->fetch($objp->fk_product); $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) $newlang = $object->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if (empty($newlang)) { + $newlang = $object->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -468,42 +512,42 @@ if ($sql_select) $description = (!empty($conf->global->PRODUIT_DESC_IN_FORM) ? '' : dol_htmlentitiesbr($objp->description)); } - if (($objp->info_bits & 2) == 2) - { + if (($objp->info_bits & 2) == 2) { print ''; $txt = ''; print img_object($langs->trans("ShowReduc"), 'reduc').' '; - if ($objp->description == '(DEPOSIT)') $txt = $langs->trans("Deposit"); - elseif ($objp->description == '(EXCESS RECEIVED)') $txt = $langs->trans("ExcessReceived"); - elseif ($objp->description == '(EXCESS PAID)') $txt = $langs->trans("ExcessPaid"); + if ($objp->description == '(DEPOSIT)') { + $txt = $langs->trans("Deposit"); + } elseif ($objp->description == '(EXCESS RECEIVED)') { + $txt = $langs->trans("ExcessReceived"); + } elseif ($objp->description == '(EXCESS PAID)') { + $txt = $langs->trans("ExcessPaid"); + } //else $txt=$langs->trans("Discount"); print $txt; print ''; - if ($objp->description) - { - if ($objp->description == '(CREDIT_NOTE)' && $objp->fk_remise_except > 0) - { + if ($objp->description) { + if ($objp->description == '(CREDIT_NOTE)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0)); } - if ($objp->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) - { + if ($objp->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0)); - } elseif ($objp->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) - { + } elseif ($objp->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0)); - } elseif ($objp->description == '(DEPOSIT)' && $objp->fk_remise_except > 0) - { + } elseif ($objp->description == '(DEPOSIT)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($db); $discount->fetch($objp->fk_remise_except); echo ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0)); // Add date of deposit - if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) echo ' ('.dol_print_date($discount->datec).')'; + if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) { + echo ' ('.dol_print_date($discount->datec).')'; + } } else { echo ($txt ? ' - ' : '').dol_htmlentitiesbr($objp->description); } @@ -516,15 +560,16 @@ if ($sql_select) echo get_date_range($objp->date_start, $objp->date_end); // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($objp->description) && $objp->description != $objp->product_label) ? '
'.dol_htmlentitiesbr($objp->description) : ''; } } else { - if (!empty($objp->label) || !empty($objp->description)) - { - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if (!empty($objp->label) || !empty($objp->description)) { + if ($type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($objp->label)) { $text .= ' '.$objp->label.''; diff --git a/htdocs/contact/document.php b/htdocs/contact/document.php index 2065ab772e6..6118553914d 100644 --- a/htdocs/contact/document.php +++ b/htdocs/contact/document.php @@ -43,15 +43,16 @@ $object = new Contact($db); $object->getCanvas($id); $objcanvas = null; $canvas = (!empty($object->canvas) ? $object->canvas : GETPOST("canvas")); -if (!empty($canvas)) -{ +if (!empty($canvas)) { require_once DOL_DOCUMENT_ROOT.'/core/class/canvas.class.php'; $objcanvas = new Canvas($db, $action); $objcanvas->getCanvas('contact', 'contactcard', $canvas); } // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe', '', '', 'rowid', 0); // If we create a contact with no company (shared contacts), no check on write permission // Get parameters @@ -59,18 +60,30 @@ $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 +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 (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; } -if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; } +if (!empty($conf->global->MAIN_DOC_SORT_FIELD)) { + $sortfield = $conf->global->MAIN_DOC_SORT_FIELD; +} +if (!empty($conf->global->MAIN_DOC_SORT_ORDER)) { + $sortorder = $conf->global->MAIN_DOC_SORT_ORDER; +} -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} $upload_dir = $conf->societe->multidir_output[$object->entity].'/contact/'.dol_sanitizeFileName($object->ref); $modulepart = 'contact'; @@ -90,12 +103,13 @@ include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; $form = new Form($db); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) { + $title = $object->lastname; +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $helpurl); -if ($object->id) -{ +if ($object->id) { $head = contact_prepare_head($object); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); @@ -105,22 +119,23 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
'; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
'; @@ -133,23 +148,23 @@ if ($object->id) // Company /* - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { - if ($object->socid > 0) - { - $objsoc = new Societe($db); - $objsoc->fetch($object->socid); + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) + { + if ($object->socid > 0) + { + $objsoc = new Societe($db); + $objsoc->fetch($object->socid); - print ''.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).''; - } + print ''.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).''; + } - else - { - print ''.$langs->trans("ThirdParty").''; - print $langs->trans("ContactNotLinkedToCompany"); - print ''; - } - }*/ + else + { + print ''.$langs->trans("ThirdParty").''; + print $langs->trans("ContactNotLinkedToCompany"); + print ''; + } + }*/ // Civility print ''.$langs->trans("UserTitle").''; diff --git a/htdocs/contact/info.php b/htdocs/contact/info.php index c39c20d3d25..4cea1cae85b 100644 --- a/htdocs/contact/info.php +++ b/htdocs/contact/info.php @@ -34,7 +34,9 @@ $langs->load("companies"); // Security check $id = GETPOST("id", 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); @@ -51,8 +53,7 @@ $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("C llxHeader('', $title, 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'); -if ($id > 0) -{ +if ($id > 0) { $result = $object->fetch($id, $user); $object->info($id); diff --git a/htdocs/contact/ldap.php b/htdocs/contact/ldap.php index 78934c5857e..7f84393c858 100644 --- a/htdocs/contact/ldap.php +++ b/htdocs/contact/ldap.php @@ -36,12 +36,13 @@ $action = GETPOST('action', 'aZ09'); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); -if ($id > 0) -{ +if ($id > 0) { $object->fetch($id, $user); } @@ -50,8 +51,7 @@ if ($id > 0) * Actions */ -if ($action == 'dolibarr2ldap') -{ +if ($action == 'dolibarr2ldap') { $db->begin(); $ldap = new Ldap(); @@ -63,8 +63,7 @@ if ($action == 'dolibarr2ldap') $result = $ldap->update($dn, $info, $user, $olddn); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("ContactSynchronized"), null, 'mesgs'); $db->commit(); } else { @@ -98,8 +97,7 @@ print '
'; print ''; // Company -if ($object->socid > 0) -{ +if ($object->socid > 0) { $thirdparty = new Societe($db); $thirdparty->fetch($object->socid); @@ -139,14 +137,15 @@ print dol_get_fiche_end(); print '
'; -if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') -{ +if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') { print ''.$langs->trans("ForceSynchronize").''; } print "
\n"; -if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') print "
\n"; +if (!empty($conf->global->LDAP_CONTACT_ACTIVE) && $conf->global->LDAP_CONTACT_ACTIVE != 'ldap2dolibarr') { + print "
\n"; +} @@ -163,8 +162,7 @@ print ''; // Lecture LDAP $ldap = new Ldap(); $result = $ldap->connect_bind(); -if ($result > 0) -{ +if ($result > 0) { $info = $object->_load_ldap_info(); $dn = $object->_load_ldap_dn($info, 1); $search = "(".$object->_load_ldap_dn($info, 2).")"; @@ -174,10 +172,8 @@ if ($result > 0) //var_dump($records); // Show tree - if (((!is_numeric($records)) || $records != 0) && (!isset($records['count']) || $records['count'] > 0)) - { - if (!is_array($records)) - { + if (((!is_numeric($records)) || $records != 0) && (!isset($records['count']) || $records['count'] > 0)) { + if (!is_array($records)) { print ''; } else { $result = show_ldap_content($records, 0, $records['count'], true); diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index c33867fed7f..53ebbdfddd9 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -55,7 +55,9 @@ $contextpage = GETPOST('contextpage', 'aZ') ?GETPOST('contextpage', 'aZ') : 'con $id = GETPOST('id', 'int'); $contactid = GETPOST('id', 'int'); $ref = ''; // There is no ref for contacts -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $contactid, ''); $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); @@ -95,7 +97,9 @@ $search_roles = GETPOST("search_roles", 'array'); $search_level = GETPOST("search_level", "array"); $search_stcomm = GETPOST('search_stcomm', 'int'); -if ($search_status == '') $search_status = 1; // always display active customer first +if ($search_status == '') { + $search_status = 1; // always display active customer first +} $optioncss = GETPOST('optioncss', 'alpha'); @@ -109,31 +113,41 @@ $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); $userid = GETPOST('userid', 'int'); $begin = GETPOST('begin'); -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "p.lastname"; -if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { $page = 0; } +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "p.lastname"; +} +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + $page = 0; +} $offset = $limit * $page; $titre = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); -if ($type == "p") -{ - if (empty($contextpage) || $contextpage == 'contactlist') $contextpage = 'contactprospectlist'; +if ($type == "p") { + if (empty($contextpage) || $contextpage == 'contactlist') { + $contextpage = 'contactprospectlist'; + } $titre .= ' ('.$langs->trans("ThirdPartyProspects").')'; $urlfiche = "card.php"; } -if ($type == "c") -{ - if (empty($contextpage) || $contextpage == 'contactlist') $contextpage = 'contactcustomerlist'; +if ($type == "c") { + if (empty($contextpage) || $contextpage == 'contactlist') { + $contextpage = 'contactcustomerlist'; + } $titre .= ' ('.$langs->trans("ThirdPartyCustomers").')'; $urlfiche = "card.php"; -} elseif ($type == "f") -{ - if (empty($contextpage) || $contextpage == 'contactlist') $contextpage = 'contactsupplierlist'; +} elseif ($type == "f") { + if (empty($contextpage) || $contextpage == 'contactlist') { + $contextpage = 'contactsupplierlist'; + } $titre .= ' ('.$langs->trans("ThirdPartySuppliers").')'; $urlfiche = "card.php"; -} elseif ($type == "o") -{ - if (empty($contextpage) || $contextpage == 'contactlist') $contextpage = 'contactotherlist'; +} elseif ($type == "o") { + if (empty($contextpage) || $contextpage == 'contactlist') { + $contextpage = 'contactotherlist'; + } $titre .= ' ('.$langs->trans("OthersNotLinkedToThirdParty").')'; $urlfiche = ""; } @@ -150,8 +164,7 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // List of fields to search into when doing a "search in all" $fieldstosearchall = array(); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // don't allow search in private notes for external users when doing "search in all" if (!empty($user->socid) && $key == "note_private") { continue; @@ -209,10 +222,11 @@ $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); -if (($id > 0 || !empty($ref)) && $action != 'add') -{ +if (($id > 0 || !empty($ref)) && $action != 'add') { $result = $object->fetch($id, $ref); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } } @@ -220,21 +234,25 @@ if (($id > 0 || !empty($ref)) && $action != 'add') * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Did we click on purge search criteria ? - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers $sall = ""; $search_id = ''; $search_firstlast_only = ""; @@ -281,19 +299,22 @@ if (empty($reshook)) $uploaddir = $conf->societe->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - if ($action == 'setstcomm') - { + if ($action == 'setstcomm') { $object = new Contact($db); $result = $object->fetch(GETPOST('stcommcontactid')); $object->stcomm_id = dol_getIdFromCode($db, GETPOST('stcomm', 'alpha'), 'c_stcommcontact'); $result = $object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } $action = ''; } } -if ($search_priv < 0) $search_priv = ''; +if ($search_priv < 0) { + $search_priv = ''; +} /* @@ -318,17 +339,18 @@ $sql .= " FROM ".MAIN_DB_PREFIX."c_prospectcontactlevel"; $sql .= " WHERE active > 0"; $sql .= " ORDER BY sortorder"; $resql = $db->query($sql); -if ($resql) -{ - while ($obj = $db->fetch_object($resql)) - { +if ($resql) { + while ($obj = $db->fetch_object($resql)) { // Compute level text $level = $langs->trans($obj->code); - if ($level == $obj->code) $level = $langs->trans($obj->label); + if ($level == $obj->code) { + $level = $langs->trans($obj->label); + } $tab_level[$obj->code] = $level; } +} else { + dol_print_error($db); } -else dol_print_error($db); $sql = "SELECT s.rowid as socid, s.nom as name,"; $sql .= " p.rowid, p.lastname as lastname, p.statut, p.firstname, p.zip, p.town, p.poste, p.email, p.no_email,"; @@ -338,64 +360,121 @@ $sql .= " st.libelle as stcomm, st.picto as stcomm_picto, p.fk_stcommcontact as $sql .= " co.label as country, co.code as country_code"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."socpeople as p"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as co ON co.rowid = p.fk_pays"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = p.fk_soc"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_stcommcontact as st ON st.id = p.fk_stcommcontact"; -if (!empty($search_categ)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_contact as cc ON p.rowid = cc.fk_socpeople"; // We need this table joined to the select in order to filter by categ -if (!empty($search_categ_thirdparty)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc"; // We need this table joined to the select in order to filter by categ -if (!empty($search_categ_supplier)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs2 ON s.rowid = cs2.fk_soc"; // We need this table joined to the select in order to filter by categ -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +if (!empty($search_categ)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_contact as cc ON p.rowid = cc.fk_socpeople"; // We need this table joined to the select in order to filter by categ +} +if (!empty($search_categ_thirdparty)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cs ON s.rowid = cs.fk_soc"; // We need this table joined to the select in order to filter by categ +} +if (!empty($search_categ_supplier)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs2 ON s.rowid = cs2.fk_soc"; // We need this table joined to the select in order to filter by categ +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +} $sql .= ' WHERE p.entity IN ('.getEntity('socpeople').')'; -if (!$user->rights->societe->client->voir && !$socid) //restriction -{ +if (!$user->rights->societe->client->voir && !$socid) { //restriction $sql .= " AND (sc.fk_user = ".$user->id." OR p.fk_soc IS NULL)"; } -if (!empty($userid)) // propre au commercial -{ +if (!empty($userid)) { // propre au commercial $sql .= " AND p.fk_user_creat=".$db->escape($userid); } -if ($search_level) $sql .= natural_search("p.fk_prospectcontactlevel", join(',', $search_level), 3); -if ($search_stcomm != '' && $search_stcomm != -2) $sql .= natural_search("p.fk_stcommcontact", $search_stcomm, 2); - -// Filter to exclude not owned private contacts -if ($search_priv != '0' && $search_priv != '1') -{ - $sql .= " AND (p.priv='0' OR (p.priv='1' AND p.fk_user_creat=".$user->id."))"; -} else { - if ($search_priv == '0') $sql .= " AND p.priv='0'"; - if ($search_priv == '1') $sql .= " AND (p.priv='1' AND p.fk_user_creat=".$user->id.")"; +if ($search_level) { + $sql .= natural_search("p.fk_prospectcontactlevel", join(',', $search_level), 3); +} +if ($search_stcomm != '' && $search_stcomm != -2) { + $sql .= natural_search("p.fk_stcommcontact", $search_stcomm, 2); } -if ($search_categ > 0) $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ); -if ($search_categ == -2) $sql .= " AND cc.fk_categorie IS NULL"; -if ($search_categ_thirdparty > 0) $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_thirdparty); -if ($search_categ_thirdparty == -2) $sql .= " AND cs.fk_categorie IS NULL"; -if ($search_categ_supplier > 0) $sql .= " AND cs2.fk_categorie = ".$db->escape($search_categ_supplier); -if ($search_categ_supplier == -2) $sql .= " AND cs2.fk_categorie IS NULL"; +// Filter to exclude not owned private contacts +if ($search_priv != '0' && $search_priv != '1') { + $sql .= " AND (p.priv='0' OR (p.priv='1' AND p.fk_user_creat=".$user->id."))"; +} else { + if ($search_priv == '0') { + $sql .= " AND p.priv='0'"; + } + if ($search_priv == '1') { + $sql .= " AND (p.priv='1' AND p.fk_user_creat=".$user->id.")"; + } +} -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if (strlen($search_phone)) $sql .= natural_search(array('p.phone', 'p.phone_perso', 'p.phone_mobile'), $search_phone); -if (strlen($search_cti)) $sql .= natural_search(array('p.phone', 'p.phone_perso', 'p.phone_mobile'), $search_cti); -if (strlen($search_firstlast_only)) $sql .= natural_search(array('p.lastname', 'p.firstname'), $search_firstlast_only); +if ($search_categ > 0) { + $sql .= " AND cc.fk_categorie = ".$db->escape($search_categ); +} +if ($search_categ == -2) { + $sql .= " AND cc.fk_categorie IS NULL"; +} +if ($search_categ_thirdparty > 0) { + $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_thirdparty); +} +if ($search_categ_thirdparty == -2) { + $sql .= " AND cs.fk_categorie IS NULL"; +} +if ($search_categ_supplier > 0) { + $sql .= " AND cs2.fk_categorie = ".$db->escape($search_categ_supplier); +} +if ($search_categ_supplier == -2) { + $sql .= " AND cs2.fk_categorie IS NULL"; +} -if ($search_id > 0) $sql .= natural_search('p.rowid', $search_id, 1); -if ($search_lastname) $sql .= natural_search('p.lastname', $search_lastname); -if ($search_firstname) $sql .= natural_search('p.firstname', $search_firstname); -if ($search_societe) $sql .= natural_search(empty($conf->global->SOCIETE_DISABLE_CONTACTS) ? 's.nom' : 'p.fk_soc', $search_societe); -if ($search_country) $sql .= " AND p.fk_pays IN (".$search_country.')'; -if (strlen($search_poste)) $sql .= natural_search('p.poste', $search_poste); -if (strlen($search_phone_perso)) $sql .= natural_search('p.phone_perso', $search_phone_perso); -if (strlen($search_phone_pro)) $sql .= natural_search('p.phone', $search_phone_pro); -if (strlen($search_phone_mobile)) $sql .= natural_search('p.phone_mobile', $search_phone_mobile); -if (strlen($search_fax)) $sql .= natural_search('p.fax', $search_fax); +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if (strlen($search_phone)) { + $sql .= natural_search(array('p.phone', 'p.phone_perso', 'p.phone_mobile'), $search_phone); +} +if (strlen($search_cti)) { + $sql .= natural_search(array('p.phone', 'p.phone_perso', 'p.phone_mobile'), $search_cti); +} +if (strlen($search_firstlast_only)) { + $sql .= natural_search(array('p.lastname', 'p.firstname'), $search_firstlast_only); +} + +if ($search_id > 0) { + $sql .= natural_search('p.rowid', $search_id, 1); +} +if ($search_lastname) { + $sql .= natural_search('p.lastname', $search_lastname); +} +if ($search_firstname) { + $sql .= natural_search('p.firstname', $search_firstname); +} +if ($search_societe) { + $sql .= natural_search(empty($conf->global->SOCIETE_DISABLE_CONTACTS) ? 's.nom' : 'p.fk_soc', $search_societe); +} +if ($search_country) { + $sql .= " AND p.fk_pays IN (".$search_country.')'; +} +if (strlen($search_poste)) { + $sql .= natural_search('p.poste', $search_poste); +} +if (strlen($search_phone_perso)) { + $sql .= natural_search('p.phone_perso', $search_phone_perso); +} +if (strlen($search_phone_pro)) { + $sql .= natural_search('p.phone', $search_phone_pro); +} +if (strlen($search_phone_mobile)) { + $sql .= natural_search('p.phone_mobile', $search_phone_mobile); +} +if (strlen($search_fax)) { + $sql .= natural_search('p.fax', $search_fax); +} if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active'] && strlen($search_[$key])) { @@ -403,31 +482,38 @@ if (!empty($conf->socialnetworks->enabled)) { } } } -if (strlen($search_email)) $sql .= natural_search('p.email', $search_email); -if (strlen($search_zip)) $sql .= natural_search("p.zip", $search_zip); -if (strlen($search_town)) $sql .= natural_search("p.town", $search_town); +if (strlen($search_email)) { + $sql .= natural_search('p.email', $search_email); +} +if (strlen($search_zip)) { + $sql .= natural_search("p.zip", $search_zip); +} +if (strlen($search_town)) { + $sql .= natural_search("p.town", $search_town); +} if (count($search_roles) > 0) { $sql .= " AND p.rowid IN (SELECT sc.fk_socpeople FROM ".MAIN_DB_PREFIX."societe_contacts as sc WHERE sc.fk_c_type_contact IN (".implode(',', $search_roles)."))"; } -if ($search_no_email != '' && $search_no_email >= 0) $sql .= " AND p.no_email = ".$db->escape($search_no_email); -if ($search_status != '' && $search_status >= 0) $sql .= " AND p.statut = ".$db->escape($search_status); -if ($search_import_key) $sql .= natural_search("p.import_key", $search_import_key); -if ($type == "o") // filtre sur type -{ +if ($search_no_email != '' && $search_no_email >= 0) { + $sql .= " AND p.no_email = ".$db->escape($search_no_email); +} +if ($search_status != '' && $search_status >= 0) { + $sql .= " AND p.statut = ".$db->escape($search_status); +} +if ($search_import_key) { + $sql .= natural_search("p.import_key", $search_import_key); +} +if ($type == "o") { // filtre sur type $sql .= " AND p.fk_soc IS NULL"; -} elseif ($type == "f") // filtre sur type -{ +} elseif ($type == "f") { // filtre sur type $sql .= " AND s.fournisseur = 1"; -} elseif ($type == "c") // filtre sur type -{ +} elseif ($type == "c") { // filtre sur type $sql .= " AND s.client IN (1, 3)"; -} elseif ($type == "p") // filtre sur type -{ +} elseif ($type == "p") { // filtre sur type $sql .= " AND s.client IN (2, 3)"; } -if (!empty($socid)) -{ +if (!empty($socid)) { $sql .= " AND s.rowid = ".$socid; } // Add where from extra fields @@ -437,8 +523,7 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; // Add order -if ($view == "recent") -{ +if ($view == "recent") { $sql .= $db->order("p.datec", "DESC"); } else { $sql .= $db->order($sortfield, $sortorder); @@ -446,12 +531,10 @@ if ($view == "recent") // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) { $resql = $db->query($sql); $nbtotalofrecords = $db->num_rows($resql); - if (($page * $limit) > $nbtotalofrecords) // if total resultset is smaller then paging size (filtering), goto and load page 0 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -460,8 +543,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -470,8 +552,7 @@ $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && ($sall != '' || $search_cti != '')) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && ($sall != '' || $search_cti != '')) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/contact/card.php?id='.$id); @@ -482,39 +563,91 @@ $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Módulo_Empresas'; llxHeader('', $title, $help_url); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; +} $param .= '&begin='.urlencode($begin).'&userid='.urlencode($userid).'&contactname='.urlencode($sall); $param .= '&type='.urlencode($type).'&view='.urlencode($view); -if (!empty($search_categ)) $param .= '&search_categ='.urlencode($search_categ); -if (!empty($search_categ_thirdparty)) $param .= '&search_categ_thirdparty='.urlencode($search_categ_thirdparty); -if (!empty($search_categ_supplier)) $param .= '&search_categ_supplier='.urlencode($search_categ_supplier); -if ($sall != '') $param .= '&sall='.urlencode($sall); -if ($search_id > 0) $param .= "&search_id=".urlencode($search_id); -if ($search_lastname != '') $param .= '&search_lastname='.urlencode($search_lastname); -if ($search_firstname != '') $param .= '&search_firstname='.urlencode($search_firstname); -if ($search_societe != '') $param .= '&search_societe='.urlencode($search_societe); -if ($search_zip != '') $param .= '&search_zip='.urlencode($search_zip); -if ($search_town != '') $param .= '&search_town='.urlencode($search_town); -if ($search_country != '') $param .= "&search_country=".urlencode($search_country); -if ($search_poste != '') $param .= '&search_poste='.urlencode($search_poste); -if ($search_phone_pro != '') $param .= '&search_phone_pro='.urlencode($search_phone_pro); -if ($search_phone_perso != '') $param .= '&search_phone_perso='.urlencode($search_phone_perso); -if ($search_phone_mobile != '') $param .= '&search_phone_mobile='.urlencode($search_phone_mobile); -if ($search_fax != '') $param .= '&search_fax='.urlencode($search_fax); -if ($search_email != '') $param .= '&search_email='.urlencode($search_email); -if ($search_no_email != '') $param .= '&search_no_email='.urlencode($search_no_email); -if ($search_status != '') $param .= '&search_status='.urlencode($search_status); -if ($search_priv == '0' || $search_priv == '1') $param .= "&search_priv=".urlencode($search_priv); -if ($search_stcomm != '') $param .= '&search_stcomm='.urlencode($search_stcomm); +if (!empty($search_categ)) { + $param .= '&search_categ='.urlencode($search_categ); +} +if (!empty($search_categ_thirdparty)) { + $param .= '&search_categ_thirdparty='.urlencode($search_categ_thirdparty); +} +if (!empty($search_categ_supplier)) { + $param .= '&search_categ_supplier='.urlencode($search_categ_supplier); +} +if ($sall != '') { + $param .= '&sall='.urlencode($sall); +} +if ($search_id > 0) { + $param .= "&search_id=".urlencode($search_id); +} +if ($search_lastname != '') { + $param .= '&search_lastname='.urlencode($search_lastname); +} +if ($search_firstname != '') { + $param .= '&search_firstname='.urlencode($search_firstname); +} +if ($search_societe != '') { + $param .= '&search_societe='.urlencode($search_societe); +} +if ($search_zip != '') { + $param .= '&search_zip='.urlencode($search_zip); +} +if ($search_town != '') { + $param .= '&search_town='.urlencode($search_town); +} +if ($search_country != '') { + $param .= "&search_country=".urlencode($search_country); +} +if ($search_poste != '') { + $param .= '&search_poste='.urlencode($search_poste); +} +if ($search_phone_pro != '') { + $param .= '&search_phone_pro='.urlencode($search_phone_pro); +} +if ($search_phone_perso != '') { + $param .= '&search_phone_perso='.urlencode($search_phone_perso); +} +if ($search_phone_mobile != '') { + $param .= '&search_phone_mobile='.urlencode($search_phone_mobile); +} +if ($search_fax != '') { + $param .= '&search_fax='.urlencode($search_fax); +} +if ($search_email != '') { + $param .= '&search_email='.urlencode($search_email); +} +if ($search_no_email != '') { + $param .= '&search_no_email='.urlencode($search_no_email); +} +if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); +} +if ($search_priv == '0' || $search_priv == '1') { + $param .= "&search_priv=".urlencode($search_priv); +} +if ($search_stcomm != '') { + $param .= '&search_stcomm='.urlencode($search_stcomm); +} if (is_array($search_level) && count($search_level)) { foreach ($search_level as $slevel) { $param .= '&search_level[]='.urlencode($slevel); } } -if ($search_import_key != '') $param .= '&search_import_key='.urlencode($search_import_key); -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); -if (count($search_roles) > 0) $param .= implode('&search_roles[]=', $search_roles); +if ($search_import_key != '') { + $param .= '&search_import_key='.urlencode($search_import_key); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +if (count($search_roles) > 0) { + $param .= implode('&search_roles[]=', $search_roles); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -525,15 +658,23 @@ $arrayofmassactions = array( // 'builddoc'=>$langs->trans("PDFMerge"), ); //if($user->rights->societe->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); -if ($user->rights->societe->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); -if ($user->rights->societe->creer) $arrayofmassactions['preaffecttag'] = ''.$langs->trans("AffectTag"); -if (in_array($massaction, array('presend', 'predelete','preaffecttag'))) $arrayofmassactions = array(); +if ($user->rights->societe->supprimer) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); +} +if ($user->rights->societe->creer) { + $arrayofmassactions['preaffecttag'] = ''.$langs->trans("AffectTag"); +} +if (in_array($massaction, array('presend', 'predelete','preaffecttag'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = dolGetButtonTitle($langs->trans('NewContactAddress'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/contact/card.php?action=create', '', $user->rights->societe->contact->creer); print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -550,35 +691,36 @@ $objecttmp = new Contact($db); $trackid = 'ctc'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($sall) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
'; } -if ($search_firstlast_only) -{ +if ($search_firstlast_only) { print '
'.$langs->trans("FilterOnInto", $search_firstlast_only).$langs->trans("Lastname").", ".$langs->trans("Firstname").'
'; } $moreforfilter = ''; -if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) -{ +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
'; $moreforfilter .= $langs->trans('Categories').': '; $moreforfilter .= $formother->select_categories(Categorie::TYPE_CONTACT, $search_categ, 'search_categ', 1); $moreforfilter .= '
'; - if (empty($type) || $type == 'c' || $type == 'p') - { + if (empty($type) || $type == 'c' || $type == 'p') { $moreforfilter .= '
'; - if ($type == 'c') $moreforfilter .= $langs->trans('CustomersCategoriesShort').': '; - elseif ($type == 'p') $moreforfilter .= $langs->trans('ProspectsCategoriesShort').': '; - else $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; + if ($type == 'c') { + $moreforfilter .= $langs->trans('CustomersCategoriesShort').': '; + } elseif ($type == 'p') { + $moreforfilter .= $langs->trans('ProspectsCategoriesShort').': '; + } else { + $moreforfilter .= $langs->trans('CustomersProspectsCategoriesShort').': '; + } $moreforfilter .= $formother->select_categories(Categorie::TYPE_CUSTOMER, $search_categ_thirdparty, 'search_categ_thirdparty', 1); $moreforfilter .= '
'; } - if (empty($type) || $type == 'f') - { + if (empty($type) || $type == 'f') { $moreforfilter .= '
'; $moreforfilter .= $langs->trans('SuppliersCategoriesShort').': '; $moreforfilter .= $formother->select_categories(Categorie::TYPE_SUPPLIER, $search_categ_supplier, 'search_categ_supplier', 1); @@ -600,45 +742,41 @@ 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); +if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +} print '
'; print '
'.$langs->trans("ErrorFailedToReadLDAP").'
'."\n"; // Lines for filter fields print ''; -if (!empty($arrayfields['p.rowid']['checked'])) -{ +if (!empty($arrayfields['p.rowid']['checked'])) { print ''; } -if (!empty($arrayfields['p.lastname']['checked'])) -{ +if (!empty($arrayfields['p.lastname']['checked'])) { print ''; } -if (!empty($arrayfields['p.firstname']['checked'])) -{ +if (!empty($arrayfields['p.firstname']['checked'])) { print ''; } -if (!empty($arrayfields['p.poste']['checked'])) -{ +if (!empty($arrayfields['p.poste']['checked'])) { print ''; } -if (!empty($arrayfields['p.zip']['checked'])) -{ +if (!empty($arrayfields['p.zip']['checked'])) { print ''; } -if (!empty($arrayfields['p.town']['checked'])) -{ +if (!empty($arrayfields['p.town']['checked'])) { print ''; @@ -658,44 +796,37 @@ if (!empty($arrayfields['p.town']['checked'])) print ''; }*/ // Country -if (!empty($arrayfields['country.code_iso']['checked'])) -{ +if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; } -if (!empty($arrayfields['p.phone']['checked'])) -{ +if (!empty($arrayfields['p.phone']['checked'])) { print ''; } -if (!empty($arrayfields['p.phone_perso']['checked'])) -{ +if (!empty($arrayfields['p.phone_perso']['checked'])) { print ''; } -if (!empty($arrayfields['p.phone_mobile']['checked'])) -{ +if (!empty($arrayfields['p.phone_mobile']['checked'])) { print ''; } -if (!empty($arrayfields['p.fax']['checked'])) -{ +if (!empty($arrayfields['p.fax']['checked'])) { print ''; } -if (!empty($arrayfields['p.email']['checked'])) -{ +if (!empty($arrayfields['p.email']['checked'])) { print ''; } -if (!empty($arrayfields['p.no_email']['checked'])) -{ +if (!empty($arrayfields['p.no_email']['checked'])) { print ''; @@ -703,8 +834,7 @@ if (!empty($arrayfields['p.no_email']['checked'])) if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active']) { - if (!empty($arrayfields['p.'.$key]['checked'])) - { + if (!empty($arrayfields['p.'.$key]['checked'])) { print ''; @@ -712,33 +842,28 @@ if (!empty($conf->socialnetworks->enabled)) { } } } -if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) -{ +if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) { print ''; } -if (!empty($arrayfields['p.priv']['checked'])) -{ +if (!empty($arrayfields['p.priv']['checked'])) { print ''; } // Prospect level -if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) -{ +if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) { print ''; } // Prospect status -if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) -{ +if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) { print ''; } // Date modification -if (!empty($arrayfields['p.tms']['checked'])) -{ +if (!empty($arrayfields['p.tms']['checked'])) { print ''; } // Status -if (!empty($arrayfields['p.statut']['checked'])) -{ +if (!empty($arrayfields['p.statut']['checked'])) { print ''; } -if (!empty($arrayfields['p.import_key']['checked'])) -{ +if (!empty($arrayfields['p.import_key']['checked'])) { print ''; @@ -786,23 +907,47 @@ print ''; // Ligne des titres print ''; -if (!empty($arrayfields['p.rowid']['checked'])) print_liste_field_titre($arrayfields['p.rowid']['label'], $_SERVER["PHP_SELF"], "p.rowid", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['p.lastname']['checked'])) print_liste_field_titre($arrayfields['p.lastname']['label'], $_SERVER["PHP_SELF"], "p.lastname", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.firstname']['checked'])) print_liste_field_titre($arrayfields['p.firstname']['label'], $_SERVER["PHP_SELF"], "p.firstname", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.poste']['checked'])) print_liste_field_titre($arrayfields['p.poste']['label'], $_SERVER["PHP_SELF"], "p.poste", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.zip']['checked'])) print_liste_field_titre($arrayfields['p.zip']['label'], $_SERVER["PHP_SELF"], "p.zip", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.town']['checked'])) print_liste_field_titre($arrayfields['p.town']['label'], $_SERVER["PHP_SELF"], "p.town", $begin, $param, '', $sortfield, $sortorder); +if (!empty($arrayfields['p.rowid']['checked'])) { + print_liste_field_titre($arrayfields['p.rowid']['label'], $_SERVER["PHP_SELF"], "p.rowid", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['p.lastname']['checked'])) { + print_liste_field_titre($arrayfields['p.lastname']['label'], $_SERVER["PHP_SELF"], "p.lastname", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.firstname']['checked'])) { + print_liste_field_titre($arrayfields['p.firstname']['label'], $_SERVER["PHP_SELF"], "p.firstname", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.poste']['checked'])) { + print_liste_field_titre($arrayfields['p.poste']['label'], $_SERVER["PHP_SELF"], "p.poste", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.zip']['checked'])) { + print_liste_field_titre($arrayfields['p.zip']['label'], $_SERVER["PHP_SELF"], "p.zip", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.town']['checked'])) { + print_liste_field_titre($arrayfields['p.town']['label'], $_SERVER["PHP_SELF"], "p.town", $begin, $param, '', $sortfield, $sortorder); +} //if (! empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'],$_SERVER["PHP_SELF"],"state.nom","",$param,'',$sortfield,$sortorder); //if (! empty($arrayfields['region.nom']['checked'])) print_liste_field_titre($arrayfields['region.nom']['label'],$_SERVER["PHP_SELF"],"region.nom","",$param,'',$sortfield,$sortorder); if (!empty($arrayfields['country.code_iso']['checked'])) { print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "co.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); } -if (!empty($arrayfields['p.phone']['checked'])) print_liste_field_titre($arrayfields['p.phone']['label'], $_SERVER["PHP_SELF"], "p.phone", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.phone_perso']['checked'])) print_liste_field_titre($arrayfields['p.phone_perso']['label'], $_SERVER["PHP_SELF"], "p.phone_perso", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.phone_mobile']['checked'])) print_liste_field_titre($arrayfields['p.phone_mobile']['label'], $_SERVER["PHP_SELF"], "p.phone_mobile", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.fax']['checked'])) print_liste_field_titre($arrayfields['p.fax']['label'], $_SERVER["PHP_SELF"], "p.fax", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.email']['checked'])) print_liste_field_titre($arrayfields['p.email']['label'], $_SERVER["PHP_SELF"], "p.email", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.no_email']['checked'])) print_liste_field_titre($arrayfields['p.no_email']['label'], $_SERVER["PHP_SELF"], "p.no_email", $begin, $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['p.phone']['checked'])) { + print_liste_field_titre($arrayfields['p.phone']['label'], $_SERVER["PHP_SELF"], "p.phone", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.phone_perso']['checked'])) { + print_liste_field_titre($arrayfields['p.phone_perso']['label'], $_SERVER["PHP_SELF"], "p.phone_perso", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.phone_mobile']['checked'])) { + print_liste_field_titre($arrayfields['p.phone_mobile']['label'], $_SERVER["PHP_SELF"], "p.phone_mobile", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.fax']['checked'])) { + print_liste_field_titre($arrayfields['p.fax']['label'], $_SERVER["PHP_SELF"], "p.fax", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.email']['checked'])) { + print_liste_field_titre($arrayfields['p.email']['label'], $_SERVER["PHP_SELF"], "p.email", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.no_email']['checked'])) { + print_liste_field_titre($arrayfields['p.no_email']['label'], $_SERVER["PHP_SELF"], "p.no_email", $begin, $param, '', $sortfield, $sortorder, 'center '); +} if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active'] && !empty($arrayfields['p.'.$key]['checked'])) { @@ -810,11 +955,21 @@ if (!empty($conf->socialnetworks->enabled)) { } } } -if (!empty($arrayfields['p.fk_soc']['checked'])) print_liste_field_titre($arrayfields['p.fk_soc']['label'], $_SERVER["PHP_SELF"], "p.fk_soc", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $begin, $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['p.priv']['checked'])) print_liste_field_titre($arrayfields['p.priv']['label'], $_SERVER["PHP_SELF"], "p.priv", $begin, $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) print_liste_field_titre($arrayfields['p.fk_prospectcontactlevel']['label'], $_SERVER["PHP_SELF"], "p.fk_prospectcontactlevel", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) print_liste_field_titre($arrayfields['p.fk_stcommcontact']['label'], $_SERVER["PHP_SELF"], "p.fk_stcommcontact", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['p.fk_soc']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_soc']['label'], $_SERVER["PHP_SELF"], "p.fk_soc", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", $begin, $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['p.priv']['checked'])) { + print_liste_field_titre($arrayfields['p.priv']['label'], $_SERVER["PHP_SELF"], "p.priv", $begin, $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_prospectcontactlevel']['label'], $_SERVER["PHP_SELF"], "p.fk_prospectcontactlevel", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) { + print_liste_field_titre($arrayfields['p.fk_stcommcontact']['label'], $_SERVER["PHP_SELF"], "p.fk_stcommcontact", "", $param, '', $sortfield, $sortorder, 'center '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields @@ -844,8 +999,7 @@ print "\n"; $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $arraysocialnetworks = (array) json_decode($obj->socialnetworks, true); @@ -870,44 +1024,50 @@ while ($i < min($num, $limit)) print ''; // ID - if (!empty($arrayfields['p.rowid']['checked'])) - { + if (!empty($arrayfields['p.rowid']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Name - if (!empty($arrayfields['p.lastname']['checked'])) - { + if (!empty($arrayfields['p.lastname']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Firstname - if (!empty($arrayfields['p.firstname']['checked'])) - { + if (!empty($arrayfields['p.firstname']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Job position - if (!empty($arrayfields['p.poste']['checked'])) - { + if (!empty($arrayfields['p.poste']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['p.zip']['checked'])) - { + if (!empty($arrayfields['p.zip']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['p.town']['checked'])) - { + if (!empty($arrayfields['p.town']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State /*if (! empty($arrayfields['state.nom']['checked'])) @@ -922,101 +1082,119 @@ while ($i < min($num, $limit)) if (! $i) $totalarray['nbfield']++; }*/ // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Phone - if (!empty($arrayfields['p.phone']['checked'])) - { + if (!empty($arrayfields['p.phone']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Phone perso - if (!empty($arrayfields['p.phone_perso']['checked'])) - { + if (!empty($arrayfields['p.phone_perso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Phone mobile - if (!empty($arrayfields['p.phone_mobile']['checked'])) - { + if (!empty($arrayfields['p.phone_mobile']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Fax - if (!empty($arrayfields['p.fax']['checked'])) - { + if (!empty($arrayfields['p.fax']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // EMail - if (!empty($arrayfields['p.email']['checked'])) - { + if (!empty($arrayfields['p.email']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // No EMail - if (!empty($arrayfields['p.no_email']['checked'])) - { + if (!empty($arrayfields['p.no_email']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } if (!empty($conf->socialnetworks->enabled)) { foreach ($socialnetworks as $key => $value) { if ($value['active'] && !empty($arrayfields['p.'.$key]['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } } } // Company - if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['p.fk_soc']['checked']) || !empty($arrayfields['s.nom']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Private/Public - if (!empty($arrayfields['p.priv']['checked'])) - { + if (!empty($arrayfields['p.priv']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) - { + if (!empty($arrayfields['p.fk_prospectcontactlevel']['checked'])) { // Prospect level print '"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) - { + if (!empty($arrayfields['p.fk_stcommcontact']['checked'])) { // Prospect status print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -1026,45 +1204,52 @@ while ($i < min($num, $limit)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['p.datec']['checked'])) - { + if (!empty($arrayfields['p.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['p.tms']['checked'])) - { + if (!empty($arrayfields['p.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['p.statut']['checked'])) - { + if (!empty($arrayfields['p.statut']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['p.import_key']['checked'])) - { + if (!empty($arrayfields['p.import_key']['checked'])) { print '\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; $i++; diff --git a/htdocs/contact/note.php b/htdocs/contact/note.php index ae32ef5c95e..9a90cafdd9a 100644 --- a/htdocs/contact/note.php +++ b/htdocs/contact/note.php @@ -36,11 +36,15 @@ $langs->load("companies"); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $id = $user->socid; +if ($user->socid) { + $id = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); -if ($id > 0) $object->fetch($id); +if ($id > 0) { + $object->fetch($id); +} $permissionnote = $user->rights->societe->creer; // Used by the include of actions_setnotes.inc.php @@ -65,12 +69,13 @@ $form = new Form($db); $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $help_url); -if ($id > 0) -{ +if ($id > 0) { /* - * Affichage onglets - */ - if (!empty($conf->notification->enabled)) $langs->load("mails"); + * Affichage onglets + */ + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = contact_prepare_head($object); @@ -79,14 +84,16 @@ if ($id > 0) $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
'; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
'; diff --git a/htdocs/contact/perso.php b/htdocs/contact/perso.php index 0555eb84719..d313712a6a6 100644 --- a/htdocs/contact/perso.php +++ b/htdocs/contact/perso.php @@ -35,7 +35,9 @@ $id = GETPOST('id', 'int'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $object = new Contact($db); @@ -43,47 +45,43 @@ $object = new Contact($db); * Action */ -if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact->creer) -{ +if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact->creer) { $ret = $object->fetch($id); // Note: Correct date should be completed with location to have exact GM time of birth. $object->birthday = dol_mktime(0, 0, 0, $_POST["birthdaymonth"], $_POST["birthdayday"], $_POST["birthdayyear"]); $object->birthday_alert = $_POST["birthday_alert"]; - if (GETPOST('deletephoto')) $object->photo = ''; - elseif (!empty($_FILES['photo']['name'])) $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); + if (GETPOST('deletephoto')) { + $object->photo = ''; + } elseif (!empty($_FILES['photo']['name'])) { + $object->photo = dol_sanitizeFileName($_FILES['photo']['name']); + } $result = $object->update_perso($id, $user); - if ($result > 0) - { + if ($result > 0) { $object->old_name = ''; $object->old_firstname = ''; // Logo/Photo save $dir = $conf->societe->dir_output.'/contact/'.get_exdir($object->id, 0, 0, 1, $object, 'contact').'/photos'; $file_OK = is_uploaded_file($_FILES['photo']['tmp_name']); - if ($file_OK) - { + if ($file_OK) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; - if (GETPOST('deletephoto')) - { + if (GETPOST('deletephoto')) { $fileimg = $conf->societe->dir_output.'/contact/'.get_exdir($object->id, 0, 0, 1, $object, 'contact').'/photos/'.$object->photo; $dirthumbs = $conf->societe->dir_output.'/contact/'.get_exdir($object->id, 0, 0, 1, $object, 'contact').'/photos/thumbs'; dol_delete_file($fileimg); dol_delete_dir_recursive($dirthumbs); } - if (image_format_supported($_FILES['photo']['name']) > 0) - { + if (image_format_supported($_FILES['photo']['name']) > 0) { dol_mkdir($dir); - if (@is_dir($dir)) - { + if (@is_dir($dir)) { $newfile = $dir.'/'.dol_sanitizeFileName($_FILES['photo']['name']); - if (!dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1, 0, $_FILES['photo']['error']) > 0) - { + if (!dol_move_uploaded_file($_FILES['photo']['tmp_name'], $newfile, 1, 0, $_FILES['photo']['error']) > 0) { setEventMessages($langs->trans("ErrorFailedToSaveFile"), null, 'errors'); } else { // Create thumbs @@ -94,8 +92,7 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact- setEventMessages("ErrorBadImageFormat", null, 'errors'); } } else { - switch ($_FILES['photo']['error']) - { + switch ($_FILES['photo']['error']) { case 1: //uploaded file exceeds the upload_max_filesize directive in php.ini case 2: //uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the html form $errors[] = "ErrorFileSizeTooLarge"; @@ -118,7 +115,9 @@ if ($action == 'update' && !$_POST["cancel"] && $user->rights->societe->contact- $now = dol_now(); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("Contacts") : $langs->trans("ContactsAddresses")); -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) $title = $object->lastname; +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contactnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->lastname) { + $title = $object->lastname; +} $help_url = 'EN:Module_Third_Parties|FR:Module_Tiers|ES:Empresas'; llxHeader('', $title, $helpurl); @@ -128,8 +127,7 @@ $object->fetch($id, $user); $head = contact_prepare_head($object); -if ($action == 'edit') -{ +if ($action == 'edit') { /* * Fiche en mode edition */ @@ -151,11 +149,15 @@ if ($action == 'edit') // Photo print ''; // Company - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { - if ($object->socid > 0) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { + if ($object->socid > 0) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); @@ -194,8 +194,7 @@ if ($action == 'edit') print ''; print ''; } else { print ''; @@ -221,14 +220,16 @@ if ($action == 'edit') $linkback = ''.$langs->trans("BackToList").''; $morehtmlref = '
'; - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) { $objsoc = new Societe($db); $objsoc->fetch($object->socid); // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '; - if ($objsoc->id > 0) $morehtmlref .= $objsoc->getNomUrl(1); - else $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + if ($objsoc->id > 0) { + $morehtmlref .= $objsoc->getNomUrl(1); + } else { + $morehtmlref .= $langs->trans("ContactNotLinkedToCompany"); + } } $morehtmlref .= '
'; @@ -243,23 +244,23 @@ if ($action == 'edit') // Company /* - if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) - { - if ($object->socid > 0) - { - $objsoc = new Societe($db); - $objsoc->fetch($object->socid); + if (empty($conf->global->SOCIETE_DISABLE_CONTACTS)) + { + if ($object->socid > 0) + { + $objsoc = new Societe($db); + $objsoc->fetch($object->socid); - print ''; - } + print ''; + } - else - { - print ''; - } - }*/ + else + { + print ''; + } + }*/ // Civility print ''; - if (!empty($object->birthday)) - { + if (!empty($object->birthday)) { include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; print ''; } else { print ''; @@ -300,15 +307,12 @@ if ($action == 'edit') } -if ($action != 'edit') -{ +if ($action != 'edit') { // Barre d'actions - if ($user->socid == 0) - { + if ($user->socid == 0) { print '
'; - if ($user->rights->societe->contact->creer) - { + if ($user->rights->societe->contact->creer) { print ''.$langs->trans('Modify').''; } diff --git a/htdocs/contact/vcard.php b/htdocs/contact/vcard.php index 05426db19a6..1fba506e910 100644 --- a/htdocs/contact/vcard.php +++ b/htdocs/contact/vcard.php @@ -39,8 +39,7 @@ $result = restrictedArea($user, 'contact', $id, 'socpeople&societe'); $result = $contact->fetch($id); -if ($result <= 0) -{ +if ($result <= 0) { dol_print_error($contact->error); exit; } @@ -48,8 +47,7 @@ if ($result <= 0) $physicalperson = 1; $company = new Societe($db); -if ($contact->socid) -{ +if ($contact->socid) { $result = $company->fetch($contact->socid); } @@ -76,33 +74,32 @@ $v->setNote($contact->note); $v->setTitle($contact->poste); // Data from linked company -if ($company->id) -{ +if ($company->id) { $v->setURL($company->url, "TYPE=WORK"); - if (!$contact->phone_pro) $v->setPhoneNumber($company->phone, "TYPE=WORK;VOICE"); - if (!$contact->fax) $v->setPhoneNumber($company->fax, "TYPE=WORK;FAX"); - if (!$contact->zip) $v->setAddress("", "", $company->address, $company->town, $company->state, $company->zip, $company->country, "TYPE=WORK;POSTAL"); + if (!$contact->phone_pro) { + $v->setPhoneNumber($company->phone, "TYPE=WORK;VOICE"); + } + if (!$contact->fax) { + $v->setPhoneNumber($company->fax, "TYPE=WORK;FAX"); + } + if (!$contact->zip) { + $v->setAddress("", "", $company->address, $company->town, $company->state, $company->zip, $company->country, "TYPE=WORK;POSTAL"); + } // when company e-mail is empty, use only contact e-mail - if (empty(trim($company->email))) - { + if (empty(trim($company->email))) { // was set before, don't set twice - } - // when contact e-mail is empty, use only company e-mail - elseif (empty(trim($contact->email))) - { + } elseif (empty(trim($contact->email))) { + // when contact e-mail is empty, use only company e-mail $v->setEmail($company->email); - } - // when e-mail domain of contact and company are the same, use contact e-mail at first (and company e-mail at second) - elseif (strtolower(end(explode("@", $contact->email))) == strtolower(end(explode("@", $company->email)))) - { + } elseif (strtolower(end(explode("@", $contact->email))) == strtolower(end(explode("@", $company->email)))) { + // when e-mail domain of contact and company are the same, use contact e-mail at first (and company e-mail at second) $v->setEmail($contact->email); // support by Microsoft Outlook (2019 and possible earlier) $v->setEmail($company->email, 'INTERNET'); - } - // when e-mail of contact and company complete different use company e-mail at first (and contact e-mail at second) - else { + } else { + // when e-mail of contact and company complete different use company e-mail at first (and contact e-mail at second) $v->setEmail($company->email); // support by Microsoft Outlook (2019 and possible earlier) @@ -110,12 +107,16 @@ if ($company->id) } // Si contact lie a un tiers non de type "particulier" - if ($contact->typent_code != 'TE_PRIVATE') $v->setOrg($company->name); + if ($contact->typent_code != 'TE_PRIVATE') { + $v->setOrg($company->name); + } } // Personal informations $v->setPhoneNumber($contact->phone_perso, "TYPE=HOME;VOICE"); -if ($contact->birthday) $v->setBirthday($contact->birthday); +if ($contact->birthday) { + $v->setBirthday($contact->birthday); +} $db->close(); From 2da97c2bacffdeb4ff652525aafb3154448883be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 21:24:38 +0100 Subject: [PATCH 22/64] code syntax contrat directory --- htdocs/contrat/admin/contract_extrafields.php | 17 +- .../contrat/admin/contractdet_extrafields.php | 17 +- htdocs/contrat/agenda.php | 84 +- htdocs/contrat/card.php | 902 +++++++++-------- htdocs/contrat/class/api_contracts.class.php | 61 +- htdocs/contrat/class/contrat.class.php | 914 +++++++++--------- htdocs/contrat/contact.php | 44 +- htdocs/contrat/document.php | 37 +- htdocs/contrat/index.php | 233 +++-- htdocs/contrat/list.php | 478 +++++---- htdocs/contrat/note.php | 36 +- htdocs/contrat/services_list.php | 558 +++++++---- htdocs/contrat/tpl/linkedobjectblock.tpl.php | 21 +- 13 files changed, 1882 insertions(+), 1520 deletions(-) diff --git a/htdocs/contrat/admin/contract_extrafields.php b/htdocs/contrat/admin/contract_extrafields.php index 8571856362a..dc361a1f0b6 100644 --- a/htdocs/contrat/admin/contract_extrafields.php +++ b/htdocs/contrat/admin/contract_extrafields.php @@ -40,13 +40,17 @@ $form = new Form($db); // List of supported format $tmptype2label = ExtraFields::$type2label; $type2label = array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); +foreach ($tmptype2label as $key => $val) { + $type2label[$key] = $langs->transnoentitiesnoconv($val); +} $action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'contrat'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print '

'; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/contrat/admin/contractdet_extrafields.php b/htdocs/contrat/admin/contractdet_extrafields.php index 4b3f03ffedf..6e83f0a4c1b 100644 --- a/htdocs/contrat/admin/contractdet_extrafields.php +++ b/htdocs/contrat/admin/contractdet_extrafields.php @@ -40,13 +40,17 @@ $form = new Form($db); // List of supported format $tmptype2label = ExtraFields::$type2label; $type2label = array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); +foreach ($tmptype2label as $key => $val) { + $type2label[$key] = $langs->transnoentitiesnoconv($val); +} $action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'contratdet'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '
'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') /* Edition d'un champ optionnel */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "
"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/contrat/agenda.php b/htdocs/contrat/agenda.php index f88b470215c..94232aa6afd 100644 --- a/htdocs/contrat/agenda.php +++ b/htdocs/contrat/agenda.php @@ -35,10 +35,11 @@ if (!empty($conf->projet->enabled)) { // Load translation files required by the page $langs->loadLangs(array("companies", "contracts")); -if (GETPOST('actioncode', 'array')) -{ +if (GETPOST('actioncode', 'array')) { $actioncode = GETPOST('actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + if (!count($actioncode)) { + $actioncode = '0'; + } } else { $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECT)); } @@ -50,19 +51,27 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id, ''); $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 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('agendacontract', 'globalcard')); @@ -74,20 +83,19 @@ $hookmanager->initHooks(array('agendacontract', 'globalcard')); $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Cancel - if (GETPOST('cancel', 'alpha') && !empty($backtopage)) - { + if (GETPOST('cancel', 'alpha') && !empty($backtopage)) { header("Location: ".$backtopage); exit; } // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers $actioncode = ''; $search_agenda_label = ''; } @@ -102,19 +110,18 @@ if (empty($reshook)) $form = new Form($db); $formfile = new FormFile($db); -if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} -if ($id > 0) -{ +if ($id > 0) { // Load object modContract $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis'); - if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $result = dol_include_once('/core/modules/contract/'.$module.'.php'); - if ($result > 0) - { + if ($result > 0) { $modCodeContract = new $module(); } @@ -126,10 +133,14 @@ if ($id > 0) $object->fetch_thirdparty(); $title = $langs->trans("Agenda"); - if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contractrefonly/', $conf->global->MAIN_HTML_TITLE) && $object->ref) $title = $object->ref." - ".$title; + if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/contractrefonly/', $conf->global->MAIN_HTML_TITLE) && $object->ref) { + $title = $object->ref." - ".$title; + } llxHeader('', $title); - if (!empty($conf->notification->enabled)) $langs->load("mails"); + if (!empty($conf->notification->enabled)) { + $langs->load("mails"); + } $head = contract_prepare_head($object); print dol_get_fiche_head($head, 'agenda', $langs->trans("Contract"), -1, 'contract'); @@ -156,14 +167,14 @@ if ($id > 0) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $permtoedit, 'string', '', null, null, '', 1, 'getFormatedSupplierRef'); // Thirdparty $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->contrat->creer) - { + if ($user->rights->contrat->creer) { if ($action != 'classify') { //$morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).''; $morehtmlref .= ' : '; @@ -231,21 +242,22 @@ if ($id > 0) $newcardbutton = ''; - if (!empty($conf->agenda->enabled)) - { - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { + if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { $newcardbutton .= dolGetButtonTitle($langs->trans('AddAction'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out); } } - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { print '
'; $param = '&id='.$id; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; + } print load_fiche_titre($langs->trans("ActionsOnContract"), $newcardbutton, ''); //print_barre_liste($langs->trans("ActionsOnCompany"), 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, '', 0, -1, '', 0, $newcardbutton, '', 0, 1, 1); diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index d625298b14c..8a8f91f2a93 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -40,7 +40,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/modules/contract/modules_contract.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -if (!empty($conf->propal->enabled)) require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +if (!empty($conf->propal->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; +} if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -62,7 +64,9 @@ $datecontrat = ''; $usehm = (!empty($conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE) ? $conf->global->MAIN_USE_HOURMIN_IN_DATE_RANGE : 0); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -74,10 +78,12 @@ $extrafields = new ExtraFields($db); // Load object if ($id > 0 || !empty($ref) && $action != 'add') { $ret = $object->fetch($id, $ref); - if ($ret > 0) + if ($ret > 0) { $ret = $object->fetch_thirdparty(); - if ($ret < 0) + } + if ($ret < 0) { dol_print_error('', $object->error); + } } // fetch optionals attributes and labels @@ -98,36 +104,31 @@ $error = 0; $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)) -{ +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} +if (empty($reshook)) { include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once - if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer) - { + if ($action == 'confirm_active' && $confirm == 'yes' && $user->rights->contrat->activer) { $result = $object->active_line($user, GETPOST('ligne'), GETPOST('date'), GETPOST('dateend'), GETPOST('comment')); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer) - { - if (!GETPOST('dateend')) - { + } elseif ($action == 'confirm_closeline' && $confirm == 'yes' && $user->rights->contrat->activer) { + if (!GETPOST('dateend')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEnd")), null, 'errors'); } - if (!$error) - { + if (!$error) { $result = $object->close_line($user, GETPOST('ligne'), GETPOST('dateend'), urldecode(GETPOST('comment'))); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -137,16 +138,13 @@ if (empty($reshook)) } // Si ajout champ produit predefini - if (GETPOST('mode') == 'predefined') - { + if (GETPOST('mode') == 'predefined') { $date_start = ''; $date_end = ''; - if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) - { + if (GETPOST('date_startmonth') && GETPOST('date_startday') && GETPOST('date_startyear')) { $date_start = dol_mktime(GETPOST('date_starthour'), GETPOST('date_startmin'), 0, GETPOST('date_startmonth'), GETPOST('date_startday'), GETPOST('date_startyear')); } - if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) - { + if (GETPOST('date_endmonth') && GETPOST('date_endday') && GETPOST('date_endyear')) { $date_end = dol_mktime(GETPOST('date_endhour'), GETPOST('date_endmin'), 0, GETPOST('date_endmonth'), GETPOST('date_endday'), GETPOST('date_endyear')); } } @@ -156,40 +154,32 @@ if (empty($reshook)) $date_end_update = ''; $date_start_real_update = ''; $date_end_real_update = ''; - if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear')) - { + if (GETPOST('date_start_updatemonth') && GETPOST('date_start_updateday') && GETPOST('date_start_updateyear')) { $date_start_update = dol_mktime(GETPOST('date_start_updatehour'), GETPOST('date_start_updatemin'), 0, GETPOST('date_start_updatemonth'), GETPOST('date_start_updateday'), GETPOST('date_start_updateyear')); } - if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear')) - { + if (GETPOST('date_end_updatemonth') && GETPOST('date_end_updateday') && GETPOST('date_end_updateyear')) { $date_end_update = dol_mktime(GETPOST('date_end_updatehour'), GETPOST('date_end_updatemin'), 0, GETPOST('date_end_updatemonth'), GETPOST('date_end_updateday'), GETPOST('date_end_updateyear')); } - if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear')) - { + if (GETPOST('date_start_real_updatemonth') && GETPOST('date_start_real_updateday') && GETPOST('date_start_real_updateyear')) { $date_start_real_update = dol_mktime(GETPOST('date_start_real_updatehour'), GETPOST('date_start_real_updatemin'), 0, GETPOST('date_start_real_updatemonth'), GETPOST('date_start_real_updateday'), GETPOST('date_start_real_updateyear')); } - if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear')) - { + if (GETPOST('date_end_real_updatemonth') && GETPOST('date_end_real_updateday') && GETPOST('date_end_real_updateyear')) { $date_end_real_update = dol_mktime(GETPOST('date_end_real_updatehour'), GETPOST('date_end_real_updatemin'), 0, GETPOST('date_end_real_updatemonth'), GETPOST('date_end_real_updateday'), GETPOST('date_end_real_updateyear')); } - if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear')) - { + if (GETPOST('remonth') && GETPOST('reday') && GETPOST('reyear')) { $datecontrat = dol_mktime(GETPOST('rehour'), GETPOST('remin'), 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); } // Add contract - if ($action == 'add' && $user->rights->contrat->creer) - { + if ($action == 'add' && $user->rights->contrat->creer) { // Check - if (empty($datecontrat)) - { + if (empty($datecontrat)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Date")), null, 'errors'); $action = 'create'; } - if ($socid < 1) - { + if ($socid < 1) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ThirdParty")), null, 'errors'); $action = 'create'; $error++; @@ -202,8 +192,7 @@ if (empty($reshook)) $action = 'create'; } - if (!$error) - { + if (!$error) { $object->socid = $socid; $object->date_contrat = $datecontrat; @@ -219,27 +208,28 @@ if (empty($reshook)) $object->ref_supplier = GETPOST('ref_supplier', 'alpha'); // If creation from another object of another module (Example: origin=propal, originid=1) - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; - if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', $origin, $regs)) { $element = $regs[1]; $subelement = $regs[2]; } // For compatibility - if ($element == 'order') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + if ($element == 'order') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; $subelement = 'propal'; + } $object->origin = $origin; $object->origin_id = $originid; // Possibility to add external linked objects with hooks $object->linked_objects[$object->origin] = $object->origin_id; - if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) - { + if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) { $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); } @@ -248,8 +238,7 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } - if ($id > 0) - { + if ($id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); @@ -257,12 +246,10 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $srcobject->fetch($object->origin_id); - if ($result > 0) - { + if ($result > 0) { $srcobject->fetch_thirdparty(); $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } @@ -270,29 +257,29 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); if ($product_type == 1 || (!empty($conf->global->CONTRACT_SUPPORT_PRODUCTS) && in_array($product_type, array(0, 1)))) { // TODO Exclude also deee // service prédéfini - if ($lines[$i]->fk_product > 0) - { + if ($lines[$i]->fk_product > 0) { $product_static = new Product($db); // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $prod = new Product($db); $prod->id = $lines[$i]->fk_product; $prod->getMultiLangs(); $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) $newlang = $srcobject->thirdparty->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if (empty($newlang)) { + $newlang = $srcobject->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -340,8 +327,7 @@ if (empty($reshook)) $lines[$i]->fk_unit ); - if ($result < 0) - { + if ($result < 0) { $error++; break; } @@ -356,16 +342,16 @@ if (empty($reshook)) $parameters = array('objFrom' => $srcobject); $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if ($reshook < 0) + if ($reshook < 0) { $error++; + } } else { setEventMessages($object->error, $object->errors, 'errors'); $error++; } } else { $result = $object->create($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -376,18 +362,14 @@ if (empty($reshook)) } } elseif ($action == 'classin' && $user->rights->contrat->creer) { $object->setProject(GETPOST('projectid')); - } - - // Add a new line - elseif ($action == 'addline' && $user->rights->contrat->creer) - { + } elseif ($action == 'addline' && $user->rights->contrat->creer) { + // Add a new line // Set if we used free entry or predefined product $predef = ''; $product_desc = (GETPOSTISSET('dp_desc') ? GETPOST('dp_desc', 'restricthtml') : ''); $price_ht = price2num(GETPOST('price_ht'), 'MU'); $price_ht_devise = price2num(GETPOST('multicurrency_price_ht', 'CU')); - if (GETPOST('prod_entry_mode', 'alpha') == 'free') - { + if (GETPOST('prod_entry_mode', 'alpha') == 'free') { $idprod = 0; $tva_tx = (GETPOST('tva_tx', 'alpha') ? GETPOST('tva_tx', 'alpha') : 0); } else { @@ -398,21 +380,18 @@ if (empty($reshook)) $qty = price2num(GETPOST('qty'.$predef, 'alpha'), 'MS'); $remise_percent = (GETPOSTISSET('remise_percent'.$predef) ? price2num(GETPOST('remise_percent'.$predef), 2) : 0); - if ($qty == '') - { + if ($qty == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Qty")), null, 'errors'); $error++; } - if (GETPOST('prod_entry_mode', 'alpha') == 'free' && empty($idprod) && empty($product_desc)) - { + if (GETPOST('prod_entry_mode', 'alpha') == 'free' && empty($idprod) && empty($product_desc)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")), null, 'errors'); $error++; } $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); - if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) - { + if (!empty($date_start) && !empty($date_end) && $date_start > $date_end) { setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); $error++; } @@ -428,8 +407,7 @@ if (empty($reshook)) } } - if (!$error) - { + if (!$error) { // Clean parameters $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); @@ -439,15 +417,16 @@ if (empty($reshook)) // Ecrase $desc par celui du produit // Ecrase $tva_tx par celui du produit // Ecrase $base_price_type par celui du produit - if ($idprod > 0) - { + if ($idprod > 0) { $prod = new Product($db); $prod->fetch($idprod); // Update if prices fields are defined $tva_tx = get_default_tva($mysoc, $object->thirdparty, $prod->id); $tva_npr = get_default_npr($mysoc, $object->thirdparty, $prod->id); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $pu_ht = $prod->price; $pu_ttc = $prod->price_ttc; @@ -455,14 +434,12 @@ if (empty($reshook)) $price_base_type = $prod->price_base_type; // On defini prix unitaire - if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) - { + if ($conf->global->PRODUIT_MULTIPRICES && $object->thirdparty->price_level) { $pu_ht = $prod->multiprices[$object->thirdparty->price_level]; $pu_ttc = $prod->multiprices_ttc[$object->thirdparty->price_level]; $price_min = $prod->multiprices_min[$object->thirdparty->price_level]; $price_base_type = $prod->multiprices_base_type[$object->thirdparty->price_level]; - } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) - { + } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php'; $prodcustprice = new Productcustomerprice($db); @@ -476,9 +453,13 @@ if (empty($reshook)) $pu_ttc = price($prodcustprice->lines [0]->price_ttc); $price_base_type = $prodcustprice->lines [0]->price_base_type; $tva_tx = $prodcustprice->lines [0]->tva_tx; - if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) { + $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')'; + } $tva_npr = $prodcustprice->lines[0]->recuperableonly; - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } } } } @@ -488,25 +469,26 @@ if (empty($reshook)) // On reevalue prix selon taux tva car taux tva transaction peut etre different // de ceux du produit par defaut (par exemple si pays different entre vendeur et acheteur). - if ($tmpvat != $tmpprodvat) - { - if ($price_base_type != 'HT') - { + if ($tmpvat != $tmpprodvat) { + if ($price_base_type != 'HT') { $pu_ht = price2num($pu_ttc / (1 + ($tmpvat / 100)), 'MU'); } else { $pu_ttc = price2num($pu_ht * (1 + ($tmpvat / 100)), 'MU'); } } - $desc = $prod->description; + $desc = $prod->description; //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) { $product_desc=''; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; - else $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) { + $desc = $product_desc; + } else { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } $fk_unit = $prod->fk_unit; } else { @@ -523,16 +505,19 @@ if (empty($reshook)) // ajout prix achat $fk_fournprice = $_POST['fournprice']; - if (!empty($_POST['buying_price'])) - $pa_ht = $_POST['buying_price']; - else $pa_ht = null; + if (!empty($_POST['buying_price'])) { + $pa_ht = $_POST['buying_price']; + } else { + $pa_ht = null; + } $info_bits = 0; - if ($tva_npr) $info_bits |= 0x01; + if ($tva_npr) { + $info_bits |= 0x01; + } if (((!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->produit->ignore_price_min_advance)) - || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && ($price_min && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) - { + || empty($conf->global->MAIN_USE_ADVANCED_PERMS)) && ($price_min && (price2num($pu_ht) * (1 - price2num($remise_percent) / 100) < price2num($price_min)))) { $object->error = $langs->trans("CantBeLessThanMinPrice", price(price2num($price_min, 'MU'), 0, $langs, 0, 0, -1, $conf->currency)); $result = -1; } else { @@ -551,22 +536,24 @@ if (empty($reshook)) $price_base_type, $pu_ttc, $info_bits, - $fk_fournprice, - $pa_ht, + $fk_fournprice, + $pa_ht, $array_options, $fk_unit ); } - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && !empty($conf->global->CONTRACT_ADDON_PDF)) // No generation if default type not defined - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE) && !empty($conf->global->CONTRACT_ADDON_PDF)) { // No generation if default type not defined $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 ($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); @@ -615,19 +602,16 @@ if (empty($reshook)) } elseif ($action == 'updateline' && $user->rights->contrat->creer && !GETPOST('cancel', 'alpha')) { $error = 0; - if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) - { + if (!empty($date_start_update) && !empty($date_end_update) && $date_start_update > $date_end_update) { setEventMessages($langs->trans("Error").': '.$langs->trans("DateStartPlanned").' > '.$langs->trans("DateEndPlanned"), null, 'errors'); $action = 'editline'; $_GET['rowid'] = GETPOST('elrowid'); $error++; } - if (!$error) - { + if (!$error) { $objectline = new ContratLigne($db); - if ($objectline->fetch(GETPOST('elrowid', 'int')) < 0) - { + if ($objectline->fetch(GETPOST('elrowid', 'int')) < 0) { setEventMessages($objectline->error, $objectline->errors, 'errors'); $error++; } @@ -636,16 +620,20 @@ if (empty($reshook)) $db->begin(); - if (!$error) - { - if ($date_start_real_update == '') $date_start_real_update = $objectline->date_ouverture; - if ($date_end_real_update == '') $date_end_real_update = $objectline->date_cloture; + if (!$error) { + if ($date_start_real_update == '') { + $date_start_real_update = $objectline->date_ouverture; + } + if ($date_end_real_update == '') { + $date_end_real_update = $objectline->date_cloture; + } $vat_rate = GETPOST('eltva_tx'); // Define info_bits $info_bits = 0; - if (preg_match('/\*/', $vat_rate)) + if (preg_match('/\*/', $vat_rate)) { $info_bits |= 0x01; + } // Define vat_rate $vat_rate = str_replace('*', '', $vat_rate); @@ -657,17 +645,18 @@ if (empty($reshook)) // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } // ajout prix d'achat $fk_fournprice = $_POST['fournprice']; - if (!empty($_POST['buying_price'])) - $pa_ht = $_POST['buying_price']; - else $pa_ht = null; + if (!empty($_POST['buying_price'])) { + $pa_ht = $_POST['buying_price']; + } else { + $pa_ht = null; + } $fk_unit = GETPOST('unit', 'alpha'); @@ -709,43 +698,40 @@ if (empty($reshook)) // TODO verifier price_min si fk_product et multiprix $result = $objectline->update($user); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($objectline->error, $objectline->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); } - } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) - { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->contrat->creer) { $result = $object->deleteline(GETPOST('lineid'), $user); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) - { + } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->contrat->creer) { $result = $object->validate($user); - if ($result > 0) - { + if ($result > 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -758,49 +744,38 @@ if (empty($reshook)) } else { setEventMessages($object->error, $object->errors, 'errors'); } - } elseif ($action == 'reopen' && $user->rights->contrat->creer) - { + } elseif ($action == 'reopen' && $user->rights->contrat->creer) { $result = $object->reopen($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Close all lines - elseif ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) { + } elseif ($action == 'confirm_close' && $confirm == 'yes' && $user->rights->contrat->creer) { + // Close all lines $result = $object->closeAll($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Close all lines - elseif ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) { + } elseif ($action == 'confirm_activate' && $confirm == 'yes' && $user->rights->contrat->creer) { + // Close all lines $result = $object->activateAll($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->contrat->supprimer) { $result = $object->delete($user); - if ($result >= 0) - { + if ($result >= 0) { header("Location: list.php?restore_lastsearch_values=1"); return; } else { setEventMessages($object->error, $object->errors, 'errors'); } } elseif ($action == 'confirm_move' && $confirm == 'yes' && $user->rights->contrat->creer) { - if (GETPOST('newcid') > 0) - { + if (GETPOST('newcid') > 0) { $contractline = new ContratLigne($db); $result = $contractline->fetch(GETPOSTINT('lineid')); $contractline->fk_contrat = GETPOSTINT('newcid'); $result = $contractline->update($user, 1); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); return; } else { @@ -809,18 +784,18 @@ if (empty($reshook)) } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("RefNewContract")), null, 'errors'); } - } elseif ($action == 'update_extras') - { + } elseif ($action == 'update_extras') { $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 ($ret < 0) { + $error++; + } if (!$error) { $result = $object->insertExtraFields('CONTRACT_MODIFY'); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $error++; } @@ -829,8 +804,7 @@ if (empty($reshook)) if ($error) { $action = 'edit_extras'; } - } elseif ($action == 'setref_supplier') - { + } elseif ($action == 'setref_supplier') { $cancelbutton = GETPOST('cancel', 'alpha'); if (!$cancelbutton) { $object->oldcopy = dol_clone($object); @@ -847,12 +821,10 @@ if (empty($reshook)) header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit; } - } elseif ($action == 'setref_customer') - { + } elseif ($action == 'setref_customer') { $cancelbutton = GETPOST('cancel', 'alpha'); - if (!$cancelbutton) - { + if (!$cancelbutton) { $object->oldcopy = dol_clone($object); $result = $object->setValueFrom('ref_customer', GETPOST('ref_customer', 'alpha'), '', null, 'text', '', $user, 'CONTRACT_MODIFY'); @@ -888,11 +860,11 @@ if (empty($reshook)) $new_filedir = $conf->contrat->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); $files = dol_dir_list($old_filedir); - if (!empty($files)) - { - if (!is_dir($new_filedir)) dol_mkdir($new_filedir); - foreach ($files as $file) - { + if (!empty($files)) { + if (!is_dir($new_filedir)) { + dol_mkdir($new_filedir); + } + foreach ($files as $file) { dol_move($file['fullname'], $new_filedir.'/'.$file['name']); } } @@ -941,42 +913,31 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer) - { - if ($action == 'addcontact') - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->contrat->creer) { + if ($action == 'addcontact') { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // bascule du statut d'un contact - elseif ($action == 'swapstatut') - { + } elseif ($action == 'swapstatut') { + // bascule du statut d'un contact $result = $object->swapContactStatus(GETPOST('ligne')); - } - - // Efface un contact - elseif ($action == 'deletecontact') - { + } elseif ($action == 'deletecontact') { + // Efface un contact $result = $object->delete_contact(GETPOST('lineid')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -986,10 +947,8 @@ if (empty($reshook)) } // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes') - { - if (!GETPOST('socid', 3)) - { + if ($action == 'confirm_clone' && $confirm == 'yes') { + if (!GETPOST('socid', 3)) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { if ($object->id > 0) { @@ -998,7 +957,9 @@ if (empty($reshook)) header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit(); } else { - if (count($object->errors) > 0) setEventMessages($object->error, $object->errors, 'errors'); + if (count($object->errors) > 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } $action = ''; } } @@ -1015,53 +976,57 @@ llxHeader('', $langs->trans("Contract"), ""); $form = new Form($db); $formfile = new FormFile($db); -if (!empty($conf->projet->enabled)) $formproject = new FormProjets($db); +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} // Load object modContract $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis'); -if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') -{ +if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $result = dol_include_once('/core/modules/contract/'.$module.'.php'); -if ($result > 0) -{ +if ($result > 0) { $modCodeContract = new $module(); } // Create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans('AddContract'), '', 'contract'); $soc = new Societe($db); - if ($socid > 0) $soc->fetch($socid); + if ($socid > 0) { + $soc->fetch($socid); + } - if (GETPOST('origin') && GETPOST('originid')) - { + if (GETPOST('origin') && GETPOST('originid')) { // Parse element/subelement (ex: project_task) $regs = array(); $element = $subelement = GETPOST('origin'); - if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin'), $regs)) { $element = $regs[1]; $subelement = $regs[2]; } - if ($element == 'project') - { + if ($element == 'project') { $projectid = GETPOST('originid'); } else { // For compatibility - if ($element == 'order' || $element == 'commande') { $element = $subelement = 'commande'; } - if ($element == 'propal') { $element = 'comm/propal'; $subelement = 'propal'; } + if ($element == 'order' || $element == 'commande') { + $element = $subelement = 'commande'; + } + if ($element == 'propal') { + $element = 'comm/propal'; $subelement = 'propal'; + } dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); $objectsrc = new $classname($db); $objectsrc->fetch($originid); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) $objectsrc->fetch_lines(); + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { + $objectsrc->fetch_lines(); + } $objectsrc->fetch_thirdparty(); // Replicate extrafields @@ -1118,8 +1083,7 @@ if ($action == 'create') // Thirdparty print '
'; print ''; - if ($socid > 0) - { + if ($socid > 0) { print ''."\n"; - if ($socid > 0) - { + if ($socid > 0) { // Ligne info remises tiers print ''; } @@ -1161,8 +1130,7 @@ if ($action == 'create') print ""; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load('projects'); $formproject = new FormProjets($db); @@ -1178,8 +1146,7 @@ if ($action == 'create') print $doleditor->Create(1); print ''; - if (empty($user->socid)) - { + if (empty($user->socid)) { print ''; @@ -1405,22 +1374,19 @@ if ($action == 'create') print ''; - if (!empty($object->brouillon) && $user->rights->contrat->creer) - { + if (!empty($object->brouillon) && $user->rights->contrat->creer) { print ''; } echo '
'; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; $title = $langs->trans('ContactsAddresses'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $blocname = 'notes'; $title = $langs->trans('Notes'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; @@ -1430,19 +1396,20 @@ if ($action == 'create') $arrayothercontracts = $object->getListOfContracts('others'); /* - * Lines of contracts - */ + * Lines of contracts + */ $productstatic = new Product($db); $usemargins = 0; - if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'propal', 'commande'))) $usemargins = 1; + if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'propal', 'commande'))) { + $usemargins = 1; + } // Title line for service $cursorline = 1; print '
'; - while ($cursorline <= $nbofservices) - { + while ($cursorline <= $nbofservices) { print '
'; print '
'; print ''; @@ -1466,8 +1433,7 @@ if ($action == 'create') $sql .= " WHERE cd.rowid = ".$object->lines[$cursorline - 1]->id; $result = $db->query($sql); - if ($result) - { + if ($result) { $total = 0; print '
'; @@ -1478,23 +1444,27 @@ if ($action == 'create') // print ''; //} print ''; - if (!empty($conf->global->PRODUCT_USE_UNITS)) print ''; + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + print ''; + } print ''; - if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; + if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) { + print ''; + } print ''; print "\n"; $objp = $db->fetch_object($result); // Line in view mode - if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) - { + if ($action != 'editline' || GETPOST('rowid') != $objp->rowid) { $moreparam = ''; - if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $objp->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"'; + if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $objp->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') { + $moreparam = 'style="display: none;"'; + } print ''; // Label - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { $productstatic->id = $objp->fk_product; $productstatic->type = $objp->ptype; $productstatic->ref = $objp->pref; @@ -1506,16 +1476,14 @@ if ($action == 'create') print ''; // Unit - if (!empty($conf->global->PRODUCT_USE_UNITS)) print ''; + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + print ''; + } // Discount - if ($objp->remise_percent > 0) - { + if ($objp->remise_percent > 0) { print '\n"; } else { print ''; } // Margin - if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) print ''; + if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) { + print ''; + } // Icon move, update et delete (statut contrat 0=brouillon,1=valide,2=ferme) print '\n"; // Dates of service planed and real - if ($objp->subprice >= 0) - { + if ($objp->subprice >= 0) { $colspan = 6; if ($conf->margin->enabled && $conf->global->PRODUCT_USE_UNITS) { @@ -1592,8 +1559,7 @@ if ($action == 'create') // Date planned print $langs->trans("DateStartPlanned").': '; - if ($objp->date_debut) - { + if ($objp->date_debut) { print dol_print_date($db->jdate($objp->date_debut), 'day'); // Warning si date prevu passee et pas en service if ($objp->statut == 0 && $db->jdate($objp->date_debut) < ($now - $conf->contrat->services->inactifs->warning_delay)) { @@ -1601,18 +1567,21 @@ if ($action == 'create') $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); print " ".img_warning($textlate); } - } else print $langs->trans("Unknown"); + } else { + print $langs->trans("Unknown"); + } print '  -  '; print $langs->trans("DateEndPlanned").': '; - if ($objp->date_fin) - { + if ($objp->date_fin) { print dol_print_date($db->jdate($objp->date_fin), 'day'); if ($objp->statut == 4 && $db->jdate($objp->date_fin) < ($now - $conf->contrat->services->expires->warning_delay)) { $warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24; $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); print " ".img_warning($textlate); } - } else print $langs->trans("Unknown"); + } else { + print $langs->trans("Unknown"); + } print ''; print ''; @@ -1625,14 +1594,12 @@ if ($action == 'create') $line->fetch_optionals(); print $line->showOptionals($extrafields, 'view', array('class'=>'oddeven', 'style'=>$moreparam, 'colspan'=>$colspan), '', '', 1); } - } - // Line in mode update - else { + } else { + // Line in mode update // Ligne carac print ''; print ''; // Unit - if (!empty($conf->global->PRODUCT_USE_UNITS)) - { + if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; @@ -1693,10 +1661,11 @@ if ($action == 'create') // Discount print ''; - if (!empty($usemargins)) - { + if (!empty($usemargins)) { print ''; } print ''; $colspan = 6; - if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) $colspan++; - if (!empty($conf->global->PRODUCT_USE_UNITS)) $colspan++; + if (!empty($conf->margin->enabled) && !empty($conf->global->MARGIN_SHOW_ON_CONTRACT)) { + $colspan++; + } + if (!empty($conf->global->PRODUCT_USE_UNITS)) { + $colspan++; + } // Ligne dates prevues print ''; @@ -1732,10 +1705,11 @@ if ($action == 'create') dol_print_error($db); } - if ($object->statut > 0) - { + if ($object->statut > 0) { $moreparam = ''; - if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->lines[$cursorline - 1]->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') $moreparam = 'style="display: none;"'; + if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->lines[$cursorline - 1]->statut == ContratLigne::STATUS_CLOSED && $action != 'showclosedlines') { + $moreparam = 'style="display: none;"'; + } print ''; print ''; print "\n"; @@ -1748,22 +1722,21 @@ if ($action == 'create') /* - * Confirmation to delete service line of contract - */ - if ($action == 'deleteline' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) - { + * Confirmation to delete service line of contract + */ + if ($action == 'deleteline' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&lineid=".GETPOST('rowid'), $langs->trans("DeleteContractLine"), $langs->trans("ConfirmDeleteContractLine"), "confirm_deleteline", '', 0, 1); - if ($ret == 'html') print '
'; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->selectarray('search_no_email', array('-1'=>'', '0'=>$langs->trans('No'), '1'=>$langs->trans('Yes')), $search_no_email); print ''; print ''; print ''; print ''; print ''; $selectarray = array('0'=>$langs->trans("ContactPublic"), '1'=>$langs->trans("ContactPrivate")); print $form->selectarray('search_priv', $selectarray, $search_priv, 1); print ''; print $form->multiselectarray('search_level', $tab_level, $search_level, 0, 0, 'width75', 0, 0, '', '', '', 2); print ''; $arraystcomm = array(); - foreach ($contactstatic->cacheprospectstatus as $key => $val) - { + foreach ($contactstatic->cacheprospectstatus as $key => $val) { $arraystcomm[$val['id']] = ($langs->trans("StatusProspect".$val['id']) != "StatusProspect".$val['id'] ? $langs->trans("StatusProspect".$val['id']) : $val['label']); } print $form->selectarray('search_stcomm', $arraystcomm, $search_stcomm, -2, 0, 0, '', 0, 0, 0, '', 'nowrap '); @@ -752,26 +877,22 @@ $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation -if (!empty($arrayfields['p.datec']['checked'])) -{ +if (!empty($arrayfields['p.datec']['checked'])) { print ''; print ''; print ''; print $form->selectarray('search_status', array('-1'=>'', '0'=>$langs->trans('ActivityCeased'), '1'=>$langs->trans('InActivity')), $search_status); print ''; print ''; print '
'; print $obj->rowid; print "'; print $contactstatic->getNomUrl(1); print ''.$obj->firstname.''.$obj->poste.''.$obj->zip.''.$obj->town.''; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print ''.dol_print_phone($obj->phone_pro, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'phone').''.dol_print_phone($obj->phone_perso, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'phone').''.dol_print_phone($obj->phone_mobile, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'mobile').''.dol_print_phone($obj->fax, $obj->country_code, $obj->rowid, $obj->socid, 'AC_TEL', ' ', 'fax').''.dol_print_email($obj->email, $obj->rowid, $obj->socid, 'AC_EMAIL', 18, 0, 1).''.yn($obj->no_email).''.dol_print_socialnetworks($arraysocialnetworks[$key], $obj->rowid, $obj->socid, $key, $socialnetworks).''; - if ($obj->socid) - { + if ($obj->socid) { $objsoc = new Societe($db); $objsoc->fetch($obj->socid); print $objsoc->getNomUrl(1); - } else print ' '; + } else { + print ' '; + } print ''.$contactstatic->LibPubPriv($obj->priv).''; print $contactstatic->getLibProspLevel(); print "
'; print '
'.$contactstatic->libProspCommStatut($obj->stcomm_id, 2, $contactstatic->cacheprospectstatus[$obj->stcomm_id]['label'], $obj->stcomm_picto); print '
-
'; foreach ($contactstatic->cacheprospectstatus as $key => $val) { $titlealt = 'default'; - if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) $titlealt = $val['label']; - if ($obj->stcomm_id != $val['id']) print ''.img_action($titlealt, $val['code'], $val['picto']).''; + if (!empty($val['code']) && !in_array($val['code'], array('ST_NO', 'ST_NEVER', 'ST_TODO', 'ST_PEND', 'ST_DONE'))) { + $titlealt = $val['label']; + } + if ($obj->stcomm_id != $val['id']) { + print ''.img_action($titlealt, $val['code'], $val['picto']).''; + } } print '
'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''.$contactstatic->getLibStatut(5).''; print $obj->import_key; print "'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + if (in_array($obj->rowid, $arrayofselected)) { + $selected = 1; + } print ''; } print '
'; print $form->showphoto('contact', $object)."\n"; - if ($object->photo) print "
\n"; + if ($object->photo) { + print "
\n"; + } print ''; - if ($object->photo) print ''; + if ($object->photo) { + print ''; + } print ''; print ''; print '
'.$langs->trans("Delete").'

'.$langs->trans("Delete").'

'.$langs->trans("PhotoFile").'
'; @@ -167,10 +169,8 @@ if ($action == 'edit') print '
'.$langs->trans("Firstname").''.$object->firstname.''.$langs->trans("Alert").': '; - if (!empty($object->birthday_alert)) - { + if (!empty($object->birthday_alert)) { print '
'.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
'.$langs->trans("ThirdParty").''.$objsoc->getNomUrl(1).'
'.$langs->trans("ThirdParty").''; - print $langs->trans("ContactNotLinkedToCompany"); - print '
'.$langs->trans("ThirdParty").''; + print $langs->trans("ContactNotLinkedToCompany"); + print '
'.$langs->trans("UserTitle").''; @@ -268,8 +269,7 @@ if ($action == 'edit') // Date To Birth print '
'.$langs->trans("DateOfBirth").''.dol_print_date($object->birthday, "day"); @@ -278,14 +278,21 @@ if ($action == 'edit') //var_dump($birthdatearray); $ageyear = convertSecondToTime($now - $object->birthday, 'year') - 1970; $agemonth = convertSecondToTime($now - $object->birthday, 'month') - 1; - if ($ageyear >= 2) print '('.$ageyear.' '.$langs->trans("DurationYears").')'; - elseif ($agemonth >= 2) print '('.$agemonth.' '.$langs->trans("DurationMonths").')'; - else print '('.$agemonth.' '.$langs->trans("DurationMonth").')'; + if ($ageyear >= 2) { + print '('.$ageyear.' '.$langs->trans("DurationYears").')'; + } elseif ($agemonth >= 2) { + print '('.$agemonth.' '.$langs->trans("DurationMonths").')'; + } else { + print '('.$agemonth.' '.$langs->trans("DurationMonth").')'; + } print '   -   '; - if ($object->birthday_alert) print $langs->trans("BirthdayAlertOn"); - else print $langs->trans("BirthdayAlertOff"); + if ($object->birthday_alert) { + print $langs->trans("BirthdayAlertOn"); + } else { + print $langs->trans("BirthdayAlertOff"); + } print ''.$langs->trans("DateOfBirth").'
'.$langs->trans('ThirdParty').''; print $soc->getNomUrl(1); print ''; @@ -1132,16 +1096,21 @@ if ($action == 'create') } print '
'.$langs->trans('Discounts').''; - if ($soc->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); + if ($soc->remise_percent) { + print $langs->trans("CompanyHasRelativeDiscount", $soc->remise_percent); + } else { + print $langs->trans("CompanyHasNoRelativeDiscount"); + } print '. '; $absolute_discount = $soc->getAvailableDiscounts(); - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($absolute_discount) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); + } else { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + } print '.'; print '
'.$langs->trans("NotePrivate").''; $doleditor = new DolEditor('note_private', $note_private, '', '100', 'dolibarr_notes', 'In', 1, true, empty($conf->global->FCKEDITOR_ENABLE_NOTE_PRIVATE) ? 0 : 1, ROWS_3, '90%'); print $doleditor->Create(1); @@ -1206,13 +1173,11 @@ if ($action == 'create') print ''; print ''; - if (is_object($objectsrc)) - { + if (is_object($objectsrc)) { print ''; print ''; - if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) - { + if (empty($conf->global->CONTRACT_SUPPORT_PRODUCTS)) { print '
'.$langs->trans("Note").': '.$langs->trans("OnlyLinesWithTypeServiceAreUsed"); } } @@ -1226,8 +1191,7 @@ if ($action == 'create') { $now = dol_now(); - if ($object->id > 0) - { + if ($object->id > 0) { $object->fetch_thirdparty(); $soc = $object->thirdparty; // $soc is used later @@ -1299,10 +1263,9 @@ if ($action == 'create') print $formconfirm; /* - * Contrat - */ - if (!empty($object->brouillon) && $user->rights->contrat->creer) - { + * Contrat + */ + if (!empty($object->brouillon) && $user->rights->contrat->creer) { print ''; print ''; print ''; @@ -1331,14 +1294,14 @@ if ($action == 'create') $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $user->rights->contrat->creer, 'string', '', null, null, '', 1, 'getFormatedSupplierRef'); // Thirdparty $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->contrat->creer) - { + if ($user->rights->contrat->creer) { if ($action != 'classify') { $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' : '; } @@ -1379,12 +1342,18 @@ if ($action == 'create') // Line info of thirdparty discounts print '
'.$langs->trans('Discount').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); + if ($object->thirdparty->remise_percent) { + print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent); + } else { + print $langs->trans("CompanyHasNoRelativeDiscount"); + } $absolute_discount = $object->thirdparty->getAvailableDiscounts(); print '. '; - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($absolute_discount) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); + } else { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + } print '.'; print '
'.$langs->trans("PriceUHTCurrency").''.$langs->trans("Qty").''.$langs->trans("Unit").''.$langs->trans("Unit").''.$langs->trans("ReductionShort").''.$langs->trans("BuyingPrice").''.$langs->trans("BuyingPrice").' 
'; $text = $productstatic->getNomUrl(1, '', 32); - if ($objp->plabel) - { + if ($objp->plabel) { $text .= ' - '; $text .= $objp->plabel; } $description = $objp->description; // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { $text .= (!empty($objp->description) && $objp->description != $objp->plabel) ? '
'.dol_htmlentitiesbr($objp->description) : ''; $description = ''; // Already added into main visible desc } @@ -1539,35 +1507,35 @@ if ($action == 'create') // Quantity print '
'.$objp->qty.''.$langs->trans($object->lines[$cursorline - 1]->getLabelOfUnit()).''.$langs->trans($object->lines[$cursorline - 1]->getLabelOfUnit()).''.$objp->remise_percent."% '.price($objp->pa_ht).''.price($objp->pa_ht).''; - if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) - { + if ($user->rights->contrat->creer && count($arrayothercontracts) && ($object->statut >= 0)) { print ''; print ''; print img_picto($langs->trans("MoveToAnotherContract"), 'uparrow'); print ''; } - if ($user->rights->contrat->creer && ($object->statut >= 0)) - { + if ($user->rights->contrat->creer && ($object->statut >= 0)) { print ''; print img_edit(); print ''; } - if ($user->rights->contrat->creer && ($object->statut >= 0)) - { + if ($user->rights->contrat->creer && ($object->statut >= 0)) { print ''; print img_delete(); print ''; @@ -1577,8 +1545,7 @@ if ($action == 'create') print "
'; - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { $canchangeproduct = 1; if (empty($canchangeproduct)) { $productstatic->id = $objp->fk_product; @@ -1659,7 +1626,9 @@ if ($action == 'create') // editeur wysiwyg require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; $nbrows = ROWS_2; - if (!empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows = $conf->global->MAIN_INPUT_DESC_HEIGHT; + if (!empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) { + $nbrows = $conf->global->MAIN_INPUT_DESC_HEIGHT; + } $enable = (isset($conf->global->FCKEDITOR_ENABLE_DETAILS) ? $conf->global->FCKEDITOR_ENABLE_DETAILS : 0); $doleditor = new DolEditor('product_desc', $objp->description, '', 92, 'dolibarr_details', '', false, true, $enable, $nbrows, '90%'); $doleditor->Create(); @@ -1683,8 +1652,7 @@ if ($action == 'create') print ''; print $form->selectUnits($objp->fk_unit, "unit"); print '%'; - if ($objp->fk_product) print ''; + if ($objp->fk_product) { + print ''; + } print ''; @@ -1706,8 +1675,12 @@ if ($action == 'create') print '

'; + if ($ret == 'html') { + print '
'; + } } /* - * Confirmation to move service toward another contract - */ - if ($action == 'move' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) - { + * Confirmation to move service toward another contract + */ + if ($action == 'move' && !$_REQUEST["cancel"] && $user->rights->contrat->creer && $object->lines[$cursorline - 1]->id == GETPOST('rowid')) { $arraycontractid = array(); - foreach ($arrayothercontracts as $contractcursor) - { + foreach ($arrayothercontracts as $contractcursor) { $arraycontractid[$contractcursor->id] = $contractcursor->ref; } //var_dump($arraycontractid); @@ -1777,10 +1750,9 @@ if ($action == 'create') } /* - * Confirmation de la validation activation - */ - if ($action == 'active' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) - { + * Confirmation de la validation activation + */ + if ($action == 'active' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) { $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); $comment = GETPOST('comment', 'alpha'); @@ -1789,16 +1761,14 @@ if ($action == 'create') } /* - * Confirmation de la validation fermeture - */ - if ($action == 'closeline' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) - { + * Confirmation de la validation fermeture + */ + if ($action == 'closeline' && !$_REQUEST["cancel"] && $user->rights->contrat->activer && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) { $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); $comment = GETPOST('comment', 'alpha'); - if (empty($dateactend)) - { + if (empty($dateactend)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateEndReal")), null, 'errors'); } else { print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id."&ligne=".GETPOST('ligne', 'int')."&date=".$dateactstart."&dateend=".$dateactend."&comment=".urlencode($comment), $langs->trans("CloseService"), $langs->trans("ConfirmCloseService", dol_print_date($dateactend, "%A %d %B %Y")), "confirm_closeline", '', 0, 1); @@ -1808,28 +1778,23 @@ if ($action == 'create') // Area with status and activation info of line - if ($object->statut > 0) - { + if ($object->statut > 0) { print ''; print ''; print ''; print ''; print ''; @@ -1871,8 +1841,7 @@ if ($action == 'create') } // Form to activate line - if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) - { + if ($user->rights->contrat->activer && $action == 'activateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) { print ''; print ''; @@ -1880,15 +1849,17 @@ if ($action == 'create') // Definie date debut et fin par defaut $dateactstart = $objp->date_debut; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (!$dateactstart) $dateactstart = time(); + if (GETPOST('remonth')) { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + } elseif (!$dateactstart) { + $dateactstart = time(); + } $dateactend = $objp->date_fin; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (!$dateactend) - { - if ($objp->fk_product > 0) - { + if (GETPOST('endmonth')) { + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + } elseif (!$dateactend) { + if ($objp->fk_product > 0) { $product = new Product($db); $product->fetch($objp->fk_product); $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); @@ -1920,8 +1891,7 @@ if ($action == 'create') print ''; } - if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) - { + if ($user->rights->contrat->activer && $action == 'unactivateline' && $object->lines[$cursorline - 1]->id == GETPOST('ligne')) { /** * Disable a contract line */ @@ -1935,28 +1905,30 @@ if ($action == 'create') // Definie date debut et fin par defaut $dateactstart = $objp->date_debut_reelle; - if (GETPOST('remonth')) $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); - elseif (!$dateactstart) $dateactstart = time(); + if (GETPOST('remonth')) { + $dateactstart = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); + } elseif (!$dateactstart) { + $dateactstart = time(); + } $dateactend = $objp->date_fin_reelle; - if (GETPOST('endmonth')) $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); - elseif (!$dateactend) - { - if ($objp->fk_product > 0) - { + if (GETPOST('endmonth')) { + $dateactend = dol_mktime(12, 0, 0, GETPOST('endmonth'), GETPOST('endday'), GETPOST('endyear')); + } elseif (!$dateactend) { + if ($objp->fk_product > 0) { $product = new Product($db); $product->fetch($objp->fk_product); $dateactend = dol_time_plus_duree(time(), $product->duration_value, $product->duration_unit); } } $now = dol_now(); - if ($dateactend > $now) $dateactend = $now; + if ($dateactend > $now) { + $dateactend = $now; + } print ''; } } - if (!empty($conf->projet->enabled) && !$this->ispublic) - { + if (!empty($conf->projet->enabled) && !$this->ispublic) { $formproject = new FormProjets($this->db); print '
'.$langs->trans("ServiceStatus").': '.$object->lines[$cursorline - 1]->getLibStatut(4).''; - if ($user->socid == 0) - { - if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') - { + if ($user->socid == 0) { + if ($object->statut > 0 && $action != 'activateline' && $action != 'unactivateline') { $tmpaction = 'activateline'; $tmpactionpicto = 'play'; $tmpactiontext = $langs->trans("Activate"); - if ($objp->statut == 4) - { + if ($objp->statut == 4) { $tmpaction = 'unactivateline'; $tmpactionpicto = 'playstop'; $tmpactiontext = $langs->trans("Disable"); } - if (($tmpaction == 'activateline' && $user->rights->contrat->activer) || ($tmpaction == 'unactivateline' && $user->rights->contrat->desactiver)) - { + if (($tmpaction == 'activateline' && $user->rights->contrat->activer) || ($tmpaction == 'unactivateline' && $user->rights->contrat->desactiver)) { print ''; print img_picto($tmpactiontext, $tmpactionpicto); print ''; @@ -1845,8 +1810,11 @@ if ($action == 'create') // Si pas encore active if (!$objp->date_debut_reelle) { print $langs->trans("DateStartReal").': '; - if ($objp->date_debut_reelle) print dol_print_date($db->jdate($objp->date_debut_reelle), 'day'); - else print $langs->trans("ContractStatusNotRunning"); + if ($objp->date_debut_reelle) { + print dol_print_date($db->jdate($objp->date_debut_reelle), 'day'); + } else { + print $langs->trans("ContractStatusNotRunning"); + } } // Si active et en cours if ($objp->date_debut_reelle && !$objp->date_fin_reelle) { @@ -1861,7 +1829,9 @@ if ($action == 'create') print $langs->trans("DateEndReal").': '; print dol_print_date($db->jdate($objp->date_fin_reelle), 'day'); } - if (!empty($objp->comment)) print "  -  ".$objp->comment; + if (!empty($objp->comment)) { + print "  -  ".$objp->comment; + } print ' 
'; - if ($objp->statut >= 4) - { - if ($objp->statut == 4) - { + if ($objp->statut >= 4) { + if ($objp->statut == 4) { print $langs->trans("DateEndReal").' '; print $form->selectDate($dateactend, "end", $usehm, $usehm, ($objp->date_fin_reelle > 0 ? 0 : 1), "closeline", 1, 1); } @@ -1983,8 +1955,7 @@ if ($action == 'create') print ''; // Form to add new line - if ($user->rights->contrat->creer && ($object->statut == 0)) - { + if ($user->rights->contrat->creer && ($object->statut == 0)) { $dateSelector = 1; print "\n"; @@ -1999,10 +1970,11 @@ if ($action == 'create') print ''; // Array with (n*2)+1 lines // Form to add new line - if ($action != 'editline') - { + if ($action != 'editline') { $forcetoshowtitlelines = 1; - if (empty($object->multicurrency_code)) $object->multicurrency_code = $conf->currency; // TODO Remove this when multicurrency supported on contracts + if (empty($object->multicurrency_code)) { + $object->multicurrency_code = $conf->currency; // TODO Remove this when multicurrency supported on contracts + } // Add free products/services $object->formAddObjectLine(1, $mysoc, $soc); @@ -2020,65 +1992,69 @@ if ($action == 'create') /* - * Buttons - */ + * Buttons + */ - if ($user->socid == 0) - { + if ($user->socid == 0) { print '
'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { // Send if (empty($user->socid)) { if ($object->statut == 1) { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->contrat->creer)) { print ''; - } else print ''; + } else { + print ''; + } } } - if ($object->statut == 0 && $nbofservices) - { - if ($user->rights->contrat->creer) print ''; - else print ''; + if ($object->statut == 0 && $nbofservices) { + if ($user->rights->contrat->creer) { + print ''; + } else { + print ''; + } } - if ($object->statut == 1) - { - if ($user->rights->contrat->creer) print ''; - else print ''; + if ($object->statut == 1) { + if ($user->rights->contrat->creer) { + print ''; + } else { + print ''; + } } - if (!empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) - { + if (!empty($conf->commande->enabled) && $object->statut > 0 && $object->nbofservicesclosed < $nbofservices) { $langs->load("orders"); - if ($user->rights->commande->creer) print ''; - else print ''; + if ($user->rights->commande->creer) { + print ''; + } else { + print ''; + } } - if (!empty($conf->facture->enabled) && $object->statut > 0) - { + if (!empty($conf->facture->enabled) && $object->statut > 0) { $langs->load("bills"); - if ($user->rights->facture->creer) print ''; - else print ''; + if ($user->rights->facture->creer) { + print ''; + } else { + print ''; + } } - if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0) - { - if ($user->rights->contrat->activer) - { + if ($object->nbofservicesclosed > 0 || $object->nbofserviceswait > 0) { + if ($user->rights->contrat->activer) { print ''; } else { print ''; } } - if ($object->nbofservicesclosed < $nbofservices) - { - if ($user->rights->contrat->desactiver) - { + if ($object->nbofservicesclosed < $nbofservices) { + if ($user->rights->contrat->desactiver) { print ''; } else { print ''; @@ -2093,10 +2069,12 @@ if ($action == 'create') //} } - if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->nbofservicesclosed > 0) - { - if ($action == 'showclosedlines') print ''; - else print ''; + if (!empty($conf->global->CONTRACT_HIDE_CLOSED_SERVICES_BY_DEFAULT) && $object->nbofservicesclosed > 0) { + if ($action == 'showclosedlines') { + print ''; + } else { + print ''; + } } // Clone @@ -2107,8 +2085,7 @@ if ($action == 'create') // On peut supprimer entite si // - Droit de creer + mode brouillon (erreur creation) // - Droit de supprimer - if (($user->rights->contrat->creer && $object->statut == $object::STATUS_DRAFT) || $user->rights->contrat->supprimer) - { + if (($user->rights->contrat->creer && $object->statut == $object::STATUS_DRAFT) || $user->rights->contrat->supprimer) { print ''; } else { print ''; @@ -2123,13 +2100,12 @@ if ($action == 'create') $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '
'; /* - * Documents generes - */ + * Documents generes + */ $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->contrat->multidir_output[$object->entity]."/".dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; @@ -2145,8 +2121,7 @@ if ($action == 'create') $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); // Show direct download link - if ($object->statut != Contrat::STATUS_DRAFT && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) - { + if ($object->statut != Contrat::STATUS_DRAFT && !empty($conf->global->CONTRACT_ALLOW_EXTERNAL_DOWNLOAD)) { print '
'."\n"; print showDirectDownloadLink($object).'
'; } @@ -2182,8 +2157,7 @@ $db->close(); ?> margin->enabled) && $action == 'editline') -{ +if (!empty($conf->margin->enabled) && $action == 'editline') { // TODO Why this ? To manage margin on contracts ? ?> rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."contrat as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('contrat').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -143,8 +152,7 @@ class Contracts extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -155,13 +163,11 @@ class Contracts extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $contrat_static = new Contrat($this->db); if ($contrat_static->fetch($obj->rowid)) { @@ -196,12 +202,12 @@ class Contracts extends DolibarrApi $this->contract->$field = $value; } /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->contract->lines = $lines; - }*/ + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->contract->lines = $lines; + }*/ if ($this->contract->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating contract", array_merge(array($this->contract->error), $this->contract->errors)); } @@ -491,7 +497,9 @@ class Contracts extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->contract->$field = $value; } @@ -667,8 +675,9 @@ class Contracts extends DolibarrApi { $contrat = array(); foreach (Contracts::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $contrat[$field] = $data[$field]; } return $contrat; diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 7c99a9483b9..94da51cca8a 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -269,8 +269,7 @@ class Contrat extends CommonObject global $db, $langs, $conf; $langs->load("contracts"); - if (!empty($conf->global->CONTRACT_ADDON)) - { + if (!empty($conf->global->CONTRACT_ADDON)) { $mybool = false; $file = $conf->global->CONTRACT_ADDON.".php"; @@ -286,8 +285,7 @@ class Contrat extends CommonObject $mybool |= @include_once $dir.$file; } - if (!$mybool) - { + if (!$mybool) { dol_print_error('', "Failed to include file ".$file); return ''; } @@ -295,8 +293,7 @@ class Contrat extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -325,8 +322,7 @@ class Contrat extends CommonObject { // phpcs:enable $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->active_line($user, $date, $date_end, $comment); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error; $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors; } @@ -348,8 +344,7 @@ class Contrat extends CommonObject { // phpcs:enable $result = $this->lines[$this->lines_id_index_mapper[$line_id]]->close_line($user, $date_end, $comment); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->lines[$this->lines_id_index_mapper[$line_id]]->error; $this->errors = $this->lines[$this->lines_id_index_mapper[$line_id]]->errors; } @@ -369,7 +364,9 @@ class Contrat extends CommonObject */ public function activateAll($user, $date_start = '', $notrigger = 0, $comment = '') { - if (empty($date_start)) $date_start = dol_now(); + if (empty($date_start)) { + $date_start = dol_now(); + } $this->db->begin(); @@ -378,16 +375,13 @@ class Contrat extends CommonObject // Load lines $this->fetch_lines(); - foreach ($this->lines as $contratline) - { + foreach ($this->lines as $contratline) { // Open lines not already open - if ($contratline->statut != ContratLigne::STATUS_OPEN) - { + if ($contratline->statut != ContratLigne::STATUS_OPEN) { $contratline->context = $this->context; $result = $contratline->active_line($user, $date_start, -1, $comment); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $contratline->error; $this->errors = $contratline->errors; @@ -396,14 +390,14 @@ class Contrat extends CommonObject } } - if (!$error && $this->statut == 0) - { + if (!$error && $this->statut == 0) { $result = $this->validate($user, '', $notrigger); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -432,17 +426,14 @@ class Contrat extends CommonObject $error = 0; - foreach ($this->lines as $contratline) - { + foreach ($this->lines as $contratline) { // Close lines not already closed - if ($contratline->statut != ContratLigne::STATUS_CLOSED) - { + if ($contratline->statut != ContratLigne::STATUS_CLOSED) { $contratline->date_cloture = $now; $contratline->fk_user_cloture = $user->id; $contratline->statut = ContratLigne::STATUS_CLOSED; $result = $contratline->close_line($user, $now, $comment, $notrigger); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $contratline->error; $this->errors = $contratline->errors; @@ -451,14 +442,14 @@ class Contrat extends CommonObject } } - if (!$error && $this->statut == 0) - { + if (!$error && $this->statut == 0) { $result = $this->validate($user, '', $notrigger); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -491,76 +482,69 @@ class Contrat extends CommonObject $this->fetch_thirdparty(); // A contract is validated so we can move thirdparty to status customer - if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION)) - { + if (empty($conf->global->CONTRACT_DISABLE_AUTOSET_AS_CLIENT_ON_CONTRACT_VALIDATION)) { $result = $this->thirdparty->set_as_client(); } // Define new ref - if ($force_number) - { + if ($force_number) { $num = $force_number; - } elseif (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + } elseif (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($this->thirdparty); } else { $num = $this->ref; } $this->newref = dol_sanitizeFileName($num); - if ($num) - { + if ($num) { $sql = "UPDATE ".MAIN_DB_PREFIX."contrat SET ref = '".$this->db->escape($num)."', statut = 1"; //$sql.= ", fk_user_valid = ".$user->id.", date_valid = '".$this->db->idate($now)."'"; $sql .= " WHERE rowid = ".$this->id." AND statut = 0"; dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; $this->error = $this->db->lasterror(); } // Trigger calls - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTRACT_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'contract/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'contract/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->contract->dir_output.'/'.$oldref; $dirdest = $conf->contract->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->contract->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -573,8 +557,7 @@ class Contrat extends CommonObject } // Set new ref and define current statut - if (!$error) - { + if (!$error) { $this->ref = $num; $this->statut = 1; $this->brouillon = 0; @@ -584,8 +567,7 @@ class Contrat extends CommonObject $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -621,16 +603,14 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; $this->error = $this->db->lasterror(); } // Trigger calls - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('CONTRACT_REOPEN', $user); if ($result < 0) { @@ -640,15 +620,13 @@ class Contrat extends CommonObject } // Set new ref and define current status - if (!$error) - { + if (!$error) { $this->statut = 0; $this->brouillon = 1; $this->date_validation = $now; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -678,36 +656,32 @@ class Contrat extends CommonObject $sql .= " fk_commercial_signature, fk_commercial_suivi,"; $sql .= " note_private, note_public, model_pdf, extraparams"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat"; - if (!$id) $sql .= " WHERE entity IN (".getEntity('contract').")"; - else $sql .= " WHERE rowid=".(int) $id; - if ($ref_customer) - { + if (!$id) { + $sql .= " WHERE entity IN (".getEntity('contract').")"; + } else { + $sql .= " WHERE rowid=".(int) $id; + } + if ($ref_customer) { $sql .= " AND ref_customer = '".$this->db->escape($ref_customer)."'"; } - if ($ref_supplier) - { + if ($ref_supplier) { $sql .= " AND ref_supplier = '".$this->db->escape($ref_supplier)."'"; } - if ($ref) - { + if ($ref) { $sql .= " AND ref='".$this->db->escape($ref)."'"; } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 1) - { + if ($num > 1) { $this->error = 'Fetch found several records.'; dol_syslog($this->error, LOG_ERR); $result = -2; - } elseif ($num) // $num = 1 - { + } elseif ($num) { // $num = 1 $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $this->id = $obj->rowid; $this->ref = (!isset($obj->ref) || !$obj->ref) ? $obj->rowid : $obj->ref; $this->ref_customer = $obj->ref_customer; @@ -745,8 +719,7 @@ class Contrat extends CommonObject // Lines $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); return -3; } @@ -791,8 +764,7 @@ class Contrat extends CommonObject $now = dol_now(); - if (!is_object($extrafields)) - { + if (!is_object($extrafields)) { require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; $extrafields = new ExtraFields($this->db); } @@ -825,13 +797,11 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new ContratLigne($this->db); @@ -908,10 +878,18 @@ class Contrat extends CommonObject //dol_syslog("1 ".$line->desc); //dol_syslog("2 ".$line->product_desc); - if ($line->statut == ContratLigne::STATUS_INITIAL) $this->nbofserviceswait++; - if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) $this->nbofservicesopened++; - if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) $this->nbofservicesexpired++; - if ($line->statut == ContratLigne::STATUS_CLOSED) $this->nbofservicesclosed++; + if ($line->statut == ContratLigne::STATUS_INITIAL) { + $this->nbofserviceswait++; + } + if ($line->statut == ContratLigne::STATUS_OPEN && (empty($line->date_fin_prevue) || $line->date_fin_prevue >= $now)) { + $this->nbofservicesopened++; + } + if ($line->statut == ContratLigne::STATUS_OPEN && (!empty($line->date_fin_prevue) && $line->date_fin_prevue < $now)) { + $this->nbofservicesexpired++; + } + if ($line->statut == ContratLigne::STATUS_CLOSED) { + $this->nbofservicesclosed++; + } $total_ttc += $objp->total_ttc; // TODO Not saved into database $total_vat += $objp->total_tva; @@ -946,20 +924,20 @@ class Contrat extends CommonObject // Check parameters $paramsok = 1; - if ($this->commercial_signature_id <= 0) - { + if ($this->commercial_signature_id <= 0) { $langs->load("commercial"); $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeSignature")); $paramsok = 0; } - if ($this->commercial_suivi_id <= 0) - { + if ($this->commercial_suivi_id <= 0) { $langs->load("commercial"); $this->error .= ($this->error ? "
" : ''); $this->error .= $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("SalesRepresentativeFollowUp")); $paramsok = 0; } - if (!$paramsok) return -1; + if (!$paramsok) { + return -1; + } $this->db->begin(); @@ -985,76 +963,66 @@ class Contrat extends CommonObject $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $error = 0; $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."contrat"); // Load object modContract $module = (!empty($conf->global->CONTRACT_ADDON) ? $conf->global->CONTRACT_ADDON : 'mod_contract_serpis'); - if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') - { + if (substr($module, 0, 13) == 'mod_contract_' && substr($module, -3) == 'php') { $module = substr($module, 0, dol_strlen($module) - 4); } $result = dol_include_once('/core/modules/contract/'.$module.'.php'); - if ($result > 0) - { + if ($result > 0) { $modCodeContract = new $module(); if (!empty($modCodeContract->code_auto)) { // Force the ref to a draft value if numbering module is an automatic numbering $sql = 'UPDATE '.MAIN_DB_PREFIX."contrat SET ref='(PROV".$this->id.")' WHERE rowid=".$this->id; - if ($this->db->query($sql)) - { - if ($this->id) - { + if ($this->db->query($sql)) { + if ($this->id) { $this->ref = "(PROV".$this->id.")"; } } } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } // Insert business contacts ('SALESREPSIGN','contrat') - if (!$error) - { + if (!$error) { $result = $this->add_contact($this->commercial_signature_id, 'SALESREPSIGN', 'internal'); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } // Insert business contacts ('SALESREPFOLL','contrat') if (!$error) { $result = $this->add_contact($this->commercial_suivi_id, 'SALESREPFOLL', 'internal'); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if (!$error) { - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -1063,8 +1031,7 @@ class Contrat extends CommonObject { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { $this->error = $this->db->lasterror(); $error++; } @@ -1072,20 +1039,16 @@ class Contrat extends CommonObject } } - if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) // Get contact from origin object - { + if (!$error && $this->id && !empty($conf->global->MAIN_PROPAGATE_CONTACTS_FROM_ORIGIN) && !empty($this->origin) && !empty($this->origin_id)) { // Get contact from origin object $originforcontact = $this->origin; $originidforcontact = $this->origin_id; - if ($originforcontact == 'shipping') // shipment and order share the same contacts. If creating from shipment we take data of order - { + if ($originforcontact == 'shipping') { // shipment and order share the same contacts. If creating from shipment we take data of order require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php'; $exp = new Expedition($this->db); $exp->fetch($this->origin_id); $exp->fetchObjectLinked(); - if (count($exp->linkedObjectsIds['commande']) > 0) - { - foreach ($exp->linkedObjectsIds['commande'] as $key => $value) - { + if (count($exp->linkedObjectsIds['commande']) > 0) { + foreach ($exp->linkedObjectsIds['commande'] as $key => $value) { $originforcontact = 'commande'; $originidforcontact = $value->id; break; // We take first one @@ -1097,28 +1060,30 @@ class Contrat extends CommonObject $sqlcontact .= " WHERE element_id = ".$originidforcontact." AND ec.fk_c_type_contact = ctc.rowid AND ctc.element = '".$this->db->escape($originforcontact)."'"; $resqlcontact = $this->db->query($sqlcontact); - if ($resqlcontact) - { - while ($objcontact = $this->db->fetch_object($resqlcontact)) - { - if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) continue; // ignore this, already forced previously + if ($resqlcontact) { + while ($objcontact = $this->db->fetch_object($resqlcontact)) { + if ($objcontact->source == 'internal' && in_array($objcontact->code, array('SALESREPSIGN', 'SALESREPFOLL'))) { + continue; // ignore this, already forced previously + } //print $objcontact->code.'-'.$objcontact->source.'-'.$objcontact->fk_socpeople."\n"; $this->add_contact($objcontact->fk_socpeople, $objcontact->code, $objcontact->source); // May failed because of duplicate key or because code of contact type does not exists for new object } - } else dol_print_error($resqlcontact); + } else { + dol_print_error($resqlcontact); + } } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('CONTRACT_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1158,29 +1123,29 @@ class Contrat extends CommonObject // Call trigger $result = $this->call_trigger('CONTRACT_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { // Delete linked contacts $res = $this->delete_linked_contact(); - if ($res < 0) - { + if ($res < 0) { dol_syslog(get_class($this)."::delete error", LOG_ERR); $error++; } } - if (!$error) - { + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete contratdet_log /* $sql = "DELETE cdl"; @@ -1193,17 +1158,14 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } $numressql = $this->db->num_rows($resql); - if (!$error && $numressql) - { + if (!$error && $numressql) { $tab_resql = array(); - for ($i = 0; $i < $numressql; $i++) - { + for ($i = 0; $i < $numressql; $i++) { $objresql = $this->db->fetch_object($resql); $tab_resql[] = $objresql->cdlrowid; } @@ -1214,8 +1176,7 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::delete contratdet_log", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } @@ -1231,23 +1192,20 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::delete contratdet_extrafields", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } } - if (!$error) - { + if (!$error) { // Delete contratdet $sql = "DELETE FROM ".MAIN_DB_PREFIX."contratdet"; $sql .= " WHERE fk_contrat=".$this->id; dol_syslog(get_class($this)."::delete contratdet", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } @@ -1257,8 +1215,7 @@ class Contrat extends CommonObject if (!$error) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX."ecm_files WHERE src_object_type = '".$this->db->escape($this->table_element.(empty($this->module) ? '' : '@'.$this->module))."' AND src_object_id = ".$this->id; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $this->errors[] = $this->error; $error++; @@ -1266,15 +1223,13 @@ class Contrat extends CommonObject } // Delete contract - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."contrat"; $sql .= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::delete contrat", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->error(); $error++; } @@ -1283,25 +1238,20 @@ class Contrat extends CommonObject // Removed extrafields if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR); } } - if (!$error) - { + if (!$error) { // We remove directory $ref = dol_sanitizeFileName($this->ref); - if ($conf->contrat->dir_output) - { + if ($conf->contrat->dir_output) { $dir = $conf->contrat->multidir_output[$this->entity]."/".$ref; - if (file_exists($dir)) - { + if (file_exists($dir)) { $res = @dol_delete_dir_recursive($dir); - if (!$res) - { + if (!$res) { $this->error = 'ErrorFailToDeleteDir'; $error++; } @@ -1309,8 +1259,7 @@ class Contrat extends CommonObject } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1333,23 +1282,55 @@ class Contrat extends CommonObject $error = 0; // Clean parameters - if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) $this->fk_commercial_signature = $this->commercial_signature_id; - if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) $this->fk_commercial_suivi = $this->commercial_suivi_id; - if (empty($this->fk_soc) && $this->socid > 0) $this->fk_soc = (int) $this->socid; - if (empty($this->fk_project) && $this->projet > 0) $this->fk_project = (int) $this->projet; + if (empty($this->fk_commercial_signature) && $this->commercial_signature_id > 0) { + $this->fk_commercial_signature = $this->commercial_signature_id; + } + if (empty($this->fk_commercial_suivi) && $this->commercial_suivi_id > 0) { + $this->fk_commercial_suivi = $this->commercial_suivi_id; + } + if (empty($this->fk_soc) && $this->socid > 0) { + $this->fk_soc = (int) $this->socid; + } + if (empty($this->fk_project) && $this->projet > 0) { + $this->fk_project = (int) $this->projet; + } - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->ref_customer)) $this->ref_customer = trim($this->ref_customer); - if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier); - if (isset($this->ref_ext)) $this->ref_ext = trim($this->ref_ext); - if (isset($this->entity)) $this->entity = (int) $this->entity; - if (isset($this->statut)) $this->statut = (int) $this->statut; - if (isset($this->fk_soc)) $this->fk_soc = (int) $this->fk_soc; - if (isset($this->fk_commercial_signature)) $this->fk_commercial_signature = trim($this->fk_commercial_signature); - if (isset($this->fk_commercial_suivi)) $this->fk_commercial_suivi = trim($this->fk_commercial_suivi); - if (isset($this->note_private)) $this->note_private = trim($this->note_private); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->ref_customer)) { + $this->ref_customer = trim($this->ref_customer); + } + if (isset($this->ref_supplier)) { + $this->ref_supplier = trim($this->ref_supplier); + } + if (isset($this->ref_ext)) { + $this->ref_ext = trim($this->ref_ext); + } + if (isset($this->entity)) { + $this->entity = (int) $this->entity; + } + if (isset($this->statut)) { + $this->statut = (int) $this->statut; + } + if (isset($this->fk_soc)) { + $this->fk_soc = (int) $this->fk_soc; + } + if (isset($this->fk_commercial_signature)) { + $this->fk_commercial_signature = trim($this->fk_commercial_signature); + } + if (isset($this->fk_commercial_suivi)) { + $this->fk_commercial_suivi = trim($this->fk_commercial_suivi); + } + if (isset($this->note_private)) { + $this->note_private = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } //if (isset($this->extraparams)) $this->extraparams=trim($this->extraparams); // Check parameters @@ -1377,30 +1358,29 @@ class Contrat extends CommonObject $this->db->begin(); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call triggers $result = $this->call_trigger('CONTRACT_MODIFY', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1444,14 +1424,12 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type, $pu_ttc, $info_bits, $rang"); // Check parameters - if ($fk_product <= 0 && empty($desc)) - { + if ($fk_product <= 0 && empty($desc)) { $this->error = "ErrorDescRequiredForFreeProductLines"; return -1; } - if ($this->statut >= 0) - { + if ($this->statut >= 0) { // Clean parameters $pu_ht = price2num($pu_ht); $pu_ttc = price2num($pu_ttc); @@ -1460,8 +1438,7 @@ class Contrat extends CommonObject // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -1471,23 +1448,38 @@ class Contrat extends CommonObject $remise_percent = price2num($remise_percent); $qty = price2num($qty); - if (empty($qty)) $qty = 1; - if (empty($info_bits)) $info_bits = 0; - if (empty($pu_ht) || !is_numeric($pu_ht)) $pu_ht = 0; - if (empty($pu_ttc)) $pu_ttc = 0; - if (empty($txtva) || !is_numeric($txtva)) $txtva = 0; - if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) $txlocaltax2 = 0; + if (empty($qty)) { + $qty = 1; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($pu_ht) || !is_numeric($pu_ht)) { + $pu_ht = 0; + } + if (empty($pu_ttc)) { + $pu_ttc = 0; + } + if (empty($txtva) || !is_numeric($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1) || !is_numeric($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2) || !is_numeric($txlocaltax2)) { + $txlocaltax2 = 0; + } - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; } // Check parameters - if (empty($remise_percent)) $remise_percent = 0; + if (empty($remise_percent)) { + $remise_percent = 0; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); @@ -1518,20 +1510,19 @@ class Contrat extends CommonObject // Anciens indicateurs: $price, $remise (a ne plus utiliser) $remise = 0; $price = price2num(round($pu_ht, 2)); - if (dol_strlen($remise_percent) > 0) - { + if (dol_strlen($remise_percent) > 0) { $remise = round(($pu_ht * $remise_percent / 100), 2); $price = $pu_ht - $remise; } - if (empty($pa_ht)) $pa_ht = 0; + if (empty($pa_ht)) { + $pa_ht = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) - { - if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) - { + if ($this->pa_ht == 0) { + if (($result = $this->defineBuyPrice($pu_ht, $remise_percent, $fk_product)) < 0) { return $result; } else { $pa_ht = $result; @@ -1545,8 +1536,12 @@ class Contrat extends CommonObject $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,"; $sql .= " info_bits,"; $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht"; - if ($date_start > 0) { $sql .= ",date_ouverture_prevue"; } - if ($date_end > 0) { $sql .= ",date_fin_validite"; } + if ($date_start > 0) { + $sql .= ",date_ouverture_prevue"; + } + if ($date_end > 0) { + $sql .= ",date_fin_validite"; + } $sql .= ", fk_unit"; $sql .= ") VALUES ("; $sql .= $this->id.", '', '".$this->db->escape($desc)."',"; @@ -1563,28 +1558,35 @@ class Contrat extends CommonObject $sql .= " ".price2num($total_ht).",".price2num($total_tva).",".price2num($total_localtax1).",".price2num($total_localtax2).",".price2num($total_ttc).","; $sql .= " '".$this->db->escape($info_bits)."',"; $sql .= " ".price2num($price).",".price2num($remise).","; - if (isset($fk_fournprice)) $sql .= ' '.$fk_fournprice.','; - else $sql .= ' null,'; - if (isset($pa_ht)) $sql .= ' '.price2num($pa_ht); - else $sql .= ' null'; - if ($date_start > 0) { $sql .= ",'".$this->db->idate($date_start)."'"; } - if ($date_end > 0) { $sql .= ",'".$this->db->idate($date_end)."'"; } + if (isset($fk_fournprice)) { + $sql .= ' '.$fk_fournprice.','; + } else { + $sql .= ' null,'; + } + if (isset($pa_ht)) { + $sql .= ' '.price2num($pa_ht); + } else { + $sql .= ' null'; + } + if ($date_start > 0) { + $sql .= ",'".$this->db->idate($date_start)."'"; + } + if ($date_end > 0) { + $sql .= ",'".$this->db->idate($date_end)."'"; + } $sql .= ", ".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null"); $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $contractlineid = $this->db->last_insert_id(MAIN_DB_PREFIX."contratdet"); - if (!$error) - { + if (!$error) { $contractline = new ContratLigne($this->db); $contractline->array_options = $array_options; $contractline->id = $contractlineid; $result = $contractline->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->error[] = $contractline->error; $error++; } @@ -1593,15 +1595,13 @@ class Contrat extends CommonObject if (empty($error)) { // Call trigger $result = $this->call_trigger('LINECONTRACT_INSERT', $user); - if ($result < 0) - { + if ($result < 0) { $error++; } // End call triggers } - if ($error) - { + if ($error) { $this->db->rollback(); return -1; } else { @@ -1657,12 +1657,13 @@ class Contrat extends CommonObject $localtax1tx = price2num($localtax1tx); $localtax2tx = price2num($localtax2tx); $pa_ht = price2num($pa_ht); - if (empty($fk_fournprice)) $fk_fournprice = 0; + if (empty($fk_fournprice)) { + $fk_fournprice = 0; + } $subprice = $price; $remise = 0; - if (dol_strlen($remise_percent) > 0) - { + if (dol_strlen($remise_percent) > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } else { @@ -1701,19 +1702,18 @@ class Contrat extends CommonObject // Anciens indicateurs: $price, $remise (a ne plus utiliser) $remise = 0; $price = price2num(round($pu, 2)); - if (dol_strlen($remise_percent) > 0) - { + if (dol_strlen($remise_percent) > 0) { $remise = round(($pu * $remise_percent / 100), 2); $price = $pu - $remise; } - if (empty($pa_ht)) $pa_ht = 0; + if (empty($pa_ht)) { + $pa_ht = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) - { - if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) - { + if ($this->pa_ht == 0) { + if (($result = $this->defineBuyPrice($pu, $remise_percent)) < 0) { return $result; } else { $pa_ht = $result; @@ -1738,22 +1738,35 @@ class Contrat extends CommonObject $sql .= ", total_ttc='".price2num($total_ttc)."'"; $sql .= ", fk_product_fournisseur_price=".($fk_fournprice > 0 ? $fk_fournprice : "null"); $sql .= ", buy_price_ht='".price2num($pa_ht)."'"; - if ($date_start > 0) { $sql .= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; } else { $sql .= ",date_ouverture_prevue=null"; } - if ($date_end > 0) { $sql .= ",date_fin_validite='".$this->db->idate($date_end)."'"; } else { $sql .= ",date_fin_validite=null"; } - if ($date_debut_reel > 0) { $sql .= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; } else { $sql .= ",date_ouverture=null"; } - if ($date_fin_reel > 0) { $sql .= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; } else { $sql .= ",date_cloture=null"; } + if ($date_start > 0) { + $sql .= ",date_ouverture_prevue='".$this->db->idate($date_start)."'"; + } else { + $sql .= ",date_ouverture_prevue=null"; + } + if ($date_end > 0) { + $sql .= ",date_fin_validite='".$this->db->idate($date_end)."'"; + } else { + $sql .= ",date_fin_validite=null"; + } + if ($date_debut_reel > 0) { + $sql .= ",date_ouverture='".$this->db->idate($date_debut_reel)."'"; + } else { + $sql .= ",date_ouverture=null"; + } + if ($date_fin_reel > 0) { + $sql .= ",date_cloture='".$this->db->idate($date_fin_reel)."'"; + } else { + $sql .= ",date_cloture=null"; + } $sql .= ", fk_unit=".($fk_unit ? "'".$this->db->escape($fk_unit)."'" : "null"); $sql .= " WHERE rowid = ".$rowid; dol_syslog(get_class($this)."::updateline", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $result = $this->update_statut($user); - if ($result >= 0) - { - if (is_array($array_options) && count($array_options) > 0) // For avoid conflicts if trigger used - { + if ($result >= 0) { + if (is_array($array_options) && count($array_options) > 0) { // For avoid conflicts if trigger used $contractline = new ContratLigne($this->db); $contractline->fetch($rowid); $contractline->fetch_optionals(); @@ -1764,8 +1777,7 @@ class Contrat extends CommonObject } $result = $contractline->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->error[] = $contractline->error; $error++; } @@ -1774,8 +1786,7 @@ class Contrat extends CommonObject if (empty($error)) { // Call trigger $result = $this->call_trigger('LINECONTRACT_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -3; } @@ -1810,11 +1821,12 @@ class Contrat extends CommonObject $error = 0; - if ($this->statut >= 0) - { + if ($this->statut >= 0) { // Call trigger $result = $this->call_trigger('LINECONTRACT_DELETE', $user); - if ($result < 0) return -1; + if ($result < 0) { + return -1; + } // End call triggers $this->db->begin(); @@ -1824,8 +1836,7 @@ class Contrat extends CommonObject dol_syslog(get_class($this)."::deleteline", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = "Error ".$this->db->lasterror(); $error++; } @@ -1835,8 +1846,7 @@ class Contrat extends CommonObject $contractline = new ContratLigne($this->db); $contractline->id = $idline; $result = $contractline->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = "Error ".get_class($this)."::deleteline deleteExtraFields error -4 ".$contractline->error; } @@ -1871,7 +1881,9 @@ class Contrat extends CommonObject dol_syslog(__METHOD__." is deprecated", LOG_WARNING); // If draft, we keep it (should not happen) - if ($this->statut == 0) return 1; + if ($this->statut == 0) { + return 1; + } // Load $this->lines array // $this->fetch_lines(); @@ -1910,8 +1922,7 @@ class Contrat extends CommonObject // phpcs:enable global $langs; - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; $langs->load("contracts"); $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('ContractStatusDraft'); @@ -1923,10 +1934,11 @@ class Contrat extends CommonObject } $statusType = 'status'.$status; - if ($status == self::STATUS_VALIDATED) $statusType = 'status6'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status6'; + } - if ($mode == 4 || $mode == 6 || $mode == 7) - { + if ($mode == 4 || $mode == 6 || $mode == 7) { $text = ''; if ($mode == 4) { $text = ''; @@ -1972,8 +1984,12 @@ class Contrat extends CommonObject //{ // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } //} $label = ''; @@ -1999,10 +2015,8 @@ class Contrat extends CommonObject } $linkclose = ''; - if (empty($notooltip) && $user->rights->contrat->lire) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip) && $user->rights->contrat->lire) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowOrder"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -2015,8 +2029,12 @@ class Contrat extends CommonObject $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($this->ref ? $this->ref : $this->id); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= ($this->ref ? $this->ref : $this->id); + } $result .= $linkend; global $action; @@ -2047,10 +2065,8 @@ class Contrat extends CommonObject $sql .= " WHERE c.rowid = ".((int) $id); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; @@ -2087,16 +2103,16 @@ class Contrat extends CommonObject $sql = "SELECT cd.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= " WHERE fk_contrat =".$this->id; - if ($status >= 0) $sql .= " AND statut = ".$status; + if ($status >= 0) { + $sql .= " AND statut = ".$status; + } dol_syslog(get_class($this)."::array_detail()", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $tab[$i] = $obj->rowid; $i++; @@ -2121,16 +2137,16 @@ class Contrat extends CommonObject $sql = "SELECT c.rowid, c.ref"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c"; $sql .= " WHERE fk_soc =".$this->socid; - if ($option == 'others') $sql .= " AND c.rowid != ".$this->id; + if ($option == 'others') { + $sql .= " AND c.rowid != ".$this->id; + } dol_syslog(get_class($this)."::getOtherContracts()", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $contrat = new Contrat($this->db); $contrat->fetch($obj->rowid); @@ -2161,25 +2177,24 @@ class Contrat extends CommonObject $this->from = " FROM ".MAIN_DB_PREFIX."contrat as c"; $this->from .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $this->from .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$user->socid) $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$user->socid) { + $this->from .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } - if ($mode == 'inactive') - { + if ($mode == 'inactive') { $sql = "SELECT cd.rowid, cd.date_ouverture_prevue as datefin"; $sql .= $this->from; $sql .= " WHERE c.statut = 1"; $sql .= " AND c.rowid = cd.fk_contrat"; $sql .= " AND cd.statut = 0"; - } elseif ($mode == 'expired') - { + } elseif ($mode == 'expired') { $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin"; $sql .= $this->from; $sql .= " WHERE c.statut = 1"; $sql .= " AND c.rowid = cd.fk_contrat"; $sql .= " AND cd.statut = 4"; $sql .= " AND cd.date_fin_validite < '".$this->db->idate(dol_now())."'"; - } elseif ($mode == 'active') - { + } elseif ($mode == 'active') { $sql = "SELECT cd.rowid, cd.date_fin_validite as datefin"; $sql .= $this->from; $sql .= " WHERE c.statut = 1"; @@ -2190,12 +2205,15 @@ class Contrat extends CommonObject } $sql .= " AND c.fk_soc = s.rowid"; $sql .= " AND c.entity = ".$conf->entity; - if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) { + $sql .= " AND c.fk_soc = ".$user->socid; + } + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $langs->load("contracts"); $now = dol_now(); @@ -2225,8 +2243,7 @@ class Contrat extends CommonObject $response->url = $url; $response->img = img_object('', "contract"); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; if ($obj->datefin && $this->db->jdate($obj->datefin) < ($now - $warning_delay)) { @@ -2259,8 +2276,7 @@ class Contrat extends CommonObject $sql = "SELECT count(c.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON c.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -2268,10 +2284,8 @@ class Contrat extends CommonObject $sql .= " ".$clause." c.entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["contracts"] = $obj->nb; } $this->db->free($resql); @@ -2328,12 +2342,10 @@ class Contrat extends CommonObject $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -2359,8 +2371,7 @@ class Contrat extends CommonObject // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new ContratLigne($this->db); $line->qty = 1; $line->subprice = 100; @@ -2374,8 +2385,7 @@ class Contrat extends CommonObject $line->date_start_real = dol_now() - 200000; $line->date_end = dol_now() + 500000; $line->date_end_real = dol_now() - 100000; - if ($num_prods > 0) - { + if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; } @@ -2478,15 +2488,12 @@ class Contrat extends CommonObject // Clean data $clonedObj->statut = 0; // Clean extrafields - if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) - { + if (is_array($clonedObj->array_options) && count($clonedObj->array_options) > 0) { $extrafields->fetch_name_optionals_label($this->table_element); - foreach ($clonedObj->array_options as $key => $option) - { + foreach ($clonedObj->array_options as $key => $option) { $shortkey = preg_replace('/options_/', '', $key); //var_dump($shortkey); var_dump($extrafields->attributes[$this->element]['unique'][$shortkey]); - if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) - { + if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) { //var_dump($key); var_dump($clonedObj->array_options[$key]); exit; unset($clonedObj->array_options[$key]); } @@ -2546,8 +2553,9 @@ class Contrat extends CommonObject ); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $clonedObj, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) + if ($reshook < 0) { $error++; + } } } @@ -2756,12 +2764,15 @@ class ContratLigne extends CommonObjectLine } $statusType = 'status'.$status; - if ($status == self::STATUS_OPEN && $expired == 1) $statusType = 'status1'; - if ($status == self::STATUS_CLOSED) $statusType = 'status6'; + if ($status == self::STATUS_OPEN && $expired == 1) { + $statusType = 'status1'; + } + if ($status == self::STATUS_CLOSED) { + $statusType = 'status6'; + } $params = array(); $reg = array(); - if (preg_match('/class="(.*)"/', $moreatt, $reg)) - { + if (preg_match('/class="(.*)"/', $moreatt, $reg)) { $params = array('badgeParams'=>array('css' => $reg[1])); } return dolGetStatus($labelStatus, $labelStatusShort, '', $statusType, $mode, '', $params); @@ -2780,17 +2791,27 @@ class ContratLigne extends CommonObjectLine $result = ''; $label = $langs->trans("ShowContractOfService").': '.$this->label; - if (empty($label)) $label = $this->description; + if (empty($label)) { + $label = $this->description; + } $link = ''; $linkend = ''; $picto = 'service'; - if ($this->type == 0) $picto = 'product'; + if ($this->type == 0) { + $picto = 'product'; + } - if ($withpicto) $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, $picto, 'class="classfortooltip"').$linkend); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.($this->product_ref ? $this->product_ref.' ' : '').($this->label ? $this->label : $this->description).$linkend; + } return $result; } @@ -2804,7 +2825,9 @@ class ContratLigne extends CommonObjectLine public function fetch($id, $ref = '') { // Check parameters - if (empty($id) && empty($ref)) return -1; + if (empty($id) && empty($ref)) { + return -1; + } $sql = "SELECT"; $sql .= " t.rowid,"; @@ -2849,15 +2872,17 @@ class ContratLigne extends CommonObjectLine $sql .= " t.commentaire,"; $sql .= " t.fk_unit"; $sql .= " FROM ".MAIN_DB_PREFIX."contratdet as t LEFT JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = t.fk_product"; - if ($id) $sql .= " WHERE t.rowid = ".$id; - if ($ref) $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'"; + if ($id) { + $sql .= " WHERE t.rowid = ".$id; + } + if ($ref) { + $sql .= " WHERE t.rowid = '".$this->db->escape($ref)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -2966,18 +2991,40 @@ class ContratLigne extends CommonObjectLine $this->fk_user_cloture = (int) $this->fk_user_cloture; $this->commentaire = trim($this->commentaire); //if (empty($this->subprice)) $this->subprice = 0; - if (empty($this->price_ht)) $this->price_ht = 0; - if (empty($this->total_ht)) $this->total_ht = 0; - if (empty($this->total_tva)) $this->total_tva = 0; - if (empty($this->total_ttc)) $this->total_ttc = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; + if (empty($this->price_ht)) { + $this->price_ht = 0; + } + if (empty($this->total_ht)) { + $this->total_ht = 0; + } + if (empty($this->total_tva)) { + $this->total_tva = 0; + } + if (empty($this->total_ttc)) { + $this->total_ttc = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } // For backward compatibility - if (empty($this->date_start)) $this->date_start = $this->date_ouverture_prevue; - if (empty($this->date_start_real)) $this->date_start = $this->date_ouverture; - if (empty($this->date_end)) $this->date_start = $this->date_fin_validite; - if (empty($this->date_end_real)) $this->date_start = $this->date_cloture; + if (empty($this->date_start)) { + $this->date_start = $this->date_ouverture_prevue; + } + if (empty($this->date_start_real)) { + $this->date_start = $this->date_ouverture; + } + if (empty($this->date_end)) { + $this->date_start = $this->date_fin_validite; + } + if (empty($this->date_end_real)) { + $this->date_start = $this->date_cloture; + } // Check parameters @@ -2996,13 +3043,13 @@ class ContratLigne extends CommonObjectLine $this->total_localtax1 = $tabprice[9]; $this->total_localtax2 = $tabprice[10]; - if (empty($this->pa_ht)) $this->pa_ht = 0; + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } // if buy price not defined, define buyprice as configured in margin admin - if ($this->pa_ht == 0) - { - if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) - { + if ($this->pa_ht == 0) { + if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0) { return $result; } else { $this->pa_ht = $result; @@ -3055,46 +3102,38 @@ class ContratLigne extends CommonObjectLine dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = "Error ".$this->db->lasterror(); $error++; } - if (!$error) // For avoid conflicts if trigger used - { + if (!$error) { // For avoid conflicts if trigger used $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } // If we change a planned date (start or end), sync dates for all services - if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) - { - if ($this->date_ouverture_prevue != $this->oldcopy->date_ouverture_prevue) - { + if (!$error && !empty($conf->global->CONTRACT_SYNC_PLANNED_DATE_OF_SERVICES)) { + if ($this->date_ouverture_prevue != $this->oldcopy->date_ouverture_prevue) { $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET'; $sql .= " date_ouverture_prevue = ".($this->date_ouverture_prevue != '' ? "'".$this->db->idate($this->date_ouverture_prevue)."'" : "null"); $sql .= " WHERE fk_contrat = ".$this->fk_contrat; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = "Error ".$this->db->lasterror(); } } - if ($this->date_fin_validite != $this->oldcopy->date_fin_validite) - { + if ($this->date_fin_validite != $this->oldcopy->date_fin_validite) { $sql = 'UPDATE '.MAIN_DB_PREFIX.'contratdet SET'; $sql .= " date_fin_validite = ".($this->date_fin_validite != '' ? "'".$this->db->idate($this->date_fin_validite)."'" : "null"); $sql .= " WHERE fk_contrat = ".$this->fk_contrat; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $error++; $this->error = "Error ".$this->db->lasterror(); } @@ -3111,8 +3150,7 @@ class ContratLigne extends CommonObjectLine // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -3147,8 +3185,7 @@ class ContratLigne extends CommonObjectLine dol_syslog(get_class($this)."::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -3178,8 +3215,12 @@ class ContratLigne extends CommonObjectLine $sql .= " total_ht, total_tva, total_localtax1, total_localtax2, total_ttc,"; $sql .= " info_bits,"; $sql .= " price_ht, remise, fk_product_fournisseur_price, buy_price_ht"; - if ($this->date_ouverture_prevue > 0) { $sql .= ",date_ouverture_prevue"; } - if ($this->date_fin_validite > 0) { $sql .= ",date_fin_validite"; } + if ($this->date_ouverture_prevue > 0) { + $sql .= ",date_ouverture_prevue"; + } + if ($this->date_fin_validite > 0) { + $sql .= ",date_fin_validite"; + } $sql .= ") VALUES ($this->fk_contrat, '', '".$this->db->escape($this->description)."',"; $sql .= ($this->fk_product > 0 ? $this->fk_product : "null").","; $sql .= " '".$this->db->escape($this->qty)."',"; @@ -3193,34 +3234,40 @@ class ContratLigne extends CommonObjectLine $sql .= " ".price2num($this->total_ht).",".price2num($this->total_tva).",".price2num($this->total_localtax1).",".price2num($this->total_localtax2).",".price2num($this->total_ttc).","; $sql .= " '".$this->db->escape($this->info_bits)."',"; $sql .= " ".price2num($this->price_ht).",".price2num($this->remise).","; - if ($this->fk_fournprice > 0) $sql .= ' '.$this->fk_fournprice.','; - else $sql .= ' null,'; - if ($this->pa_ht > 0) $sql .= ' '.price2num($this->pa_ht); - else $sql .= ' null'; - if ($this->date_ouverture > 0) { $sql .= ",'".$this->db->idate($this->date_ouverture)."'"; } - if ($this->date_cloture > 0) { $sql .= ",'".$this->db->idate($this->date_cloture)."'"; } + if ($this->fk_fournprice > 0) { + $sql .= ' '.$this->fk_fournprice.','; + } else { + $sql .= ' null,'; + } + if ($this->pa_ht > 0) { + $sql .= ' '.price2num($this->pa_ht); + } else { + $sql .= ' null'; + } + if ($this->date_ouverture > 0) { + $sql .= ",'".$this->db->idate($this->date_ouverture)."'"; + } + if ($this->date_cloture > 0) { + $sql .= ",'".$this->db->idate($this->date_cloture)."'"; + } $sql .= ")"; dol_syslog(get_class($this)."::insert", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'contratdet'); // Insert of extrafields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } } - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINECONTRACT_INSERT', $user); if ($result < 0) { @@ -3260,7 +3307,9 @@ class ContratLigne extends CommonObjectLine $sql = "UPDATE ".MAIN_DB_PREFIX."contratdet SET statut = ".ContratLigne::STATUS_OPEN.","; $sql .= " date_ouverture = ".(dol_strlen($date) != 0 ? "'".$this->db->idate($date)."'" : "null").","; - if ($date_end >= 0) $sql .= " date_fin_validite = ".(dol_strlen($date_end) != 0 ? "'".$this->db->idate($date_end)."'" : "null").","; + if ($date_end >= 0) { + $sql .= " date_fin_validite = ".(dol_strlen($date_end) != 0 ? "'".$this->db->idate($date_end)."'" : "null").","; + } $sql .= " fk_user_ouverture = ".$user->id.","; $sql .= " date_cloture = null,"; $sql .= " commentaire = '".$this->db->escape($comment)."'"; @@ -3271,11 +3320,12 @@ class ContratLigne extends CommonObjectLine if ($resql) { // Call trigger $result = $this->call_trigger('LINECONTRACT_ACTIVATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if (!$error) - { + if (!$error) { $this->statut = ContratLigne::STATUS_OPEN; $this->date_ouverture = $date; $this->date_fin_validite = $date_end; @@ -3329,10 +3379,8 @@ class ContratLigne extends CommonObjectLine $sql .= " WHERE rowid = ".$this->id." AND statut = ".ContratLigne::STATUS_OPEN; $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { + if ($resql) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINECONTRACT_CLOSE', $user); if ($result < 0) { diff --git a/htdocs/contrat/contact.php b/htdocs/contrat/contact.php index c837769819a..35b7268109b 100644 --- a/htdocs/contrat/contact.php +++ b/htdocs/contrat/contact.php @@ -43,7 +43,9 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); $object = new Contrat($db); @@ -56,19 +58,16 @@ $hookmanager->initHooks(array('contractcard', 'globalcard')); * Actions */ -if ($action == 'addcontact' && $user->rights->contrat->creer) -{ +if ($action == 'addcontact' && $user->rights->contrat->creer) { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -84,10 +83,8 @@ if ($action == 'addcontact' && $user->rights->contrat->creer) } // bascule du statut d'un contact -if ($action == 'swapstatut' && $user->rights->contrat->creer) -{ - if ($object->fetch($id)) - { +if ($action == 'swapstatut' && $user->rights->contrat->creer) { + if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db, $object->error); @@ -95,13 +92,11 @@ if ($action == 'swapstatut' && $user->rights->contrat->creer) } // Delete contact -if ($action == 'deletecontact' && $user->rights->contrat->creer) -{ +if ($action == 'deletecontact' && $user->rights->contrat->creer) { $object->fetch($id); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } @@ -125,10 +120,8 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $head = contract_prepare_head($object); @@ -146,9 +139,9 @@ if ($id > 0 || !empty($ref)) //if (! empty($modCodeContract->code_auto)) { $morehtmlref .= $object->ref; /*} else { - $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); - $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); - }*/ + $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); + $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); + }*/ $morehtmlref .= '
'; // Ref customer @@ -213,8 +206,11 @@ if ($id > 0 || !empty($ref)) } $absolute_discount = $object->thirdparty->getAvailableDiscounts(); print '. '; - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($absolute_discount) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); + } else { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + } print '.'; print ''; diff --git a/htdocs/contrat/document.php b/htdocs/contrat/document.php index dfdb0fe6d31..8e5b1281c47 100644 --- a/htdocs/contrat/document.php +++ b/htdocs/contrat/document.php @@ -46,8 +46,7 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { unset($_GET["action"]); $action = ''; $socid = $user->socid; @@ -59,18 +58,23 @@ $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 +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 = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} $object = new Contrat($db); $object->fetch($id, $ref); -if ($object->id > 0) -{ +if ($object->id > 0) { $object->fetch_thirdparty(); } @@ -97,8 +101,7 @@ $form = new Form($db); llxHeader('', $langs->trans("Contract"), ""); -if ($object->id) -{ +if ($object->id) { $head = contract_prepare_head($object); print dol_get_fiche_head($head, 'documents', $langs->trans("Contract"), -1, 'contract'); @@ -107,8 +110,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -136,17 +138,18 @@ if ($object->id) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1, 'getFormatedSupplierRef'); // Thirdparty $morehtmlref .= '
'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherContracts").')'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
'.$langs->trans('Project').' '; - if ($user->rights->contrat->creer) - { - if ($action != 'classify') + if ($user->rights->contrat->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 .= '
'; diff --git a/htdocs/contrat/index.php b/htdocs/contrat/index.php index 5ea558c9689..6b1aecf1162 100644 --- a/htdocs/contrat/index.php +++ b/htdocs/contrat/index.php @@ -46,7 +46,9 @@ $statut = GETPOST('statut') ?GETPOST('statut') : 1; // Security check $socid = 0; $id = GETPOST('id', 'int'); -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); $staticcompany = new Societe($db); @@ -78,11 +80,9 @@ print load_fiche_titre($langs->trans("ContractsArea"), '', 'contract'); print '
'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search contract - if (!empty($conf->contrat->enabled)) - { + if (!empty($conf->contrat->enabled)) { print ''; print ''; @@ -112,26 +112,28 @@ $vals = array(); $sql = "SELECT count(cd.rowid) as nb, cd.statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE cd.fk_contrat = c.rowid AND c.fk_soc = s.rowid"; $sql .= " AND (cd.statut != 4 OR (cd.statut = 4 AND (cd.date_fin_validite is null or cd.date_fin_validite >= '".$db->idate($now)."')))"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")"; -if ($user->socid) $sql .= ' AND c.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND c.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY cd.statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $nb[$obj->status] = $obj->nb; - if ($obj->status != 5) - { + if ($obj->status != 5) { $vals[$obj->status] = $obj->nb; $totalinprocess += $obj->nb; } @@ -147,28 +149,30 @@ if ($resql) $sql = "SELECT count(cd.rowid) as nb, cd.statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd, ".MAIN_DB_PREFIX."contrat as c"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE cd.fk_contrat = c.rowid AND c.fk_soc = s.rowid"; $sql .= " AND (cd.statut = 4 AND cd.date_fin_validite < '".$db->idate($now)."')"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")"; -if ($user->socid) $sql .= ' AND c.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND c.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY cd.statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); // 0 inactive, 4 active, 5 closed $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $nb[$obj->status.true] = $obj->nb; - if ($obj->status != 5) - { + if ($obj->status != 5) { $vals[$obj->status.true] = $obj->nb; $totalinprocess += $obj->nb; } @@ -189,26 +193,34 @@ print '
'; print '
'; print ''."\n"; $listofstatus = array(0, 4, 4, 5); $bool = false; -foreach ($listofstatus as $status) -{ +foreach ($listofstatus as $status) { $dataseries[] = array($staticcontratligne->LibStatut($status, 1, ($bool ? 1 : 0)), (isset($nb[$status.$bool]) ? (int) $nb[$status.$bool] : 0)); - if ($status == ContratLigne::STATUS_INITIAL) $colorseries[$status.$bool] = '-'.$badgeStatus0; - if ($status == ContratLigne::STATUS_OPEN && !$bool) $colorseries[$status.$bool] = $badgeStatus4; - if ($status == ContratLigne::STATUS_OPEN && $bool) $colorseries[$status.$bool] = $badgeStatus1; - if ($status == ContratLigne::STATUS_CLOSED) $colorseries[$status.$bool] = $badgeStatus6; + if ($status == ContratLigne::STATUS_INITIAL) { + $colorseries[$status.$bool] = '-'.$badgeStatus0; + } + if ($status == ContratLigne::STATUS_OPEN && !$bool) { + $colorseries[$status.$bool] = $badgeStatus4; + } + if ($status == ContratLigne::STATUS_OPEN && $bool) { + $colorseries[$status.$bool] = $badgeStatus1; + } + if ($status == ContratLigne::STATUS_CLOSED) { + $colorseries[$status.$bool] = $badgeStatus6; + } - if (empty($conf->use_javascript_ajax)) - { + if (empty($conf->use_javascript_ajax)) { print ''; print ''; print ''; print "\n"; } - if ($status == 4 && !$bool) $bool = true; - else $bool = false; + if ($status == 4 && !$bool) { + $bool = true; + } else { + $bool = false; + } } -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print ''; } $listofstatus = array(0, 4, 4, 5); $bool = false; -foreach ($listofstatus as $status) -{ - if (empty($conf->use_javascript_ajax)) - { +foreach ($listofstatus as $status) { + if (empty($conf->use_javascript_ajax)) { print ''; print ''; print ''; - if ($status == 4 && !$bool) $bool = true; - else $bool = false; + if ($status == 4 && !$bool) { + $bool = true; + } else { + $bool = false; + } print "\n"; } } @@ -245,36 +258,38 @@ print "
'.$langs->trans("Statistics").' - '.$langs->trans("Services").'
'.$staticcontratligne->LibStatut($status, 0, ($bool ? 1 : 0)).''.($nb[$status.$bool] ? $nb[$status.$bool] : 0).' '.$staticcontratligne->LibStatut($status, 3, ($bool ? 1 : 0)).'
'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -225,15 +237,16 @@ if (!empty($conf->use_javascript_ajax)) print '
'.$staticcontratligne->LibStatut($status, 0, ($bool ? 1 : 0)).''.($nb[$status.$bool] ? $nb[$status.$bool] : 0).' '.$staticcontratligne->LibStatut($status, 3, ($bool ? 1 : 0)).'

"; // Draft contracts -if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) -{ +if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { $sql = "SELECT c.rowid, c.ref,"; $sql .= " s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c, ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.rowid = c.fk_soc"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND c.statut = 0"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND c.fk_soc = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND c.fk_soc = ".$socid; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '
'; print ''; print ''; print ''; - if ($num) - { + if ($num) { $companystatic = new Societe($db); $i = 0; //$tot_ttc = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $staticcontrat->ref = $obj->ref; @@ -319,22 +334,27 @@ $sql .= ' sum('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AN $sql .= ' sum('.$db->ifsql("cd.statut=5", 1, 0).') as nb_closed,'; $sql .= " c.rowid as cid, c.ref, c.datec, c.tms, c.statut, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s,"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; +} $sql .= " ".MAIN_DB_PREFIX."contrat as c"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat"; $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND c.statut > 0"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " GROUP BY c.rowid, c.ref, c.datec, c.tms, c.statut, s.nom, s.rowid"; $sql .= " ORDER BY c.tms DESC"; $sql .= " LIMIT ".$max; dol_syslog("contrat/index.php", LOG_DEBUG); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; @@ -347,8 +367,7 @@ if ($result) print ''; print "\n"; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($result); print ''; @@ -356,7 +375,9 @@ if ($result) $staticcontrat->ref = ($obj->ref ? $obj->ref : $obj->cid); $staticcontrat->id = $obj->cid; print $staticcontrat->getNomUrl(1, 16); - if ($obj->nb_late) print img_warning($langs->trans("Late")); + if ($obj->nb_late) { + print img_warning($langs->trans("Late")); + } print ''; print ''; print "\n"; - while ($i < min($num, $max)) - { + while ($i < min($num, $max)) { $obj = $db->fetch_object($resql); print ''; @@ -422,8 +447,7 @@ if ($resql) //if (1 == 1) print img_warning($langs->trans("Late")); print ''; print ''; print ''; print "\n"; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; @@ -498,8 +529,7 @@ if ($resql) print $staticcontrat->getNomUrl(1, 16); print ''; print ''; print ''; print "\n"; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; @@ -574,8 +611,7 @@ if ($resql) print $staticcontrat->getNomUrl(1, 16); print ''; print ''; print ''; print ''; print ''; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($resqllist); print ''; @@ -7308,23 +7707,27 @@ class Form dol_print_error($this->db); } print ''; - if ($num > 0) - { + if ($num > 0) { } //$linktoelem.=($linktoelem?'   ':''); - if ($num > 0) $linktoelemlist .= '
  • '.$langs->trans($possiblelink['label']).' ('.$num.')
  • '; + if ($num > 0) { + $linktoelemlist .= '
  • '.$langs->trans($possiblelink['label']).' ('.$num.')
  • '; + } //else $linktoelem.=$langs->trans($possiblelink['label']); - else $linktoelemlist .= '
  • '.$langs->trans($possiblelink['label']).' (0)
  • '; + else { + $linktoelemlist .= '
  • '.$langs->trans($possiblelink['label']).' (0)
  • '; + } } } - if ($linktoelemlist) - { + if ($linktoelemlist) { $linktoelem = ' '; print "\n"; - if (is_array($listofactions) && count($listofactions)) - { + if (is_array($listofactions) && count($listofactions)) { $cacheusers = array(); $cursorevent = 0; - foreach ($listofactions as $actioncomm) - { - if ($max && $cursorevent >= $max) break; + foreach ($listofactions as $actioncomm) { + if ($max && $cursorevent >= $max) { + break; + } $ref = $actioncomm->getNomUrl(1, -1); $label = $actioncomm->getNomUrl(0, 36); @@ -244,18 +260,15 @@ class FormActions // Onwer print ''; print ''; } - if ($max && $num > $max) - { + if ($max && $num > $max) { print ''; } @@ -329,7 +343,9 @@ class FormActions // phpcs:enable global $langs, $user, $form, $conf; - if (!is_object($form)) $form = new Form($this->db); + if (!is_object($form)) { + $form = new Form($this->db); + } require_once DOL_DOCUMENT_ROOT.'/comm/action/class/cactioncomm.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; @@ -343,28 +359,37 @@ class FormActions } //asort($arraylist); - if ($selected == 'manual') $selected = 'AC_OTH'; - if ($selected == 'auto') $selected = 'AC_OTH_AUTO'; + if ($selected == 'manual') { + $selected = 'AC_OTH'; + } + if ($selected == 'auto') { + $selected = 'AC_OTH_AUTO'; + } - if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) unset($arraylist['AC_OTH_AUTO']); + if (!empty($conf->global->AGENDA_ALWAYS_HIDE_AUTO)) { + unset($arraylist['AC_OTH_AUTO']); + } - $out = ''; + $out = ''; - if (!empty($multiselect)) - { - if (!is_array($selected) && !empty($selected)) $selected = explode(',', $selected); + if (!empty($multiselect)) { + if (!is_array($selected) && !empty($selected)) { + $selected = explode(',', $selected); + } $out .= $form->multiselectarray($htmlname, $arraylist, $selected, 0, 0, 'centpercent', 0, 0); } else { $out .= $form->selectarray($htmlname, $arraylist, $selected, 0, 0, 0, '', 0, 0, 0, '', 'minwidth300'.($morecss ? ' '.$morecss : ''), 1); } - if ($user->admin && empty($onlyautoornot) && $hideinfohelp <= 0) - { + if ($user->admin && empty($onlyautoornot) && $hideinfohelp <= 0) { $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup").($hideinfohelp == -1 ? ". ".$langs->trans("YouCanSetDefaultValueInModuleSetup") : ''), 1); } - if ($nooutput) return $out; - else print $out; + if ($nooutput) { + return $out; + } else { + print $out; + } return ''; } } diff --git a/htdocs/core/class/html.formadmin.class.php b/htdocs/core/class/html.formadmin.class.php index 36af8bfa875..f58e567a37d 100644 --- a/htdocs/core/class/html.formadmin.class.php +++ b/htdocs/core/class/html.formadmin.class.php @@ -67,45 +67,59 @@ class FormAdmin // phpcs:enable global $conf, $langs; - if (!empty($conf->global->MAIN_DEFAULT_LANGUAGE_FILTER)) $filter[$conf->global->MAIN_DEFAULT_LANGUAGE_FILTER] = 1; + if (!empty($conf->global->MAIN_DEFAULT_LANGUAGE_FILTER)) { + $filter[$conf->global->MAIN_DEFAULT_LANGUAGE_FILTER] = 1; + } $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 12, 0, $mainlangonly); $out = ''; $out .= ''; // Make select dynamic - if (!$forcecombo) - { + if (!$forcecombo) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $out .= ajax_combobox($htmlname); } @@ -152,38 +165,45 @@ class FormAdmin // Check parameters - if (!is_array($dirmenuarray)) return -1; + if (!is_array($dirmenuarray)) { + return -1; + } $menuarray = array(); - foreach ($conf->file->dol_document_root as $dirroot) - { - foreach ($dirmenuarray as $dirtoscan) - { + foreach ($conf->file->dol_document_root as $dirroot) { + foreach ($dirmenuarray as $dirtoscan) { $dir = $dirroot.$dirtoscan; //print $dir.'
    '; - if (is_dir($dir)) - { + if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && substr($file, 0, 5) != 'index') - { - if (preg_match('/lib\.php$/i', $file)) continue; // We exclude library files - if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files - if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i', $file)) continue; // We exclude all menu manager files + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (is_file($dir."/".$file) && substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS' && substr($file, 0, 5) != 'index') { + if (preg_match('/lib\.php$/i', $file)) { + continue; // We exclude library files + } + if (preg_match('/eldy_(backoffice|frontoffice)\.php$/i', $file)) { + continue; // We exclude all menu manager files + } + if (preg_match('/auguria_(backoffice|frontoffice)\.php$/i', $file)) { + continue; // We exclude all menu manager files + } + if (preg_match('/smartphone_(backoffice|frontoffice)\.php$/i', $file)) { + continue; // We exclude all menu manager files + } $filelib = preg_replace('/\.php$/i', '', $file); $prefix = ''; // 0=Recommanded, 1=Experimental, 2=Developpement, 3=Other - if (preg_match('/^eldy/i', $file)) $prefix = '0'; - elseif (preg_match('/^smartphone/i', $file)) $prefix = '2'; - else $prefix = '3'; + if (preg_match('/^eldy/i', $file)) { + $prefix = '0'; + } elseif (preg_match('/^smartphone/i', $file)) { + $prefix = '2'; + } else { + $prefix = '3'; + } - if ($file == $selected) - { + if ($file == $selected) { $menuarray[$prefix.'_'.$file] = ''; } else { $menuarray[$prefix.'_'.$file] = ''; @@ -200,20 +220,30 @@ class FormAdmin // Output combo list of menus print ''; $oldprefix = ''; - foreach ($menuarray as $key => $val) - { + foreach ($menuarray as $key => $val) { $tab = explode('_', $key); $newprefix = $tab[0]; print ''."\n"; } print ''; @@ -340,7 +375,9 @@ class FormAdmin ); foreach ($arraytz as $lib => $gmt) { print ''."\n"; } print ''; @@ -368,15 +405,15 @@ class FormAdmin $sql = "SELECT code, label, width, height, unit"; $sql .= " FROM ".MAIN_DB_PREFIX."c_paper_format"; $sql .= " WHERE active=1"; - if ($filter) $sql .= " AND code LIKE '%".$this->db->escape($filter)."%'"; + if ($filter) { + $sql .= " AND code LIKE '%".$this->db->escape($filter)."%'"; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $unitKey = $langs->trans('SizeUnit'.$obj->unit); @@ -391,16 +428,15 @@ class FormAdmin $out = ''; $out .= ''; print ''; print ''; - if ($conf->global->MARGIN_TYPE == "1") + if ($conf->global->MARGIN_TYPE == "1") { print ''; - else print ''; + } else { + print ''; + } print ''; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print ''; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print ''; + } print ''; - if (!empty($conf->product->enabled)) - { + if (!empty($conf->product->enabled)) { //if ($marginInfo['margin_on_products'] != 0 && $marginInfo['margin_on_services'] != 0) { print ''; print ''; print ''; print ''; print ''; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print ''; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print ''; + } print ''; } - if (!empty($conf->service->enabled)) - { + if (!empty($conf->service->enabled)) { print ''; print ''; print ''; print ''; print ''; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print ''; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print ''; + } print ''; } - if (!empty($conf->product->enabled) && !empty($conf->service->enabled)) - { + if (!empty($conf->product->enabled) && !empty($conf->service->enabled)) { print ''; print ''; print ''; print ''; print ''; - if (!empty($conf->global->DISPLAY_MARGIN_RATES)) + if (!empty($conf->global->DISPLAY_MARGIN_RATES)) { print ''; - if (!empty($conf->global->DISPLAY_MARK_RATES)) + } + if (!empty($conf->global->DISPLAY_MARK_RATES)) { print ''; + } print ''; } print '
    '.$langs->trans("DraftContracts").($num ? ''.$num.'' : '').'
    '.$langs->trans("Services").'
    '; $staticcompany->id = $obj->socid; @@ -388,19 +409,24 @@ $sql .= " s.nom as name,"; $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; $sql .= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= ") LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= " WHERE c.entity IN (".getEntity('contract', 0).")"; $sql .= " AND cd.fk_contrat = c.rowid"; $sql .= " AND c.fk_soc = s.rowid"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " ORDER BY cd.tms DESC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -410,8 +436,7 @@ if ($resql) print '
    '.$langs->trans("LastModifiedServices", $max).'
    '; - if ($obj->fk_product > 0) - { + if ($obj->fk_product > 0) { $productstatic->id = $obj->fk_product; $productstatic->type = $obj->ptype; $productstatic->ref = $obj->pref; @@ -431,8 +455,11 @@ if ($resql) print $productstatic->getNomUrl(1, '', 20); } else { print ''.img_object($langs->trans("ShowService"), "service"); - if ($obj->label) print ' '.dol_trunc($obj->label, 20).''; - else print ' '.dol_trunc($obj->note, 20); + if ($obj->label) { + print ' '.dol_trunc($obj->label, 20).''; + } else { + print ' '.dol_trunc($obj->note, 20); + } } print ''; @@ -462,7 +489,9 @@ $sql .= " s.nom as name,"; $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; $sql .= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= " ) LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= " WHERE c.entity IN (".getEntity('contract', 0).")"; @@ -470,13 +499,16 @@ $sql .= " AND c.statut = 1"; $sql .= " AND cd.statut = 0"; $sql .= " AND cd.fk_contrat = c.rowid"; $sql .= " AND c.fk_soc = s.rowid"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " ORDER BY cd.tms DESC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -486,8 +518,7 @@ if ($resql) print '
    '.$langs->trans("NotActivatedServices").' '.$num.'
    '; - if ($obj->fk_product > 0) - { + if ($obj->fk_product > 0) { $productstatic->id = $obj->fk_product; $productstatic->type = $obj->ptype; $productstatic->ref = $obj->pref; @@ -507,8 +537,11 @@ if ($resql) print $productstatic->getNomUrl(1, '', 20); } else { print ''.img_object($langs->trans("ShowService"), "service"); - if ($obj->label) print ' '.dol_trunc($obj->label, 20).''; - else print ' '.dol_trunc($obj->note, 20); + if ($obj->label) { + print ' '.dol_trunc($obj->label, 20).''; + } else { + print ' '.dol_trunc($obj->note, 20); + } } print ''; @@ -537,7 +570,9 @@ $sql .= " s.nom as name,"; $sql .= " p.rowid as pid, p.ref as pref, p.label as plabel, p.fk_product_type as ptype, p.entity as pentity"; $sql .= " FROM (".MAIN_DB_PREFIX."contrat as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."contratdet as cd"; $sql .= " ) LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; $sql .= " WHERE c.entity IN (".getEntity('contract', 0).")"; @@ -546,13 +581,16 @@ $sql .= " AND cd.statut = 4"; $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'"; $sql .= " AND cd.fk_contrat = c.rowid"; $sql .= " AND c.fk_soc = s.rowid"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " ORDER BY cd.tms DESC"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -562,8 +600,7 @@ if ($resql) print '
    '.$langs->trans("ListOfExpiredServices").' '.$num.'
    '; - if ($obj->fk_product > 0) - { + if ($obj->fk_product > 0) { $productstatic->id = $obj->fk_product; $productstatic->type = $obj->ptype; $productstatic->ref = $obj->pref; @@ -583,8 +619,11 @@ if ($resql) print $productstatic->getNomUrl(1, '', 20); } else { print ''.img_object($langs->trans("ShowService"), "service"); - if ($obj->label) print ' '.dol_trunc($obj->label, 20).''; - else print ' '.dol_trunc($obj->note, 20); + if ($obj->label) { + print ' '.dol_trunc($obj->label, 20).''; + } else { + print ' '.dol_trunc($obj->note, 20); + } } print ''; diff --git a/htdocs/contrat/list.php b/htdocs/contrat/list.php index a890b1f3ce2..27cbf5a3a70 100644 --- a/htdocs/contrat/list.php +++ b/htdocs/contrat/list.php @@ -76,16 +76,24 @@ $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 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'c.ref'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'c.ref'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); $diroutputmassaction = $conf->contrat->dir_output.'/temp/massgeneration/'.$user->id; @@ -93,7 +101,9 @@ $diroutputmassaction = $conf->contrat->dir_output.'/temp/massgeneration/'.$user- $staticcontrat = new Contrat($db); $staticcontratligne = new ContratLigne($db); -if ($search_status == '') $search_status = 1; +if ($search_status == '') { + $search_status = 1; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new Contrat($db); @@ -112,7 +122,9 @@ $fieldstosearchall = array( 's.nom'=>"ThirdParty", 'c.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["c.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["c.note_private"] = "NotePrivate"; +} $arrayfields = array( 'c.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1, 'position'=>10), @@ -142,18 +154,23 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Action */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $parameters = array('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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} 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 test are required to be compatible with all browsers -{ +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 $day = ''; $month = ''; $year = ''; @@ -180,8 +197,7 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $search_array_options = array(); } -if (empty($reshook)) -{ +if (empty($reshook)) { $objectclass = 'Contrat'; $objectlabel = 'Contracts'; $permissiontoread = $user->rights->contrat->lire; @@ -216,7 +232,9 @@ $sql .= ' SUM('.$db->ifsql("cd.statut=4 AND (cd.date_fin_validite IS NOT NULL AN $sql .= ' SUM('.$db->ifsql("cd.statut=5", 1, 0).') as nb_closed'; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); @@ -226,34 +244,60 @@ $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."contrat as c"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (c.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (c.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contratdet as cd ON c.rowid = cd.fk_contrat"; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; -if ($search_user > 0) -{ +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql .= " WHERE c.fk_soc = s.rowid "; $sql .= ' AND c.entity IN ('.getEntity('contract').')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; -if ($socid) $sql .= " AND s.rowid = ".$db->escape($socid); -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; +} +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} +if ($socid) { + $sql .= " AND s.rowid = ".$db->escape($socid); +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= dolSqlDateFilter('c.date_contrat', $day, $month, $year); -if ($search_name) $sql .= natural_search('s.nom', $search_name); -if ($search_email) $sql .= natural_search('s.email', $search_email); -if ($search_contract) $sql .= natural_search(array('c.rowid', 'c.ref'), $search_contract); -if (!empty($search_ref_customer)) $sql .= natural_search(array('c.ref_customer'), $search_ref_customer); -if (!empty($search_ref_supplier)) $sql .= natural_search(array('c.ref_supplier'), $search_ref_supplier); -if ($search_sale > 0) -{ +if ($search_name) { + $sql .= natural_search('s.nom', $search_name); +} +if ($search_email) { + $sql .= natural_search('s.email', $search_email); +} +if ($search_contract) { + $sql .= natural_search(array('c.rowid', 'c.ref'), $search_contract); +} +if (!empty($search_ref_customer)) { + $sql .= natural_search(array('c.ref_customer'), $search_ref_customer); +} +if (!empty($search_ref_supplier)) { + $sql .= natural_search(array('c.ref_supplier'), $search_ref_supplier); +} +if ($search_sale > 0) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$search_sale; } -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='contrat' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($search_user > 0) { + $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='contrat' AND tc.source='internal' AND ec.element_id = c.rowid AND ec.fk_socpeople = ".$search_user; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -266,34 +310,36 @@ $sql .= " typent.code,"; $sql .= " state.code_departement, state.nom"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : ''); + } } // Add where from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -if ($search_dfyear > 0 && $search_op2df) -{ - if ($search_op2df == '<=') $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."'"; - elseif ($search_op2df == '>=') $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; - else $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."' AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; +if ($search_dfyear > 0 && $search_op2df) { + if ($search_op2df == '<=') { + $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."'"; + } elseif ($search_op2df == '>=') { + $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; + } else { + $sql .= " HAVING MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") <= '".$db->idate(dol_get_last_day($search_dfyear, $search_dfmonth, false))."' AND MIN(".$db->ifsql("cd.statut=4", "cd.date_fin_validite", "null").") >= '".$db->idate(dol_get_first_day($search_dfyear, $search_dfmonth, false))."'"; + } } $sql .= $db->order($sortfield, $sortorder); $totalnboflines = 0; $result = $db->query($sql); -if ($result) -{ +if ($result) { $totalnboflines = $db->num_rows($result); } $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -302,8 +348,7 @@ if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) $sql .= $db->plimit($limit + 1, $offset); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -311,8 +356,7 @@ if (!$resql) $num = $db->num_rows($resql); // Direct jump if only one record found -if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall && !$page) -{ +if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall && !$page) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/contrat/card.php?id='.$id); @@ -329,31 +373,66 @@ $i = 0; $arrayofselected = is_array($toselect) ? $toselect : array(); -if ($socid > 0) -{ +if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); - if (empty($search_name)) $search_name = $soc->name; + if (empty($search_name)) { + $search_name = $soc->name; + } } $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); -if ($sall != '') $param .= '&sall='.urlencode($sall); -if ($search_contract != '') $param .= '&search_contract='.urlencode($search_contract); -if ($search_name != '') $param .= '&search_name='.urlencode($search_name); -if ($search_email != '') $param .= '&search_email='.urlencode($search_email); -if ($search_ref_customer != '') $param .= '&search_ref_customer='.urlencode($search_ref_customer); -if ($search_ref_supplier != '') $param .= '&search_ref_supplier='.urlencode($search_ref_supplier); -if ($search_op2df != '') $param .= '&search_op2df='.urlencode($search_op2df); -if ($search_dfyear != '') $param .= '&search_dfyear='.urlencode($search_dfyear); -if ($search_dfmonth != '') $param .= '&search_dfmonth='.urlencode($search_dfmonth); -if ($search_sale != '') $param .= '&search_sale='.urlencode($search_sale); -if ($search_user != '') $param .= '&search_user='.urlencode($search_user); -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); -if ($search_product_category != '') $param .= '&search_product_category='.urlencode($search_product_category); -if ($show_files) $param .= '&show_files='.urlencode($show_files); -if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); +} +if ($sall != '') { + $param .= '&sall='.urlencode($sall); +} +if ($search_contract != '') { + $param .= '&search_contract='.urlencode($search_contract); +} +if ($search_name != '') { + $param .= '&search_name='.urlencode($search_name); +} +if ($search_email != '') { + $param .= '&search_email='.urlencode($search_email); +} +if ($search_ref_customer != '') { + $param .= '&search_ref_customer='.urlencode($search_ref_customer); +} +if ($search_ref_supplier != '') { + $param .= '&search_ref_supplier='.urlencode($search_ref_supplier); +} +if ($search_op2df != '') { + $param .= '&search_op2df='.urlencode($search_op2df); +} +if ($search_dfyear != '') { + $param .= '&search_dfyear='.urlencode($search_dfyear); +} +if ($search_dfmonth != '') { + $param .= '&search_dfmonth='.urlencode($search_dfmonth); +} +if ($search_sale != '') { + $param .= '&search_sale='.urlencode($search_sale); +} +if ($search_user != '') { + $param .= '&search_user='.urlencode($search_user); +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); +} +if ($search_product_category != '') { + $param .= '&search_product_category='.urlencode($search_product_category); +} +if ($show_files) { + $param .= '&show_files='.urlencode($show_files); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -363,16 +442,24 @@ $arrayofmassactions = array( 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); -if ($user->rights->contrat->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); -if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($user->rights->contrat->supprimer) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); +} +if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/contrat/card.php?action=create'; -if (!empty($socid)) $url .= '&socid='.$socid; +if (!empty($socid)) { + $url .= '&socid='.$socid; +} $newcardbutton = dolGetButtonTitle($langs->trans('NewContractSubscription'), '', 'fa fa-plus-circle', $url, '', $user->rights->contrat->creer); print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -388,17 +475,17 @@ $objecttmp = new Contrat($db); $trackid = 'con'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; -if ($sall) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } $moreforfilter = ''; // If the user can view prospects other than his' -if ($user->rights->societe->client->voir || $socid) -{ +if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; @@ -406,16 +493,14 @@ if ($user->rights->societe->client->voir || $socid) $moreforfilter .= '
    '; } // If the user can view other users -if ($user->rights->user->user->lire) -{ +if ($user->rights->user->user->lire) { $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter .= '
    '; + $moreforfilter .= ''; } // If the user can view categories of products -if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) -{ +if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -426,11 +511,13 @@ if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($use $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 (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} -if (!empty($moreforfilter)) -{ +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -438,77 +525,75 @@ if (!empty($moreforfilter)) $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); +if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +} print '
    '; print ''."\n"; print ''; -if (!empty($arrayfields['c.ref']['checked'])) -{ +if (!empty($arrayfields['c.ref']['checked'])) { print ''; } -if (!empty($arrayfields['c.ref_customer']['checked'])) -{ +if (!empty($arrayfields['c.ref_customer']['checked'])) { print ''; } -if (!empty($arrayfields['c.ref_supplier']['checked'])) -{ +if (!empty($arrayfields['c.ref_supplier']['checked'])) { print ''; } -if (!empty($arrayfields['s.nom']['checked'])) -{ +if (!empty($arrayfields['s.nom']['checked'])) { print ''; } -if (!empty($arrayfields['s.email']['checked'])) -{ +if (!empty($arrayfields['s.email']['checked'])) { print ''; } // Town -if (!empty($arrayfields['s.town']['checked'])) print ''; +if (!empty($arrayfields['s.town']['checked'])) { + print ''; +} // Zip -if (!empty($arrayfields['s.zip']['checked'])) print ''; +if (!empty($arrayfields['s.zip']['checked'])) { + print ''; +} // State -if (!empty($arrayfields['state.nom']['checked'])) -{ +if (!empty($arrayfields['state.nom']['checked'])) { print ''; } // Country -if (!empty($arrayfields['country.code_iso']['checked'])) -{ +if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; } // Company type -if (!empty($arrayfields['typent.code']['checked'])) -{ +if (!empty($arrayfields['typent.code']['checked'])) { print ''; } -if (!empty($arrayfields['sale_representative']['checked'])) -{ +if (!empty($arrayfields['sale_representative']['checked'])) { print ''; } -if (!empty($arrayfields['c.date_contrat']['checked'])) -{ +if (!empty($arrayfields['c.date_contrat']['checked'])) { // Date contract print ''; } // Date modification -if (!empty($arrayfields['c.tms']['checked'])) -{ +if (!empty($arrayfields['c.tms']['checked'])) { print ''; } // First end date -if (!empty($arrayfields['lower_planned_end_date']['checked'])) -{ +if (!empty($arrayfields['lower_planned_end_date']['checked'])) { print ''; } // Status -if (!empty($arrayfields['status']['checked'])) -{ +if (!empty($arrayfields['status']['checked'])) { print ''; } print ''; print "\n"; print ''; -if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['c.ref_customer']['checked'])) print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['c.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.email']['checked'])) print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['sale_representative']['checked'])) print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder); -if (!empty($arrayfields['c.date_contrat']['checked'])) print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['c.ref']['checked'])) { + print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['c.ref_customer']['checked'])) { + print_liste_field_titre($arrayfields['c.ref_customer']['label'], $_SERVER["PHP_SELF"], "c.ref_customer", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['c.ref_supplier']['checked'])) { + print_liste_field_titre($arrayfields['c.ref_supplier']['label'], $_SERVER["PHP_SELF"], "c.ref_supplier", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.email']['checked'])) { + print_liste_field_titre($arrayfields['s.email']['label'], $_SERVER["PHP_SELF"], "s.email", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['state.nom']['checked'])) { + print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['country.code_iso']['checked'])) { + print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['sale_representative']['checked'])) { + print_liste_field_titre($arrayfields['sale_representative']['label'], $_SERVER["PHP_SELF"], "", "", $param, '', $sortfield, $sortorder); +} +if (!empty($arrayfields['c.date_contrat']['checked'])) { + print_liste_field_titre($arrayfields['c.date_contrat']['label'], $_SERVER["PHP_SELF"], "c.date_contrat", "", $param, '', $sortfield, $sortorder, 'center '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields @@ -598,8 +703,7 @@ $totalarray = array(); $typenArray = array(); $cacheCountryIDCode = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $contracttmp->ref = $obj->ref; @@ -632,11 +736,12 @@ while ($i < min($num, $limit)) print ''; // Ref - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print ''; } - if (!empty($arrayfields['c.ref_customer']['checked'])) - { + if (!empty($arrayfields['c.ref_customer']['checked'])) { print ''; } - if (!empty($arrayfields['c.ref_supplier']['checked'])) - { + if (!empty($arrayfields['c.ref_supplier']['checked'])) { print ''; } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; } - if (!empty($arrayfields['s.email']['checked'])) - { + if (!empty($arrayfields['s.email']['checked'])) { print ''; } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['sale_representative']['checked'])) - { + if (!empty($arrayfields['sale_representative']['checked'])) { // Sales representatives print ''; } // Date - if (!empty($arrayfields['c.date_contrat']['checked'])) - { + if (!empty($arrayfields['c.date_contrat']['checked'])) { print ''; } // Extra fields @@ -767,32 +874,34 @@ while ($i < min($num, $limit)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['c.datec']['checked'])) - { + if (!empty($arrayfields['c.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['c.tms']['checked'])) - { + if (!empty($arrayfields['c.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date lower end date - if (!empty($arrayfields['lower_planned_end_date']['checked'])) - { + if (!empty($arrayfields['lower_planned_end_date']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['status']['checked'])) - { + if (!empty($arrayfields['status']['checked'])) { print ''; print ''; print ''; @@ -800,14 +909,17 @@ while ($i < min($num, $limit)) } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; $i++; @@ -824,7 +936,9 @@ print ''; print ''; $hidegeneratedfilelistifempty = 1; -if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; +if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; +} // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/contrat/note.php b/htdocs/contrat/note.php index c9000c4fb0d..d61ac357a40 100644 --- a/htdocs/contrat/note.php +++ b/htdocs/contrat/note.php @@ -41,7 +41,9 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $id); $object = new Contrat($db); @@ -70,8 +72,7 @@ llxHeader('', $langs->trans("Contract"), ""); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = contract_prepare_head($object); @@ -89,9 +90,9 @@ if ($id > 0 || !empty($ref)) //if (! empty($modCodeContract->code_auto)) { $morehtmlref .= $object->ref; /*} else { - $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); - $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); - }*/ + $morehtmlref.=$form->editfieldkey("",'ref',$object->ref,0,'string','',0,3); + $morehtmlref.=$form->editfieldval("",'ref',$object->ref,0,'string','',0,2); + }*/ $morehtmlref .= '
    '; // Ref customer @@ -104,15 +105,14 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '
    '.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '
    '.$langs->trans('Project').' '; - if ($user->rights->contrat->creer) - { - if ($action != 'classify') + if ($user->rights->contrat->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 .= '
    '; @@ -150,12 +150,18 @@ if ($id > 0 || !empty($ref)) // Ligne info remises tiers print '
    '; diff --git a/htdocs/contrat/services_list.php b/htdocs/contrat/services_list.php index 4de651a24f9..072982e56eb 100644 --- a/htdocs/contrat/services_list.php +++ b/htdocs/contrat/services_list.php @@ -39,12 +39,18 @@ $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 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = "c.rowid"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "c.rowid"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} $mode = GETPOST("mode"); $filter = GETPOST("filter"); @@ -90,22 +96,32 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Security check $contratid = GETPOST('id', 'int'); -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'contrat', $contratid); -if ($search_status != '') -{ +if ($search_status != '') { $tmp = explode('&', $search_status); $mode = $tmp[0]; - if (empty($tmp[1])) $filter = ''; - else { - if ($tmp[1] == 'filter=notexpired') $filter = 'notexpired'; - if ($tmp[1] == 'filter=expired') $filter = 'expired'; + if (empty($tmp[1])) { + $filter = ''; + } else { + if ($tmp[1] == 'filter=notexpired') { + $filter = 'notexpired'; + } + if ($tmp[1] == 'filter=expired') { + $filter = 'expired'; + } } } else { $search_status = $mode; - if ($filter == 'expired') $search_status .= '&filter=expired'; - if ($filter == 'notexpired') $search_status .= '&filter=notexpired'; + if ($filter == 'expired') { + $search_status .= '&filter=expired'; + } + if ($filter == 'notexpired') { + $search_status .= '&filter=notexpired'; + } } $staticcontrat = new Contrat($db); @@ -142,21 +158,25 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { + $massaction = ''; +} $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Selection of new fields 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_product_category = 0; + 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_product_category = 0; $search_name = ""; $search_contract = ""; $search_service = ""; @@ -197,7 +217,9 @@ $sql = "SELECT c.rowid as cid, c.ref, c.statut as cstatut, c.ref_customer, c.ref $sql .= " s.rowid as socid, s.nom as name, s.email, s.client, s.fournisseur,"; $sql .= " cd.rowid, cd.description, cd.statut,"; $sql .= " p.rowid as pid, p.ref as pref, p.label as label, p.fk_product_type as ptype, p.entity as pentity,"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " sc.fk_soc, sc.fk_user,"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " sc.fk_soc, sc.fk_user,"; +} $sql .= " cd.date_ouverture_prevue,"; $sql .= " cd.date_ouverture,"; $sql .= " cd.date_fin_validite,"; @@ -211,7 +233,9 @@ $sql .= " cd.subprice,"; $sql .= " cd.tms as date_update"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); @@ -219,50 +243,102 @@ $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // N $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."contrat as c,"; $sql .= " ".MAIN_DB_PREFIX."societe as s,"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " ".MAIN_DB_PREFIX."societe_commerciaux as sc,"; +} $sql .= " ".MAIN_DB_PREFIX."contratdet as cd"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cd.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cd.rowid = ef.fk_object)"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON cd.fk_product = p.rowid"; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=cd.fk_product'; +} $sql .= " WHERE c.entity = ".$conf->entity; $sql .= " AND c.rowid = cd.fk_contrat"; -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} $sql .= " AND c.fk_soc = s.rowid"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($mode == "0") $sql .= " AND cd.statut = 0"; -if ($mode == "4") $sql .= " AND cd.statut = 4"; -if ($mode == "5") $sql .= " AND cd.statut = 5"; -if ($filter == "expired") $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'"; -if ($filter == "notexpired") $sql .= " AND cd.date_fin_validite >= '".$db->idate($now)."'"; -if ($search_name) $sql .= " AND s.nom LIKE '%".$db->escape($search_name)."%'"; -if ($search_contract) $sql .= " AND c.ref LIKE '%".$db->escape($search_contract)."%' "; -if ($search_service) $sql .= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')"; -if ($socid > 0) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($mode == "0") { + $sql .= " AND cd.statut = 0"; +} +if ($mode == "4") { + $sql .= " AND cd.statut = 4"; +} +if ($mode == "5") { + $sql .= " AND cd.statut = 5"; +} +if ($filter == "expired") { + $sql .= " AND cd.date_fin_validite < '".$db->idate($now)."'"; +} +if ($filter == "notexpired") { + $sql .= " AND cd.date_fin_validite >= '".$db->idate($now)."'"; +} +if ($search_name) { + $sql .= " AND s.nom LIKE '%".$db->escape($search_name)."%'"; +} +if ($search_contract) { + $sql .= " AND c.ref LIKE '%".$db->escape($search_contract)."%' "; +} +if ($search_service) { + $sql .= " AND (p.ref LIKE '%".$db->escape($search_service)."%' OR p.description LIKE '%".$db->escape($search_service)."%' OR cd.description LIKE '%".$db->escape($search_service)."%')"; +} +if ($socid > 0) { + $sql .= " AND s.rowid = ".$socid; +} $filter_dateouvertureprevue_start = dol_mktime(0, 0, 0, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear); $filter_dateouvertureprevue_end = dol_mktime(23, 59, 59, $opouvertureprevuemonth, $opouvertureprevueday, $opouvertureprevueyear); -if ($filter_dateouvertureprevue_start != '' && $filter_opouvertureprevue == -1) $filter_opouvertureprevue = ' BETWEEN '; +if ($filter_dateouvertureprevue_start != '' && $filter_opouvertureprevue == -1) { + $filter_opouvertureprevue = ' BETWEEN '; +} $filter_date1_start = dol_mktime(0, 0, 0, $op1month, $op1day, $op1year); $filter_date1_end = dol_mktime(23, 59, 59, $op1month, $op1day, $op1year); -if ($filter_date1_start != '' && $filter_op1 == -1) $filter_op1 = ' BETWEEN '; +if ($filter_date1_start != '' && $filter_op1 == -1) { + $filter_op1 = ' BETWEEN '; +} $filter_date2_start = dol_mktime(0, 0, 0, $op2month, $op2day, $op2year); $filter_date2_end = dol_mktime(23, 59, 59, $op2month, $op2day, $op2year); -if ($filter_date2_start != '' && $filter_op2 == -1) $filter_op2 = ' BETWEEN '; +if ($filter_date2_start != '' && $filter_op2 == -1) { + $filter_op2 = ' BETWEEN '; +} $filter_datecloture_start = dol_mktime(0, 0, 0, $opcloturemonth, $opclotureday, $opclotureyear); $filter_datecloture_end = dol_mktime(23, 59, 59, $opcloturemonth, $opclotureday, $opclotureyear); -if ($filter_datecloture_start != '' && $filter_opcloture == -1) $filter_opcloture = ' BETWEEN '; +if ($filter_datecloture_start != '' && $filter_opcloture == -1) { + $filter_opcloture = ' BETWEEN '; +} -if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_opouvertureprevue != ' BETWEEN ' && $filter_dateouvertureprevue_start != '') $sql .= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue_start)."'"; -if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_dateouvertureprevue_end)."'"; -if (!empty($filter_op1) && $filter_op1 != -1 && $filter_op1 != ' BETWEEN ' && $filter_date1_start != '') $sql .= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1_start)."'"; -if (!empty($filter_op1) && $filter_op1 == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_date1_end)."'"; -if (!empty($filter_op2) && $filter_op2 != -1 && $filter_op2 != ' BETWEEN ' && $filter_date2_start != '') $sql .= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2_start)."'"; -if (!empty($filter_op2) && $filter_op2 == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_date2_end)."'"; -if (!empty($filter_opcloture) && $filter_opcloture != ' BETWEEN ' && $filter_opcloture != -1 && $filter_datecloture_start != '') $sql .= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture_start)."'"; -if (!empty($filter_opcloture) && $filter_opcloture == ' BETWEEN ') $sql .= " AND '".$db->idate($filter_datecloture_end)."'"; +if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1 && $filter_opouvertureprevue != ' BETWEEN ' && $filter_dateouvertureprevue_start != '') { + $sql .= " AND cd.date_ouverture_prevue ".$filter_opouvertureprevue." '".$db->idate($filter_dateouvertureprevue_start)."'"; +} +if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue == ' BETWEEN ') { + $sql .= " AND '".$db->idate($filter_dateouvertureprevue_end)."'"; +} +if (!empty($filter_op1) && $filter_op1 != -1 && $filter_op1 != ' BETWEEN ' && $filter_date1_start != '') { + $sql .= " AND cd.date_ouverture ".$filter_op1." '".$db->idate($filter_date1_start)."'"; +} +if (!empty($filter_op1) && $filter_op1 == ' BETWEEN ') { + $sql .= " AND '".$db->idate($filter_date1_end)."'"; +} +if (!empty($filter_op2) && $filter_op2 != -1 && $filter_op2 != ' BETWEEN ' && $filter_date2_start != '') { + $sql .= " AND cd.date_fin_validite ".$filter_op2." '".$db->idate($filter_date2_start)."'"; +} +if (!empty($filter_op2) && $filter_op2 == ' BETWEEN ') { + $sql .= " AND '".$db->idate($filter_date2_end)."'"; +} +if (!empty($filter_opcloture) && $filter_opcloture != ' BETWEEN ' && $filter_opcloture != -1 && $filter_datecloture_start != '') { + $sql .= " AND cd.date_cloture ".$filter_opcloture." '".$db->idate($filter_datecloture_start)."'"; +} +if (!empty($filter_opcloture) && $filter_opcloture == ' BETWEEN ') { + $sql .= " AND '".$db->idate($filter_datecloture_end)."'"; +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; $sql .= $db->order($sortfield, $sortorder); @@ -270,12 +346,10 @@ $sql .= $db->order($sortfield, $sortorder); //print $sql; $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -286,8 +360,7 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; dol_syslog("contrat/services_list.php", LOG_DEBUG); $resql = $db->query($sql); -if (!$resql) -{ +if (!$resql) { dol_print_error($db); exit; } @@ -297,31 +370,63 @@ $num = $db->num_rows($resql); /* if ($num == 1 && ! empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all) { - $obj = $db->fetch_object($resql); - $id = $obj->id; - header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); - exit; + $obj = $db->fetch_object($resql); + $id = $obj->id; + header("Location: ".DOL_URL_ROOT.'/projet/tasks/task.php?id='.$id.'&withprojet=1'); + exit; }*/ llxHeader(null, $langs->trans("Services")); $param = ''; -if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); -if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; -if ($search_contract) $param .= '&search_contract='.urlencode($search_contract); -if ($search_name) $param .= '&search_name='.urlencode($search_name); -if ($search_service) $param .= '&search_service='.urlencode($search_service); -if ($mode) $param .= '&mode='.urlencode($mode); -if ($filter) $param .= '&filter='.urlencode($filter); -if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) $param .= '&filter_opouvertureprevue='.urlencode($filter_opouvertureprevue); -if (!empty($filter_op1) && $filter_op1 != -1) $param .= '&filter_op1='.urlencode($filter_op1); -if (!empty($filter_op2) && $filter_op2 != -1) $param .= '&filter_op2='.urlencode($filter_op2); -if (!empty($filter_opcloture) && $filter_opcloture != -1) $param .= '&filter_opcloture='.urlencode($filter_opcloture); -if ($filter_dateouvertureprevue != '') $param .= '&opouvertureprevueday='.$opouvertureprevueday.'&opouvertureprevuemonth='.$opouvertureprevuemonth.'&opouvertureprevueyear='.$opouvertureprevueyear; -if ($filter_date1 != '') $param .= '&op1day='.$op1day.'&op1month='.$op1month.'&op1year='.$op1year; -if ($filter_date2 != '') $param .= '&op2day='.$op2day.'&op2month='.$op2month.'&op2year='.$op2year; -if ($filter_datecloture != '') $param .= '&opclotureday='.$op2day.'&opcloturemonth='.$op2month.'&opclotureyear='.$op2year; -if ($optioncss != '') $param .= '&optioncss='.$optioncss; +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; +} +if ($search_contract) { + $param .= '&search_contract='.urlencode($search_contract); +} +if ($search_name) { + $param .= '&search_name='.urlencode($search_name); +} +if ($search_service) { + $param .= '&search_service='.urlencode($search_service); +} +if ($mode) { + $param .= '&mode='.urlencode($mode); +} +if ($filter) { + $param .= '&filter='.urlencode($filter); +} +if (!empty($filter_opouvertureprevue) && $filter_opouvertureprevue != -1) { + $param .= '&filter_opouvertureprevue='.urlencode($filter_opouvertureprevue); +} +if (!empty($filter_op1) && $filter_op1 != -1) { + $param .= '&filter_op1='.urlencode($filter_op1); +} +if (!empty($filter_op2) && $filter_op2 != -1) { + $param .= '&filter_op2='.urlencode($filter_op2); +} +if (!empty($filter_opcloture) && $filter_opcloture != -1) { + $param .= '&filter_opcloture='.urlencode($filter_opcloture); +} +if ($filter_dateouvertureprevue != '') { + $param .= '&opouvertureprevueday='.$opouvertureprevueday.'&opouvertureprevuemonth='.$opouvertureprevuemonth.'&opouvertureprevueyear='.$opouvertureprevueyear; +} +if ($filter_date1 != '') { + $param .= '&op1day='.$op1day.'&op1month='.$op1month.'&op1year='.$op1year; +} +if ($filter_date2 != '') { + $param .= '&op2day='.$op2day.'&op2month='.$op2month.'&op2year='.$op2year; +} +if ($filter_datecloture != '') { + $param .= '&opclotureday='.$op2day.'&opcloturemonth='.$op2month.'&opclotureyear='.$op2year; +} +if ($optioncss != '') { + $param .= '&optioncss='.$optioncss; +} // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -335,7 +440,9 @@ $arrayofmassactions = array( $massactionbutton = $form->selectMassAction('', $arrayofmassactions); print ''; -if ($optioncss != '') print ''; +if ($optioncss != '') { + print ''; +} print ''; print ''; print ''; @@ -345,24 +452,32 @@ print ''; print ''; $title = $langs->trans("ListOfServices"); -if ($mode == "0") $title = $langs->trans("ListOfInactiveServices"); // Must use == "0" -if ($mode == "4" && $filter != "expired") $title = $langs->trans("ListOfRunningServices"); -if ($mode == "4" && $filter == "expired") $title = $langs->trans("ListOfExpiredServices"); -if ($mode == "5") $title = $langs->trans("ListOfClosedServices"); +if ($mode == "0") { + $title = $langs->trans("ListOfInactiveServices"); // Must use == "0" +} +if ($mode == "4" && $filter != "expired") { + $title = $langs->trans("ListOfRunningServices"); +} +if ($mode == "4" && $filter == "expired") { + $title = $langs->trans("ListOfExpiredServices"); +} +if ($mode == "5") { + $title = $langs->trans("ListOfClosedServices"); +} print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'contract', 0, '', '', $limit); -if ($sall) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } $morefilter = ''; // If the user can view categories of products -if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) -{ +if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '
    '; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -373,12 +488,14 @@ if ($conf->categorie->enabled && ($user->rights->produit->lire || $user->rights- $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 (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} -if (!empty($moreforfilter)) -{ +if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -392,33 +509,62 @@ print '
    '; print '
    '; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print ''; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print ''; //print $langs->trans('Month').': '; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print ''; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print ''; + } print ''; //print ' '.$langs->trans('Year').': '; $syear = $year; @@ -523,20 +608,17 @@ $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation -if (!empty($arrayfields['c.datec']['checked'])) -{ +if (!empty($arrayfields['c.datec']['checked'])) { print ''; print ''; print ''; $arrayofoperators = array('0'=>'', '='=>'=', '<='=>'<=', '>='=>'>='); print $form->selectarray('search_op2df', $arrayofoperators, $search_op2df, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth50imp'); @@ -547,8 +629,7 @@ if (!empty($arrayfields['lower_planned_end_date']['checked'])) print ''; @@ -558,18 +639,42 @@ print '
    '; print $contracttmp->getNomUrl(1); - if ($obj->nb_late) print img_warning($langs->trans("Late")); + if ($obj->nb_late) { + print img_warning($langs->trans("Late")); + } if (!empty($obj->note_private) || !empty($obj->note_public)) { print ' '; print ''.img_picto($langs->trans("ViewPrivateNote"), 'note').''; @@ -652,16 +757,13 @@ while ($i < min($num, $limit)) print ''.$contracttmp->getFormatedCustomerRef($obj->ref_customer).''.$obj->ref_supplier.''; if ($obj->socid > 0) { // TODO Use a cache for this string @@ -669,57 +771,63 @@ while ($i < min($num, $limit)) } print ''.$obj->email.''; print $obj->town; print ''; print $obj->zip; print '".$obj->state_name."'; print $socstatic->country; print ''; - if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); + if (count($typenArray) == 0) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print ''; - if ($obj->socid > 0) - { + if ($obj->socid > 0) { $listsalesrepresentatives = $socstatic->getSalesRepresentatives($user); - if ($listsalesrepresentatives < 0) dol_print_error($db); + if ($listsalesrepresentatives < 0) { + dol_print_error($db); + } $nbofsalesrepresentative = count($listsalesrepresentatives); if ($nbofsalesrepresentative > 6) { // We print only number @@ -756,8 +864,7 @@ while ($i < min($num, $limit)) print ''.dol_print_date($db->jdate($obj->date_contrat), 'day', 'tzserver').''; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->lower_planned_end_date), 'day', 'tzuser'); print ''.($obj->nb_initial > 0 ? $obj->nb_initial : '').''.($obj->nb_running > 0 ? $obj->nb_running : '').''.($obj->nb_expired > 0 ? $obj->nb_expired : '').''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + if (in_array($obj->rowid, $arrayofselected)) { + $selected = 1; + } print ''; } print '
    '.$langs->trans('Discount').''; - if ($object->thirdparty->remise_percent) print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent); - else print $langs->trans("CompanyHasNoRelativeDiscount"); + if ($object->thirdparty->remise_percent) { + print $langs->trans("CompanyHasRelativeDiscount", $object->thirdparty->remise_percent); + } else { + print $langs->trans("CompanyHasNoRelativeDiscount"); + } $absolute_discount = $object->thirdparty->getAvailableDiscounts(); print '. '; - if ($absolute_discount) print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); - else print $langs->trans("CompanyHasNoAbsoluteDiscount"); + if ($absolute_discount) { + print $langs->trans("CompanyHasAbsoluteDiscount", price($absolute_discount), $langs->trans("Currency".$conf->currency)); + } else { + print $langs->trans("CompanyHasNoAbsoluteDiscount"); + } print '.'; print '
    '."\n"; print ''; -if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['p.description']['checked'])) print_liste_field_titre($arrayfields['p.description']['label'], $_SERVER["PHP_SELF"], "p.description", "", $param, "", $sortfield, $sortorder); -if (!empty($arrayfields['cd.qty']['checked'])) print_liste_field_titre($arrayfields['cd.qty']['label'], $_SERVER["PHP_SELF"], "cd.qty", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.total_ht']['checked'])) print_liste_field_titre($arrayfields['cd.total_ht']['label'], $_SERVER["PHP_SELF"], "cd.total_ht", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.total_tva']['checked'])) print_liste_field_titre($arrayfields['cd.total_tva']['label'], $_SERVER["PHP_SELF"], "cd.total_tva", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.tva_tx']['checked'])) print_liste_field_titre($arrayfields['cd.tva_tx']['label'], $_SERVER["PHP_SELF"], "cd.tva_tx", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.subprice']['checked'])) print_liste_field_titre($arrayfields['cd.subprice']['label'], $_SERVER["PHP_SELF"], "cd.subprice", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -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['cd.date_ouverture_prevue']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture_prevue", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['cd.date_ouverture']['checked'])) print_liste_field_titre($arrayfields['cd.date_ouverture']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['cd.date_fin_validite']['checked'])) print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'], $_SERVER["PHP_SELF"], "cd.date_fin_validite", "", $param, '', $sortfield, $sortorder, 'center '); -if (!empty($arrayfields['cd.date_cloture']['checked'])) print_liste_field_titre($arrayfields['cd.date_cloture']['label'], $_SERVER["PHP_SELF"], "cd.date_cloture", "", $param, '', $sortfield, $sortorder, 'center '); +if (!empty($arrayfields['c.ref']['checked'])) { + print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['p.description']['checked'])) { + print_liste_field_titre($arrayfields['p.description']['label'], $_SERVER["PHP_SELF"], "p.description", "", $param, "", $sortfield, $sortorder); +} +if (!empty($arrayfields['cd.qty']['checked'])) { + print_liste_field_titre($arrayfields['cd.qty']['label'], $_SERVER["PHP_SELF"], "cd.qty", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['cd.total_ht']['label'], $_SERVER["PHP_SELF"], "cd.total_ht", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.total_tva']['checked'])) { + print_liste_field_titre($arrayfields['cd.total_tva']['label'], $_SERVER["PHP_SELF"], "cd.total_tva", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.tva_tx']['checked'])) { + print_liste_field_titre($arrayfields['cd.tva_tx']['label'], $_SERVER["PHP_SELF"], "cd.tva_tx", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.subprice']['checked'])) { + print_liste_field_titre($arrayfields['cd.subprice']['label'], $_SERVER["PHP_SELF"], "cd.subprice", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +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['cd.date_ouverture_prevue']['checked'])) { + print_liste_field_titre($arrayfields['cd.date_ouverture_prevue']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture_prevue", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['cd.date_ouverture']['checked'])) { + print_liste_field_titre($arrayfields['cd.date_ouverture']['label'], $_SERVER["PHP_SELF"], "cd.date_ouverture", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['cd.date_fin_validite']['checked'])) { + print_liste_field_titre($arrayfields['cd.date_fin_validite']['label'], $_SERVER["PHP_SELF"], "cd.date_fin_validite", "", $param, '', $sortfield, $sortorder, 'center '); +} +if (!empty($arrayfields['cd.date_cloture']['checked'])) { + print_liste_field_titre($arrayfields['cd.date_cloture']['label'], $_SERVER["PHP_SELF"], "cd.date_cloture", "", $param, '', $sortfield, $sortorder, 'center '); +} // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['cd.datec']['checked'])) print_liste_field_titre($arrayfields['cd.datec']['label'], $_SERVER["PHP_SELF"], "cd.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['cd.tms']['checked'])) print_liste_field_titre($arrayfields['cd.tms']['label'], $_SERVER["PHP_SELF"], "cd.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); -if (!empty($arrayfields['status']['checked'])) print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], "cd.statut,c.statut", "", $param, '', $sortfield, $sortorder, 'right '); +if (!empty($arrayfields['cd.datec']['checked'])) { + print_liste_field_titre($arrayfields['cd.datec']['label'], $_SERVER["PHP_SELF"], "cd.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['cd.tms']['checked'])) { + print_liste_field_titre($arrayfields['cd.tms']['label'], $_SERVER["PHP_SELF"], "cd.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); +} +if (!empty($arrayfields['status']['checked'])) { + print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], "cd.statut,c.statut", "", $param, '', $sortfield, $sortorder, 'right '); +} print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "\n"; print ''; -if (!empty($arrayfields['c.ref']['checked'])) -{ +if (!empty($arrayfields['c.ref']['checked'])) { print ''; } // Service label -if (!empty($arrayfields['p.description']['checked'])) -{ +if (!empty($arrayfields['p.description']['checked'])) { print ''; } // detail lines -if (!empty($arrayfields['cd.qty']['checked'])) -{ +if (!empty($arrayfields['cd.qty']['checked'])) { print ''; } -if (!empty($arrayfields['cd.total_ht']['checked'])) -{ +if (!empty($arrayfields['cd.total_ht']['checked'])) { print ''; } -if (!empty($arrayfields['cd.total_tva']['checked'])) -{ +if (!empty($arrayfields['cd.total_tva']['checked'])) { print ''; } -if (!empty($arrayfields['cd.tva_tx']['checked'])) -{ +if (!empty($arrayfields['cd.tva_tx']['checked'])) { print ''; } -if (!empty($arrayfields['cd.subprice']['checked'])) -{ +if (!empty($arrayfields['cd.subprice']['checked'])) { print ''; } // Third party -if (!empty($arrayfields['s.nom']['checked'])) -{ +if (!empty($arrayfields['s.nom']['checked'])) { print ''; } -if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) -{ +if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) { print ''; } -if (!empty($arrayfields['cd.date_ouverture']['checked'])) -{ +if (!empty($arrayfields['cd.date_ouverture']['checked'])) { print ''; } -if (!empty($arrayfields['cd.date_fin_validite']['checked'])) -{ +if (!empty($arrayfields['cd.date_fin_validite']['checked'])) { print ''; } -if (!empty($arrayfields['cd.date_cloture']['checked'])) -{ +if (!empty($arrayfields['cd.date_cloture']['checked'])) { print ''; } -if (!empty($arrayfields['cd.tms']['checked'])) -{ +if (!empty($arrayfields['cd.tms']['checked'])) { // Date modification print ''; } -if (!empty($arrayfields['status']['checked'])) -{ +if (!empty($arrayfields['status']['checked'])) { // Status print ''; // Ref - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Service - if (!empty($arrayfields['p.description']['checked'])) - { + if (!empty($arrayfields['p.description']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cd.qty']['checked'])) - { + if (!empty($arrayfields['cd.qty']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cd.total_ht']['checked'])) - { + if (!empty($arrayfields['cd.total_ht']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_ht'; + } $totalarray['val']['cd.total_ht'] += $obj->total_ht; } - if (!empty($arrayfields['cd.total_tva']['checked'])) - { + if (!empty($arrayfields['cd.total_tva']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_tva'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cd.total_tva'; + } $totalarray['val']['cd.total_tva'] += $obj->total_tva; } - if (!empty($arrayfields['cd.tva_tx']['checked'])) - { + if (!empty($arrayfields['cd.tva_tx']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cd.subprice']['checked'])) - { + if (!empty($arrayfields['cd.subprice']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Third party - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Start date - if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) - { + if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['cd.date_ouverture']['checked'])) - { + if (!empty($arrayfields['cd.date_ouverture']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // End date - if (!empty($arrayfields['cd.date_fin_validite']['checked'])) - { + if (!empty($arrayfields['cd.date_fin_validite']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Close date (real end date) - if (!empty($arrayfields['cd.date_cloture']['checked'])) - { + if (!empty($arrayfields['cd.date_cloture']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -691,45 +846,50 @@ while ($i < min($num, $limit)) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['cd.datec']['checked'])) - { + if (!empty($arrayfields['cd.datec']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['cd.tms']['checked'])) - { + if (!empty($arrayfields['cd.tms']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['status']['checked'])) - { + if (!empty($arrayfields['status']['checked'])) { print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; $i++; diff --git a/htdocs/contrat/tpl/linkedobjectblock.tpl.php b/htdocs/contrat/tpl/linkedobjectblock.tpl.php index 339f51db22c..310e2bd00b9 100644 --- a/htdocs/contrat/tpl/linkedobjectblock.tpl.php +++ b/htdocs/contrat/tpl/linkedobjectblock.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,24 +36,24 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $langs->load("contracts"); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - - - + + + - '; } print '
    '; print ''; print ''; @@ -426,49 +572,41 @@ if (!empty($arrayfields['c.ref']['checked'])) print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; print ''; $arrayofoperators = array('<'=>'<', '>'=>'>'); print $form->selectarray('filter_opouvertureprevue', $arrayofoperators, $filter_opouvertureprevue, 1); @@ -477,8 +615,7 @@ if (!empty($arrayfields['cd.date_ouverture_prevue']['checked'])) print $form->selectDate($filter_dateouvertureprevue, 'opouvertureprevue', 0, 0, 1, '', 1, 0); print ''; $arrayofoperators = array('<'=>'<', '>'=>'>'); print $form->selectarray('filter_op1', $arrayofoperators, $filter_op1, 1); @@ -487,8 +624,7 @@ if (!empty($arrayfields['cd.date_ouverture']['checked'])) print $form->selectDate($filter_date1, 'op1', 0, 0, 1, '', 1, 0); print ''; $arrayofoperators = array('<'=>'<', '>'=>'>'); print $form->selectarray('filter_op2', $arrayofoperators, $filter_op2, 1); @@ -497,8 +633,7 @@ if (!empty($arrayfields['cd.date_fin_validite']['checked'])) print $form->selectDate($filter_date2, 'op2', 0, 0, 1, '', 1, 0); print ''; $arrayofoperators = array('<'=>'<', '>'=>'>'); print $form->selectarray('filter_opcloture', $arrayofoperators, $filter_opcloture, 1); @@ -514,20 +649,17 @@ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; -if (!empty($arrayfields['cd.datec']['checked'])) -{ +if (!empty($arrayfields['cd.datec']['checked'])) { // Date creation print ''; print ''; print ''; $arrayofstatus = array( @@ -552,8 +684,7 @@ $productstatic = new Product($db); $i = 0; $totalarray = array(); -while ($i < min($num, $limit)) -{ +while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $contractstatic->id = $obj->cid; @@ -570,118 +701,142 @@ while ($i < min($num, $limit)) print '
    '; print $contractstatic->getNomUrl(1, 16); print ''; - if ($obj->pid > 0) - { + if ($obj->pid > 0) { $productstatic->id = $obj->pid; $productstatic->type = $obj->ptype; $productstatic->ref = $obj->pref; $productstatic->entity = $obj->pentity; print $productstatic->getNomUrl(1, '', 24); print $obj->label ? ' - '.dol_trunc($obj->label, 16) : ''; - if (!empty($obj->description) && !empty($conf->global->PRODUCT_DESC_IN_LIST)) print '
    '.dol_nl2br($obj->description); + if (!empty($obj->description) && !empty($conf->global->PRODUCT_DESC_IN_LIST)) { + print '
    '.dol_nl2br($obj->description); + } } else { - if ($obj->type == 0) print img_object($obj->description, 'product').' '.dol_trunc($obj->description, 24); - if ($obj->type == 1) print img_object($obj->description, 'service').' '.dol_trunc($obj->description, 24); + if ($obj->type == 0) { + print img_object($obj->description, 'product').' '.dol_trunc($obj->description, 24); + } + if ($obj->type == 1) { + print img_object($obj->description, 'service').' '.dol_trunc($obj->description, 24); + } } print '
    '; print $obj->qty; print ''; print price($obj->total_ht); print ''; print price($obj->total_tva); print ''; print price2num($obj->tva_tx).'%'; print ''; print price($obj->subprice); print ''; print $companystatic->getNomUrl(1, 'customer', 28); print ''; print ($obj->date_ouverture_prevue ?dol_print_date($db->jdate($obj->date_ouverture_prevue), 'dayhour') : ' '); - if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) - print ' '.img_picto($langs->trans("Late"), "warning"); - else print '    '; + if ($db->jdate($obj->date_ouverture_prevue) && ($db->jdate($obj->date_ouverture_prevue) < ($now - $conf->contrat->services->inactifs->warning_delay)) && $obj->statut == 0) { + print ' '.img_picto($langs->trans("Late"), "warning"); + } else { + print '    '; + } print ''.($obj->date_ouverture ?dol_print_date($db->jdate($obj->date_ouverture), 'dayhour') : ' ').''.($obj->date_fin_validite ?dol_print_date($db->jdate($obj->date_fin_validite), 'dayhour') : ' '); - if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) - { + if ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < ($now - $conf->contrat->services->expires->warning_delay) && $obj->statut < 5) { $warning_delay = $conf->contrat->services->expires->warning_delay / 3600 / 24; $textlate = $langs->trans("Late").' = '.$langs->trans("DateReference").' > '.$langs->trans("DateToday").' '.(ceil($warning_delay) >= 0 ? '+' : '').ceil($warning_delay).' '.$langs->trans("days"); print img_warning($textlate); - } else print '    '; + } else { + print '    '; + } print ''.dol_print_date($db->jdate($obj->date_cloture), 'dayhour').''; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print ''; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print ''; - if ($obj->cstatut == 0) - { + if ($obj->cstatut == 0) { // If contract is draft, we say line is also draft print $contractstatic->LibStatut(0, 5); } else { print $staticcontratligne->LibStatut($obj->statut, 5, ($obj->date_fin_validite && $db->jdate($obj->date_fin_validite) < $now) ? 1 : 0); } print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + if (in_array($obj->rowid, $arrayofselected)) { + $selected = 1; + } print ''; } print '
    trans("Contract"); ?>getNomUrl(1); ?>trans("Contract"); ?>getNomUrl(1); ?> date_contrat, 'day'); ?>rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) - { + if ($user->rights->contrat->lire && empty($conf->global->CONTRACT_SHOW_TOTAL_OF_PRODUCT_AS_PRICE)) { $totalcontrat = 0; foreach ($objectlink->lines as $linecontrat) { $totalcontrat = $totalcontrat + $linecontrat->total_ht; From 554e449e407c4caec9bd203e67cab380acc4b53d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Tue, 23 Feb 2021 22:03:23 +0100 Subject: [PATCH 23/64] code syntax core directory --- htdocs/core/actions_addupdatedelete.inc.php | 207 +- htdocs/core/actions_builddoc.inc.php | 73 +- .../core/actions_changeselectedfields.inc.php | 10 +- htdocs/core/actions_comments.inc.php | 27 +- htdocs/core/actions_dellink.inc.php | 10 +- htdocs/core/actions_extrafields.inc.php | 130 +- htdocs/core/actions_fetchobject.inc.php | 15 +- htdocs/core/actions_lineupdown.inc.php | 22 +- htdocs/core/actions_linkedfiles.inc.php | 124 +- htdocs/core/actions_massactions.inc.php | 836 ++-- htdocs/core/actions_printing.inc.php | 19 +- htdocs/core/actions_setmoduleoptions.inc.php | 69 +- htdocs/core/actions_setnotes.inc.php | 44 +- htdocs/core/ajax/ajaxdirpreview.php | 269 +- htdocs/core/ajax/ajaxdirtree.php | 217 +- htdocs/core/ajax/bankconciliate.php | 32 +- htdocs/core/ajax/box.php | 39 +- htdocs/core/ajax/check_notifications.php | 64 +- htdocs/core/ajax/constantonoff.php | 40 +- htdocs/core/ajax/contacts.php | 19 +- htdocs/core/ajax/extraparams.php | 23 +- htdocs/core/ajax/fileupload.php | 16 +- htdocs/core/ajax/getaccountcurrency.php | 15 +- htdocs/core/ajax/loadinplace.php | 59 +- htdocs/core/ajax/objectonoff.php | 28 +- htdocs/core/ajax/pingresult.php | 33 +- htdocs/core/ajax/price.php | 22 +- htdocs/core/ajax/row.php | 37 +- htdocs/core/ajax/saveinplace.php | 63 +- htdocs/core/ajax/security.php | 30 +- htdocs/core/ajax/selectobject.php | 41 +- htdocs/core/ajax/selectsearchbox.php | 117 +- htdocs/core/ajax/vatrates.php | 18 +- htdocs/core/ajax/ziptown.php | 58 +- htdocs/core/antispamimage.php | 30 +- .../box_accountancy_last_manual_entries.php | 9 +- .../box_accountancy_suspense_account.php | 9 +- htdocs/core/boxes/box_actions.php | 47 +- htdocs/core/boxes/box_activity.php | 39 +- htdocs/core/boxes/box_birthdays.php | 19 +- htdocs/core/boxes/box_birthdays_members.php | 23 +- htdocs/core/boxes/box_boms.php | 13 +- htdocs/core/boxes/box_bookmarks.php | 10 +- htdocs/core/boxes/box_clients.php | 31 +- htdocs/core/boxes/box_commandes.php | 36 +- htdocs/core/boxes/box_comptes.php | 6 +- htdocs/core/boxes/box_contacts.php | 21 +- htdocs/core/boxes/box_contracts.php | 31 +- ...box_customers_outstanding_bill_reached.php | 34 +- .../core/boxes/box_dolibarr_state_board.php | 4 +- htdocs/core/boxes/box_external_rss.php | 50 +- htdocs/core/boxes/box_factures.php | 25 +- htdocs/core/boxes/box_factures_fourn.php | 28 +- htdocs/core/boxes/box_factures_fourn_imp.php | 24 +- htdocs/core/boxes/box_factures_imp.php | 27 +- htdocs/core/boxes/box_ficheinter.php | 27 +- htdocs/core/boxes/box_fournisseurs.php | 23 +- htdocs/core/boxes/box_goodcustomers.php | 23 +- .../boxes/box_graph_invoices_permonth.php | 89 +- .../box_graph_invoices_supplier_permonth.php | 93 +- .../core/boxes/box_graph_orders_permonth.php | 89 +- .../box_graph_orders_supplier_permonth.php | 83 +- .../boxes/box_graph_product_distribution.php | 153 +- .../boxes/box_graph_propales_permonth.php | 89 +- .../core/boxes/box_last_modified_ticket.php | 4 +- htdocs/core/boxes/box_lastlogin.php | 7 +- htdocs/core/boxes/box_mos.php | 13 +- .../core/boxes/box_produits_alerte_stock.php | 36 +- htdocs/core/boxes/box_project.php | 17 +- htdocs/core/boxes/box_prospect.php | 25 +- htdocs/core/boxes/box_services_contracts.php | 36 +- htdocs/core/boxes/box_services_expired.php | 28 +- htdocs/core/boxes/box_shipments.php | 28 +- htdocs/core/boxes/box_supplier_orders.php | 28 +- ...box_supplier_orders_awaiting_reception.php | 28 +- htdocs/core/boxes/box_task.php | 8 +- htdocs/core/boxes/box_validated_projects.php | 15 +- htdocs/core/boxes/modules_boxes.php | 180 +- htdocs/core/class/CSMSFile.class.php | 57 +- htdocs/core/class/antivir.class.php | 22 +- htdocs/core/class/canvas.class.php | 43 +- htdocs/core/class/ccountry.class.php | 109 +- .../core/class/commondocgenerator.class.php | 276 +- htdocs/core/class/commonincoterm.class.php | 21 +- htdocs/core/class/commoninvoice.class.php | 190 +- htdocs/core/class/commonobject.class.php | 3121 +++++++------ htdocs/core/class/commonobjectline.class.php | 14 +- .../class/commonstickergenerator.class.php | 4 +- htdocs/core/class/conf.class.php | 408 +- htdocs/core/class/coreobject.class.php | 156 +- htdocs/core/class/cproductnature.class.php | 35 +- htdocs/core/class/cstate.class.php | 79 +- htdocs/core/class/ctypent.class.php | 103 +- htdocs/core/class/ctyperesource.class.php | 10 +- htdocs/core/class/cunits.class.php | 128 +- htdocs/core/class/discount.class.php | 192 +- htdocs/core/class/doleditor.class.php | 64 +- htdocs/core/class/dolgeoip.class.php | 89 +- htdocs/core/class/dolgraph.class.php | 221 +- htdocs/core/class/dolreceiptprinter.class.php | 34 +- .../core/class/emailsenderprofile.class.php | 35 +- htdocs/core/class/evalmath.class.php | 51 +- htdocs/core/class/events.class.php | 23 +- htdocs/core/class/extrafields.class.php | 625 +-- htdocs/core/class/extralanguages.class.php | 22 +- htdocs/core/class/fileupload.class.php | 55 +- htdocs/core/class/fiscalyear.class.php | 148 +- htdocs/core/class/hookmanager.class.php | 98 +- htdocs/core/class/html.form.class.php | 3477 ++++++++------- .../core/class/html.formaccounting.class.php | 72 +- htdocs/core/class/html.formactions.class.php | 153 +- htdocs/core/class/html.formadmin.class.php | 208 +- htdocs/core/class/html.formbarcode.class.php | 15 +- htdocs/core/class/html.formcategory.class.php | 3 +- htdocs/core/class/html.formcompany.class.php | 348 +- htdocs/core/class/html.formcontract.class.php | 57 +- .../class/html.formexpensereport.class.php | 42 +- htdocs/core/class/html.formfile.class.php | 944 ++-- .../class/html.formintervention.class.php | 42 +- htdocs/core/class/html.formmargin.class.php | 81 +- htdocs/core/class/html.formorder.class.php | 7 +- htdocs/core/class/html.formother.class.php | 492 ++- htdocs/core/class/html.formprojet.class.php | 283 +- htdocs/core/class/html.formpropal.class.php | 32 +- htdocs/core/class/html.formsms.class.php | 94 +- .../class/html.formsocialcontrib.class.php | 35 +- htdocs/core/class/html.formticket.class.php | 68 +- htdocs/core/class/html.formwebsite.class.php | 88 +- htdocs/core/class/infobox.class.php | 43 +- htdocs/core/class/interfaces.class.php | 150 +- htdocs/core/class/ldap.class.php | 344 +- htdocs/core/class/lessc.class.php | 2939 +++++++------ htdocs/core/class/link.class.php | 73 +- htdocs/core/class/menu.class.php | 7 +- htdocs/core/class/menubase.class.php | 127 +- htdocs/core/class/notify.class.php | 38 +- htdocs/core/class/openid.class.php | 93 +- htdocs/core/class/rssparser.class.php | 273 +- htdocs/core/class/smtps.class.php | 481 +- htdocs/core/class/stats.class.php | 280 +- htdocs/core/class/translate.class.php | 444 +- htdocs/core/class/utils.class.php | 500 ++- htdocs/core/class/vcard.class.php | 107 +- htdocs/core/commonfieldsinexport.inc.php | 13 +- htdocs/core/customreports.php | 105 +- htdocs/core/datepicker.php | 132 +- htdocs/core/db/DoliDB.class.php | 50 +- htdocs/core/db/mysqli.class.php | 327 +- htdocs/core/db/pgsql.class.php | 399 +- htdocs/core/db/sqlite3.class.php | 436 +- htdocs/core/extrafieldsinexport.inc.php | 22 +- .../browser/default/frmresourceslist.php | 22 +- .../filemanagerdol/connectors/php/basexml.php | 12 +- .../connectors/php/commands.php | 115 +- .../filemanagerdol/connectors/php/config.php | 28 +- .../connectors/php/connector.php | 24 +- .../core/filemanagerdol/connectors/php/io.php | 70 +- .../filemanagerdol/connectors/php/upload.php | 9 +- .../filemanagerdol/connectors/php/util.php | 36 +- htdocs/core/get_info.php | 65 +- htdocs/core/get_menudiv.php | 72 +- htdocs/core/js/lib_gravatar.js.php | 243 +- htdocs/core/js/lib_head.js.php | 301 +- htdocs/core/js/lib_notification.js.php | 213 +- htdocs/core/js/timepicker.js.php | 39 +- htdocs/core/lib/accounting.lib.php | 55 +- htdocs/core/lib/admin.lib.php | 6 +- htdocs/core/lib/agenda.lib.php | 94 +- htdocs/core/lib/ajax.lib.php | 57 +- htdocs/core/lib/asset.lib.php | 16 +- htdocs/core/lib/bank.lib.php | 65 +- htdocs/core/lib/barcode.lib.php | 162 +- htdocs/core/lib/categories.lib.php | 3 +- htdocs/core/lib/company.lib.php | 398 +- htdocs/core/lib/contact.lib.php | 19 +- htdocs/core/lib/contract.lib.php | 29 +- htdocs/core/lib/cron.lib.php | 18 +- htdocs/core/lib/date.lib.php | 357 +- htdocs/core/lib/doc.lib.php | 85 +- htdocs/core/lib/doleditor.lib.php | 68 +- htdocs/core/lib/donation.lib.php | 16 +- htdocs/core/lib/ecm.lib.php | 18 +- htdocs/core/lib/emailing.lib.php | 10 +- htdocs/core/lib/expedition.lib.php | 25 +- htdocs/core/lib/expensereport.lib.php | 29 +- htdocs/core/lib/fichinter.lib.php | 37 +- htdocs/core/lib/files.lib.php | 1468 +++---- htdocs/core/lib/format_cards.lib.php | 9 +- htdocs/core/lib/fourn.lib.php | 75 +- htdocs/core/lib/functions.lib.php | 3862 ++++++++++------- htdocs/core/lib/functions2.lib.php | 1368 +++--- htdocs/core/lib/functions_ch.lib.php | 3 +- htdocs/core/lib/functionsnumtoword.lib.php | 46 +- htdocs/core/lib/geturl.lib.php | 42 +- htdocs/core/lib/holiday.lib.php | 4 +- htdocs/core/lib/images.lib.php | 206 +- htdocs/core/lib/import.lib.php | 7 +- htdocs/core/lib/invoice.lib.php | 44 +- htdocs/core/lib/invoice2.lib.php | 209 +- htdocs/core/lib/json.lib.php | 124 +- htdocs/core/lib/ldap.lib.php | 75 +- htdocs/core/lib/loan.lib.php | 8 +- htdocs/core/lib/member.lib.php | 42 +- htdocs/core/lib/memory.lib.php | 43 +- htdocs/core/lib/modulebuilder.lib.php | 202 +- htdocs/core/lib/multicurrency.lib.php | 3 +- htdocs/core/lib/oauth.lib.php | 3 +- htdocs/core/lib/order.lib.php | 64 +- htdocs/core/lib/parsemd.lib.php | 15 +- htdocs/core/lib/payments.lib.php | 229 +- htdocs/core/lib/pdf.lib.php | 1106 ++--- htdocs/core/lib/prelevement.lib.php | 20 +- htdocs/core/lib/price.lib.php | 156 +- htdocs/core/lib/product.lib.php | 171 +- htdocs/core/lib/project.lib.php | 1253 +++--- htdocs/core/lib/propal.lib.php | 37 +- htdocs/core/lib/receiptprinter.lib.php | 3 +- htdocs/core/lib/reception.lib.php | 28 +- htdocs/core/lib/report.lib.php | 34 +- htdocs/core/lib/resource.lib.php | 29 +- htdocs/core/lib/salaries.lib.php | 4 +- htdocs/core/lib/security.lib.php | 446 +- htdocs/core/lib/security2.lib.php | 161 +- htdocs/core/lib/sendings.lib.php | 176 +- htdocs/core/lib/signature.lib.php | 27 +- htdocs/core/lib/stock.lib.php | 3 +- htdocs/core/lib/supplier_proposal.lib.php | 26 +- htdocs/core/lib/takepos.lib.php | 3 +- htdocs/core/lib/tax.lib.php | 485 ++- htdocs/core/lib/ticket.lib.php | 135 +- htdocs/core/lib/treeview.lib.php | 87 +- htdocs/core/lib/usergroups.lib.php | 426 +- htdocs/core/lib/vat.lib.php | 4 +- htdocs/core/lib/website.lib.php | 261 +- htdocs/core/lib/website2.lib.php | 96 +- htdocs/core/lib/ws.lib.php | 32 +- htdocs/core/lib/xcal.lib.php | 170 +- htdocs/core/login/functions_dolibarr.php | 51 +- htdocs/core/login/functions_forceuser.php | 8 +- htdocs/core/login/functions_googleoauth.php | 37 +- htdocs/core/login/functions_http.php | 3 +- htdocs/core/login/functions_ldap.php | 102 +- htdocs/core/login/functions_openid.php | 24 +- htdocs/core/menus/standard/auguria.lib.php | 294 +- htdocs/core/menus/standard/auguria_menu.php | 182 +- htdocs/core/modules/DolibarrModules.class.php | 255 +- htdocs/core/modules/action/modules_action.php | 32 +- htdocs/core/modules/action/rapport.pdf.php | 80 +- .../core/modules/bank/doc/pdf_ban.modules.php | 107 +- .../bank/doc/pdf_sepamandate.modules.php | 171 +- .../barcode/doc/phpbarcode.modules.php | 47 +- .../barcode/doc/tcpdfbarcode.modules.php | 8 +- .../barcode/mod_barcode_product_standard.php | 118 +- .../modules/barcode/modules_barcode.class.php | 65 +- .../bom/doc/doc_generic_bom_odt.modules.php | 140 +- htdocs/core/modules/bom/mod_bom_advanced.php | 10 +- htdocs/core/modules/bom/mod_bom_standard.php | 29 +- htdocs/core/modules/bom/modules_bom.php | 16 +- .../modules/cheque/doc/pdf_blochet.class.php | 67 +- .../modules/cheque/mod_chequereceipt_mint.php | 29 +- .../cheque/mod_chequereceipt_thyme.php | 8 +- .../modules/cheque/modules_chequereceipts.php | 28 +- .../doc/doc_generic_order_odt.modules.php | 134 +- .../commande/doc/pdf_einstein.modules.php | 473 +- .../commande/doc/pdf_eratosthene.modules.php | 581 ++- .../modules/commande/mod_commande_marbre.php | 29 +- .../modules/commande/mod_commande_saphir.php | 10 +- .../modules/commande/modules_commande.php | 16 +- .../doc/doc_generic_contract_odt.modules.php | 120 +- .../contract/doc/pdf_strato.modules.php | 174 +- .../modules/contract/mod_contract_magre.php | 10 +- .../modules/contract/mod_contract_olive.php | 6 +- .../modules/contract/mod_contract_serpis.php | 29 +- .../modules/contract/modules_contract.php | 16 +- .../delivery/doc/pdf_storm.modules.php | 293 +- .../delivery/doc/pdf_typhon.modules.php | 209 +- .../modules/delivery/mod_delivery_jade.php | 28 +- .../modules/delivery/mod_delivery_saphir.php | 8 +- .../modules/delivery/modules_delivery.php | 16 +- .../modules/dons/html_cerfafr.modules.php | 99 +- htdocs/core/modules/dons/modules_don.php | 16 +- .../doc/doc_generic_shipment_odt.modules.php | 195 +- .../expedition/doc/pdf_espadon.modules.php | 388 +- .../expedition/doc/pdf_merou.modules.php | 123 +- .../expedition/doc/pdf_rouget.modules.php | 370 +- .../expedition/mod_expedition_ribera.php | 10 +- .../expedition/mod_expedition_safor.php | 29 +- .../modules/expedition/modules_expedition.php | 16 +- .../doc/pdf_standard.modules.php | 199 +- .../expensereport/mod_expensereport_jade.php | 43 +- .../expensereport/mod_expensereport_sand.php | 22 +- .../expensereport/modules_expensereport.php | 16 +- .../modules/export/export_csv.modules.php | 54 +- .../export/export_excel2007.modules.php | 97 +- .../modules/export/export_tsv.modules.php | 27 +- htdocs/core/modules/export/modules_export.php | 12 +- .../doc/doc_generic_invoice_odt.modules.php | 135 +- .../modules/facture/doc/pdf_crabe.modules.php | 626 +-- .../facture/doc/pdf_sponge.modules.php | 650 ++- .../core/modules/facture/mod_facture_mars.php | 78 +- .../modules/facture/mod_facture_mercure.php | 26 +- .../modules/facture/mod_facture_terre.php | 85 +- .../core/modules/facture/modules_facture.php | 16 +- .../fichinter/doc/pdf_soleil.modules.php | 157 +- htdocs/core/modules/fichinter/mod_arctic.php | 10 +- htdocs/core/modules/fichinter/mod_pacific.php | 29 +- .../modules/fichinter/modules_fichinter.php | 48 +- .../holiday/mod_holiday_immaculate.php | 10 +- .../modules/holiday/mod_holiday_madonna.php | 29 +- .../core/modules/holiday/modules_holiday.php | 16 +- .../modules/import/import_csv.modules.php | 285 +- .../modules/import/import_xlsx.modules.php | 180 +- htdocs/core/modules/import/modules_import.php | 9 +- .../mailings/advthirdparties.modules.php | 47 +- .../modules/mailings/contacts1.modules.php | 189 +- .../core/modules/mailings/example.modules.php | 2 +- .../core/modules/mailings/fraise.modules.php | 56 +- .../modules/mailings/modules_mailings.php | 73 +- .../core/modules/mailings/pomme.modules.php | 25 +- .../modules/mailings/thirdparties.modules.php | 56 +- .../thirdparties_services_expired.modules.php | 32 +- .../modules/mailings/xinputfile.modules.php | 37 +- .../modules/mailings/xinputuser.modules.php | 12 +- .../doc/doc_generic_member_odt.class.php | 55 +- .../modules/member/doc/pdf_standard.class.php | 169 +- htdocs/core/modules/member/modules_cards.php | 40 +- htdocs/core/modules/modAdherent.class.php | 36 +- htdocs/core/modules/modAgenda.class.php | 26 +- htdocs/core/modules/modApi.class.php | 3 +- htdocs/core/modules/modAsset.class.php | 3 +- htdocs/core/modules/modBanque.class.php | 3 +- htdocs/core/modules/modBlockedLog.class.php | 25 +- htdocs/core/modules/modBom.class.php | 49 +- htdocs/core/modules/modCategorie.class.php | 71 +- htdocs/core/modules/modCollab.class.php | 28 +- htdocs/core/modules/modCommande.class.php | 17 +- htdocs/core/modules/modContrat.class.php | 6 +- htdocs/core/modules/modDataPolicy.class.php | 44 +- htdocs/core/modules/modDav.class.php | 29 +- htdocs/core/modules/modDeplacement.class.php | 15 +- .../core/modules/modEmailCollector.class.php | 45 +- htdocs/core/modules/modExpedition.class.php | 25 +- htdocs/core/modules/modExternalRss.class.php | 9 +- htdocs/core/modules/modFacture.class.php | 40 +- htdocs/core/modules/modFournisseur.class.php | 122 +- htdocs/core/modules/modHoliday.class.php | 2 +- htdocs/core/modules/modIncoterm.class.php | 3 +- .../core/modules/modIntracommreport.class.php | 3 +- htdocs/core/modules/modMrp.class.php | 116 +- .../core/modules/modMultiCurrency.class.php | 39 +- htdocs/core/modules/modOauth.class.php | 10 +- htdocs/core/modules/modPaypal.class.php | 28 +- htdocs/core/modules/modProduct.class.php | 272 +- htdocs/core/modules/modProductBatch.class.php | 3 +- htdocs/core/modules/modProjet.class.php | 31 +- htdocs/core/modules/modPropale.class.php | 21 +- htdocs/core/modules/modReception.class.php | 25 +- htdocs/core/modules/modRecruitment.class.php | 14 +- htdocs/core/modules/modResource.class.php | 6 +- htdocs/core/modules/modService.class.php | 312 +- htdocs/core/modules/modSociete.class.php | 48 +- htdocs/core/modules/modStock.class.php | 23 +- htdocs/core/modules/modStripe.class.php | 28 +- .../modules/modSupplierProposal.class.php | 8 +- htdocs/core/modules/modTakePos.class.php | 29 +- htdocs/core/modules/modTicket.class.php | 6 +- htdocs/core/modules/modUser.class.php | 9 +- htdocs/core/modules/modVariants.class.php | 3 +- htdocs/core/modules/modWebsite.class.php | 13 +- htdocs/core/modules/modWorkflow.class.php | 64 +- htdocs/core/modules/modWorkstation.class.php | 54 +- htdocs/core/modules/modZapier.class.php | 112 +- .../movement/doc/pdf_standard.modules.php | 428 +- .../mrp/doc/doc_generic_mo_odt.modules.php | 137 +- htdocs/core/modules/mrp/mod_mo_advanced.php | 10 +- htdocs/core/modules/mrp/mod_mo_standard.php | 29 +- htdocs/core/modules/mrp/modules_mo.php | 16 +- .../modules/oauth/github_oauthcallback.php | 16 +- .../modules/oauth/google_oauthcallback.php | 16 +- .../oauth/stripelive_oauthcallback.php | 17 +- .../oauth/stripetest_oauthcallback.php | 17 +- .../core/modules/payment/mod_payment_ant.php | 10 +- .../modules/payment/mod_payment_cicada.php | 29 +- .../core/modules/payment/modules_payment.php | 16 +- .../modules/printing/modules_printing.php | 7 +- .../modules/printing/printgcp.modules.php | 37 +- .../modules/printing/printipp.modules.php | 15 +- .../doc/pdf_standardlabel.class.php | 128 +- .../printsheet/doc/pdf_tcpdflabel.class.php | 114 +- .../modules/printsheet/modules_labels.php | 55 +- .../doc/doc_generic_product_odt.modules.php | 117 +- .../product/doc/pdf_standard.modules.php | 248 +- .../product/mod_codeproduct_elephant.php | 85 +- .../product/mod_codeproduct_leopard.php | 6 +- .../doc/doc_generic_project_odt.modules.php | 286 +- .../project/doc/pdf_baleine.modules.php | 189 +- .../project/doc/pdf_beluga.modules.php | 174 +- .../project/doc/pdf_timespent.modules.php | 189 +- .../modules/project/mod_project_simple.php | 29 +- .../modules/project/mod_project_universal.php | 6 +- .../core/modules/project/modules_project.php | 16 +- .../task/doc/doc_generic_task_odt.modules.php | 213 +- .../modules/project/task/mod_task_simple.php | 29 +- .../modules/project/task/modules_task.php | 12 +- .../doc/doc_generic_proposal_odt.modules.php | 144 +- .../modules/propale/doc/pdf_azur.modules.php | 552 ++- .../modules/propale/doc/pdf_cyan.modules.php | 562 ++- .../modules/propale/mod_propale_marbre.php | 29 +- .../modules/propale/mod_propale_saphir.php | 10 +- .../core/modules/propale/modules_propale.php | 16 +- .../modules/rapport/pdf_paiement.class.php | 137 +- .../doc/doc_generic_reception_odt.modules.php | 139 +- .../reception/doc/pdf_squille.modules.php | 337 +- .../modules/reception/mod_reception_beryl.php | 29 +- .../reception/mod_reception_moonstone.php | 10 +- .../modules/reception/modules_reception.php | 13 +- .../generate/modGeneratePassPerso.class.php | 7 +- .../modGeneratePassStandard.class.php | 10 +- .../societe/doc/doc_generic_odt.modules.php | 125 +- .../societe/mod_codeclient_elephant.php | 66 +- .../societe/mod_codeclient_leopard.php | 6 +- .../modules/societe/mod_codeclient_monkey.php | 52 +- .../societe/mod_codecompta_aquarium.php | 60 +- .../societe/mod_codecompta_digitaria.php | 60 +- .../societe/mod_codecompta_panicum.php | 7 +- .../doc/doc_generic_stock_odt.modules.php | 120 +- .../stock/doc/pdf_standard.modules.php | 196 +- .../doc/pdf_canelle.modules.php | 348 +- .../mod_facture_fournisseur_cactus.php | 82 +- .../mod_facture_fournisseur_tulip.php | 25 +- .../modules_facturefournisseur.php | 16 +- ...doc_generic_supplier_order_odt.modules.php | 137 +- .../supplier_order/doc/pdf_cornas.modules.php | 474 +- .../doc/pdf_muscadet.modules.php | 415 +- .../mod_commande_fournisseur_muguet.php | 37 +- .../mod_commande_fournisseur_orchidee.php | 6 +- .../modules_commandefournisseur.php | 16 +- .../doc/pdf_standard.modules.php | 172 +- .../mod_supplier_payment_brodator.php | 10 +- .../mod_supplier_payment_bronan.php | 29 +- .../modules_supplier_payment.php | 13 +- ..._generic_supplier_proposal_odt.modules.php | 141 +- .../doc/pdf_aurore.modules.php | 6 +- .../mod_supplier_proposal_marbre.php | 29 +- .../mod_supplier_proposal_saphir.php | 10 +- .../modules_supplier_proposal.php | 16 +- .../core/modules/syslog/mod_syslog_file.php | 43 +- .../core/modules/syslog/mod_syslog_syslog.php | 22 +- .../takepos/mod_takepos_ref_simple.php | 39 +- .../core/modules/takepos/modules_takepos.php | 16 +- .../doc/doc_generic_ticket_odt.modules.php | 96 +- .../user/doc/doc_generic_user_odt.modules.php | 102 +- .../doc/doc_generic_usergroup_odt.modules.php | 126 +- .../workstation/mod_workstation_advanced.php | 6 +- .../workstation/mod_workstation_standard.php | 27 +- .../workstation/modules_workstation.php | 16 +- htdocs/core/photos_resize.php | 316 +- htdocs/core/search.php | 95 +- htdocs/core/search_page.php | 36 +- htdocs/core/tools.php | 4 +- htdocs/core/tpl/admin_extrafields_add.tpl.php | 127 +- .../core/tpl/admin_extrafields_edit.tpl.php | 156 +- .../core/tpl/admin_extrafields_view.tpl.php | 20 +- htdocs/core/tpl/advtarget.tpl.php | 6 +- htdocs/core/tpl/ajax/fileupload_main.tpl.php | 31 +- htdocs/core/tpl/ajax/fileupload_view.tpl.php | 103 +- .../tpl/ajax/objectlinked_lineimport.tpl.php | 90 +- htdocs/core/tpl/ajaxrow.tpl.php | 23 +- htdocs/core/tpl/bloc_comment.tpl.php | 33 +- htdocs/core/tpl/bloc_showhide.tpl.php | 11 +- htdocs/core/tpl/card_presend.tpl.php | 48 +- htdocs/core/tpl/commonfields_add.tpl.php | 62 +- htdocs/core/tpl/commonfields_edit.tpl.php | 55 +- htdocs/core/tpl/commonfields_view.tpl.php | 98 +- htdocs/core/tpl/contacts.tpl.php | 74 +- .../tpl/document_actions_post_headers.tpl.php | 39 +- htdocs/core/tpl/extrafields_add.tpl.php | 11 +- htdocs/core/tpl/extrafields_edit.tpl.php | 7 +- .../tpl/extrafields_list_array_fields.tpl.php | 17 +- .../tpl/extrafields_list_print_fields.tpl.php | 51 +- .../tpl/extrafields_list_search_input.tpl.php | 42 +- .../tpl/extrafields_list_search_param.tpl.php | 17 +- .../tpl/extrafields_list_search_sql.tpl.php | 55 +- .../tpl/extrafields_list_search_title.tpl.php | 31 +- htdocs/core/tpl/extrafields_view.tpl.php | 129 +- htdocs/core/tpl/filemanager.tpl.php | 76 +- htdocs/core/tpl/list_print_total.tpl.php | 25 +- htdocs/core/tpl/login.tpl.php | 138 +- htdocs/core/tpl/massactions_pre.tpl.php | 47 +- htdocs/core/tpl/notes.tpl.php | 26 +- htdocs/core/tpl/object_discounts.tpl.php | 7 +- htdocs/core/tpl/objectline_create.tpl.php | 235 +- htdocs/core/tpl/objectline_edit.tpl.php | 130 +- htdocs/core/tpl/objectline_title.tpl.php | 41 +- htdocs/core/tpl/objectline_view.tpl.php | 147 +- htdocs/core/tpl/onlinepaymentlinks.tpl.php | 51 +- htdocs/core/tpl/originproductline.tpl.php | 13 +- htdocs/core/tpl/passwordforgotten.tpl.php | 89 +- htdocs/core/tpl/resource_add.tpl.php | 3 +- htdocs/core/tpl/resource_view.tpl.php | 15 +- .../core/triggers/dolibarrtriggers.class.php | 2 +- .../interface_20_all_Logevents.class.php | 26 +- ...e_20_modWorkflow_WorkflowManager.class.php | 46 +- ...terface_50_modAgenda_ActionsAuto.class.php | 344 +- ..._modBlockedlog_ActionsBlockedLog.class.php | 17 +- ...interface_50_modLdap_Ldapsynchro.class.php | 68 +- ...odMailmanspip_Mailmanspipsynchro.class.php | 20 +- ..._50_modNotification_Notification.class.php | 37 +- ...terface_50_modTicket_TicketEmail.class.php | 28 +- .../interface_80_modStripe_Stripe.class.php | 40 +- ...rface_90_modSociete_ContactRoles.class.php | 6 +- htdocs/core/website.inc.php | 58 +- 512 files changed, 34726 insertions(+), 28660 deletions(-) diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php index 1c874fd2418..d7dcbf699c8 100644 --- a/htdocs/core/actions_addupdatedelete.inc.php +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -30,18 +30,17 @@ // $backtopage may be defined // $triggermodname may be defined -if (!empty($permissionedit) && empty($permissiontoadd)) $permissiontoadd = $permissionedit; // For backward compatibility +if (!empty($permissionedit) && empty($permissiontoadd)) { + $permissiontoadd = $permissionedit; // For backward compatibility +} -if ($cancel) -{ +if ($cancel) { /*var_dump($cancel); var_dump($backtopage);exit;*/ - if (!empty($backtopageforcancel)) - { + if (!empty($backtopageforcancel)) { header("Location: ".$backtopageforcancel); exit; - } elseif (!empty($backtopage)) - { + } elseif (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -50,19 +49,25 @@ if ($cancel) // Action to add record -if ($action == 'add' && !empty($permissiontoadd)) -{ - foreach ($object->fields as $key => $val) - { +if ($action == 'add' && !empty($permissiontoadd)) { + foreach ($object->fields as $key => $val) { if ($object->fields[$key]['type'] == 'duration') { - if (GETPOST($key.'hour') == '' && GETPOST($key.'min') == '') continue; // The field was not submited to be edited + if (GETPOST($key.'hour') == '' && GETPOST($key.'min') == '') { + continue; // The field was not submited to be edited + } } else { - if (!GETPOSTISSET($key)) continue; // The field was not submited to be edited + if (!GETPOSTISSET($key)) { + continue; // The field was not submited to be edited + } } // Ignore special fields - if (in_array($key, array('rowid', 'entity', 'import_key'))) continue; + if (in_array($key, array('rowid', 'entity', 'import_key'))) { + continue; + } if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) { - if (!in_array(abs($val['visible']), array(1, 3))) continue; // Only 1 and 3 that are case to create + if (!in_array(abs($val['visible']), array(1, 3))) { + continue; // Only 1 and 3 that are case to create + } } // Set value to insert @@ -84,17 +89,19 @@ if ($action == 'add' && !empty($permissiontoadd)) } else { $value = GETPOST($key, 'alphanohtml'); } - if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value = ''; // This is an implicit foreign key field - if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') $value = ''; // This is an explicit foreign key field + if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') { + $value = ''; // This is an implicit foreign key field + } + if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') { + $value = ''; // This is an explicit foreign key field + } //var_dump($key.' '.$value.' '.$object->fields[$key]['type']); $object->$key = $value; - if ($val['notnull'] > 0 && $object->$key == '' && !is_null($val['default']) && $val['default'] == '(PROV)') - { + if ($val['notnull'] > 0 && $object->$key == '' && !is_null($val['default']) && $val['default'] == '(PROV)') { $object->$key = '(PROV)'; } - if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) - { + if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val['label'])), null, 'errors'); } @@ -103,14 +110,14 @@ if ($action == 'add' && !empty($permissiontoadd)) // Fill array 'array_options' with data from add form if (!$error) { $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $result = $object->create($user); - if ($result > 0) - { + if ($result > 0) { // Creation OK $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist; $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $urltogo); // New method to autoselect project after a New on another form object creation @@ -118,8 +125,11 @@ if ($action == 'add' && !empty($permissiontoadd)) exit; } else { // Creation KO - if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); + if (!empty($object->errors)) { + setEventMessages(null, $object->errors, 'errors'); + } else { + setEventMessages($object->error, null, 'errors'); + } $action = 'create'; } } else { @@ -128,25 +138,31 @@ if ($action == 'add' && !empty($permissiontoadd)) } // Action to update record -if ($action == 'update' && !empty($permissiontoadd)) -{ - foreach ($object->fields as $key => $val) - { +if ($action == 'update' && !empty($permissiontoadd)) { + foreach ($object->fields as $key => $val) { // Check if field was submited to be edited if ($object->fields[$key]['type'] == 'duration') { - if (!GETPOSTISSET($key.'hour') || !GETPOSTISSET($key.'min')) continue; // The field was not submited to be edited + if (!GETPOSTISSET($key.'hour') || !GETPOSTISSET($key.'min')) { + continue; // The field was not submited to be edited + } } elseif ($object->fields[$key]['type'] == 'boolean') { if (!GETPOSTISSET($key)) { $object->$key = 0; // use 0 instead null if the field is defined as not null continue; } } else { - if (!GETPOSTISSET($key)) continue; // The field was not submited to be edited + if (!GETPOSTISSET($key)) { + continue; // The field was not submited to be edited + } } // Ignore special fields - if (in_array($key, array('rowid', 'entity', 'import_key'))) continue; + if (in_array($key, array('rowid', 'entity', 'import_key'))) { + continue; + } if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) { - if (!in_array(abs($val['visible']), array(1, 3, 4))) continue; // Only 1 and 3 and 4 that are case to update + if (!in_array(abs($val['visible']), array(1, 3, 4))) { + continue; // Only 1 and 3 and 4 that are case to update + } } // Set value to update @@ -176,12 +192,15 @@ if ($action == 'update' && !empty($permissiontoadd)) } else { $value = GETPOST($key, 'alpha'); } - if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') $value = ''; // This is an implicit foreign key field - if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') $value = ''; // This is an explicit foreign key field + if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') { + $value = ''; // This is an implicit foreign key field + } + if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') { + $value = ''; // This is an explicit foreign key field + } $object->$key = $value; - if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) - { + if ($val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val['label'])), null, 'errors'); } @@ -190,14 +209,14 @@ if ($action == 'update' && !empty($permissiontoadd)) // Fill array 'array_options' with data from add form if (!$error) { $ret = $extrafields->setOptionalsFromPost(null, $object, '@GETPOSTISSET'); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $result = $object->update($user); - if ($result > 0) - { + if ($result > 0) { $action = 'view'; } else { // Creation KO @@ -210,8 +229,7 @@ if ($action == 'update' && !empty($permissiontoadd)) } // Action to update one extrafield -if ($action == "update_extras" && !empty($permissiontoadd)) -{ +if ($action == "update_extras" && !empty($permissiontoadd)) { $object->fetch(GETPOST('id', 'int')); $attributekey = GETPOST('attribute', 'alpha'); @@ -226,8 +244,7 @@ if ($action == "update_extras" && !empty($permissiontoadd)) } $result = $object->insertExtraFields(empty($triggermodname) ? '' : $triggermodname, $user); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans('RecordSaved'), null, 'mesgs'); $action = 'view'; } else { @@ -237,46 +254,42 @@ if ($action == "update_extras" && !empty($permissiontoadd)) } // Action to delete -if ($action == 'confirm_delete' && !empty($permissiontodelete)) -{ - if (!($object->id > 0)) - { +if ($action == 'confirm_delete' && !empty($permissiontodelete)) { + if (!($object->id > 0)) { dol_print_error('', 'Error, object must be fetched before being deleted'); exit; } $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { // Delete OK setEventMessages("RecordDeleted", null, 'mesgs'); header("Location: ".$backurlforlist); exit; } else { - if (!empty($object->errors)) setEventMessages(null, $object->errors, 'errors'); - else setEventMessages($object->error, null, 'errors'); + if (!empty($object->errors)) { + setEventMessages(null, $object->errors, 'errors'); + } else { + setEventMessages($object->error, null, 'errors'); + } } } // Remove a line -if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty($permissiontoadd)) -{ +if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty($permissiontoadd)) { if (method_exists($object, 'deleteline')) { $result = $object->deleteline($user, $lineid); // For backward compatibility } else { $result = $object->deleteLine($user, $lineid); } - if ($result > 0) - { + if ($result > 0) { // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); } - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && is_object($object->thirdparty)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && is_object($object->thirdparty)) { $newlang = $object->thirdparty->default_lang; } if (!empty($newlang)) { @@ -299,18 +312,20 @@ if ($action == 'confirm_deleteline' && $confirm == 'yes' && !empty($permissionto } // Action validate object -if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) -{ +if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) { $result = $object->validate($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { if (method_exists($object, 'generateDocument')) { $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 ($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); @@ -332,18 +347,20 @@ if ($action == 'confirm_validate' && $confirm == 'yes' && $permissiontoadd) } // Action close object -if ($action == 'confirm_close' && $confirm == 'yes' && $permissiontoadd) -{ +if ($action == 'confirm_close' && $confirm == 'yes' && $permissiontoadd) { $result = $object->cancel($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { if (method_exists($object, 'generateDocument')) { $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 ($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); @@ -360,11 +377,9 @@ if ($action == 'confirm_close' && $confirm == 'yes' && $permissiontoadd) } // Action setdraft object -if ($action == 'confirm_setdraft' && $confirm == 'yes' && $permissiontoadd) -{ +if ($action == 'confirm_setdraft' && $confirm == 'yes' && $permissiontoadd) { $result = $object->setDraft($user); - if ($result >= 0) - { + if ($result >= 0) { // Nothing else done } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -372,18 +387,20 @@ if ($action == 'confirm_setdraft' && $confirm == 'yes' && $permissiontoadd) } // Action reopen object -if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd) -{ +if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd) { $result = $object->reopen($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { if (method_exists($object, 'generateDocument')) { $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 ($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); @@ -400,21 +417,21 @@ if ($action == 'confirm_reopen' && $confirm == 'yes' && $permissiontoadd) } // Action clone object -if ($action == 'confirm_clone' && $confirm == 'yes' && !empty($permissiontoadd)) -{ - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { +if ($action == 'confirm_clone' && $confirm == 'yes' && !empty($permissiontoadd)) { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { $objectutil = dol_clone($object, 1); // To avoid to denaturate loaded object when setting some properties for clone or if createFromClone modifies the object. We use native clone to keep this->db valid. //$objectutil->date = dol_mktime(12, 0, 0, GETPOST('newdatemonth', 'int'), GETPOST('newdateday', 'int'), GETPOST('newdateyear', 'int')); // ... $result = $objectutil->createFromClone($user, (($object->id > 0) ? $object->id : $id)); - if (is_object($result) || $result > 0) - { + if (is_object($result) || $result > 0) { $newid = 0; - if (is_object($result)) $newid = $result->id; - else $newid = $result; + if (is_object($result)) { + $newid = $result->id; + } else { + $newid = $result; + } header("Location: ".$_SERVER['PHP_SELF'].'?id='.$newid); // Open record of new object exit; } else { diff --git a/htdocs/core/actions_builddoc.inc.php b/htdocs/core/actions_builddoc.inc.php index 4ae83829fa4..63cac253976 100644 --- a/htdocs/core/actions_builddoc.inc.php +++ b/htdocs/core/actions_builddoc.inc.php @@ -29,27 +29,26 @@ // $upload_dir must be defined (example $conf->projet->dir_output . "/";) // $hidedetails, $hidedesc, $hideref and $moreparams may have been set or not. -if (!empty($permissioncreate) && empty($permissiontoadd)) $permissiontoadd = $permissioncreate; // For backward compatibility +if (!empty($permissioncreate) && empty($permissiontoadd)) { + $permissiontoadd = $permissioncreate; // For backward compatibility +} // Build doc -if ($action == 'builddoc' && $permissiontoadd) -{ - if (is_numeric(GETPOST('model', 'alpha'))) - { +if ($action == 'builddoc' && $permissiontoadd) { + if (is_numeric(GETPOST('model', 'alpha'))) { $error = $langs->trans("ErrorFieldRequired", $langs->transnoentities("Model")); } else { - // Reload to get all modified line records and be ready for hooks + // Reload to get all modified line records and be ready for hooks $ret = $object->fetch($id); $ret = $object->fetch_thirdparty(); /*if (empty($object->id) || ! $object->id > 0) - { - dol_print_error('Object must have been loaded by a fetch'); - exit; - }*/ + { + dol_print_error('Object must have been loaded by a fetch'); + exit; + }*/ // Save last template used to generate document - if (GETPOST('model', 'alpha')) - { + if (GETPOST('model', 'alpha')) { $object->setDocModel($user, GETPOST('model', 'alpha')); } @@ -67,29 +66,40 @@ if ($action == 'builddoc' && $permissiontoadd) $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) && isset($object->thirdparty->default_lang)) $newlang = $object->thirdparty->default_lang; // for proposal, order, invoice, ... - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) $newlang = $object->default_lang; // for thirdparty - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->thirdparty->default_lang)) { + $newlang = $object->thirdparty->default_lang; // for proposal, order, invoice, ... + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($object->default_lang)) { + $newlang = $object->default_lang; // for thirdparty + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } // To be sure vars is defined - if (empty($hidedetails)) $hidedetails = 0; - if (empty($hidedesc)) $hidedesc = 0; - if (empty($hideref)) $hideref = 0; - if (empty($moreparams)) $moreparams = null; + if (empty($hidedetails)) { + $hidedetails = 0; + } + if (empty($hidedesc)) { + $hidedesc = 0; + } + if (empty($hideref)) { + $hideref = 0; + } + if (empty($moreparams)) { + $moreparams = null; + } $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = ''; } else { - if (empty($donotredirect)) // This is set when include is done by bulk action "Bill Orders" - { + if (empty($donotredirect)) { // This is set when include is done by bulk action "Bill Orders" setEventMessages($langs->trans("FileGenerated"), null); $urltoredirect = $_SERVER['REQUEST_URI']; @@ -104,13 +114,11 @@ if ($action == 'builddoc' && $permissiontoadd) } // Delete file in doc form -if ($action == 'remove_file' && $permissiontoadd) -{ +if ($action == 'remove_file' && $permissiontoadd) { if (!empty($upload_dir)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (empty($object->id) || !$object->id > 0) - { + if (empty($object->id) || !$object->id > 0) { // Reload to get all modified line records and be ready for hooks $ret = $object->fetch($id); $ret = $object->fetch_thirdparty(); @@ -120,8 +128,11 @@ if ($action == 'remove_file' && $permissiontoadd) $filetodelete = GETPOST('file', 'alpha'); $file = $upload_dir.'/'.$filetodelete; $ret = dol_delete_file($file, 0, 0, 0, $object); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", $filetodelete), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", $filetodelete), null, 'errors'); + } // Make a redirect to avoid to keep the remove_file into the url that create side effects $urltoredirect = $_SERVER['REQUEST_URI']; diff --git a/htdocs/core/actions_changeselectedfields.inc.php b/htdocs/core/actions_changeselectedfields.inc.php index 4daf53891cf..f0ead24e6b1 100644 --- a/htdocs/core/actions_changeselectedfields.inc.php +++ b/htdocs/core/actions_changeselectedfields.inc.php @@ -28,14 +28,16 @@ // $object must be defined (object is loaded in this file with fetch) // Save selection -if (GETPOST('formfilteraction', 'alphanohtml') == 'listafterchangingselectedfields') -{ +if (GETPOST('formfilteraction', 'alphanohtml') == 'listafterchangingselectedfields') { $tabparam = array(); $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - if (GETPOST("selectedfields")) $tabparam["MAIN_SELECTEDFIELDS_".$varpage] = GETPOST("selectedfields"); - else $tabparam["MAIN_SELECTEDFIELDS_".$varpage] = ''; + if (GETPOST("selectedfields")) { + $tabparam["MAIN_SELECTEDFIELDS_".$varpage] = GETPOST("selectedfields"); + } else { + $tabparam["MAIN_SELECTEDFIELDS_".$varpage] = ''; + } include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; diff --git a/htdocs/core/actions_comments.inc.php b/htdocs/core/actions_comments.inc.php index f590adee197..fc6bf11a115 100644 --- a/htdocs/core/actions_comments.inc.php +++ b/htdocs/core/actions_comments.inc.php @@ -33,19 +33,16 @@ $comment = new Comment($db); * Actions */ -if ($action == 'addcomment') -{ +if ($action == 'addcomment') { $description = GETPOST('comment_description', 'restricthtml'); - if (!empty($description)) - { + if (!empty($description)) { $comment->description = $description; $comment->datec = time(); $comment->fk_element = GETPOST('id', 'int'); $comment->element_type = GETPOST('comment_element_type', 'alpha'); $comment->fk_user_author = $user->id; $comment->entity = $conf->entity; - if ($comment->create($user) > 0) - { + if ($comment->create($user) > 0) { setEventMessages($langs->trans("CommentAdded"), null, 'mesgs'); header('Location: '.$varpage.'?id='.$id.($withproject ? '&withproject=1' : '')); exit; @@ -55,13 +52,10 @@ if ($action == 'addcomment') } } } -if ($action === 'updatecomment') -{ - if ($comment->fetch($idcomment) >= 0) - { +if ($action === 'updatecomment') { + if ($comment->fetch($idcomment) >= 0) { $comment->description = GETPOST('comment_description', 'restricthtml'); - if ($comment->update($user) > 0) - { + if ($comment->update($user) > 0) { setEventMessages($langs->trans("CommentAdded"), null, 'mesgs'); header('Location: '.$varpage.'?id='.$id.($withproject ? '&withproject=1#comment' : '')); exit; @@ -71,12 +65,9 @@ if ($action === 'updatecomment') } } } -if ($action == 'deletecomment') -{ - if ($comment->fetch($idcomment) >= 0) - { - if ($comment->delete($user) > 0) - { +if ($action == 'deletecomment') { + if ($comment->fetch($idcomment) >= 0) { + if ($comment->delete($user) > 0) { setEventMessages($langs->trans("CommentDeleted"), null, 'mesgs'); header('Location: '.$varpage.'?id='.$id.($withproject ? '&withproject=1' : '')); exit; diff --git a/htdocs/core/actions_dellink.inc.php b/htdocs/core/actions_dellink.inc.php index 2dd2588ca48..a7ac035506f 100644 --- a/htdocs/core/actions_dellink.inc.php +++ b/htdocs/core/actions_dellink.inc.php @@ -30,16 +30,16 @@ $dellinkid = GETPOST('dellinkid', 'int'); $addlinkid = GETPOST('idtolinkto', 'int'); // Link invoice to order -if ($action == 'addlink' && !empty($permissiondellink) && !GETPOST('cancel', 'alpha') && $id > 0 && $addlinkid > 0) -{ +if ($action == 'addlink' && !empty($permissiondellink) && !GETPOST('cancel', 'alpha') && $id > 0 && $addlinkid > 0) { $object->fetch($id); $object->fetch_thirdparty(); $result = $object->add_object_linked(GETPOST('addlink', 'alpha'), $addlinkid); } // Delete link -if ($action == 'dellink' && !empty($permissiondellink) && !GETPOST('cancel', 'alpha') && $dellinkid > 0) -{ +if ($action == 'dellink' && !empty($permissiondellink) && !GETPOST('cancel', 'alpha') && $dellinkid > 0) { $result = $object->deleteObjectLinked(0, '', 0, '', $dellinkid); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } diff --git a/htdocs/core/actions_extrafields.inc.php b/htdocs/core/actions_extrafields.inc.php index 7ba4d7d64b9..b03c2c3d192 100644 --- a/htdocs/core/actions_extrafields.inc.php +++ b/htdocs/core/actions_extrafields.inc.php @@ -31,91 +31,85 @@ $extrasize = GETPOST('size', 'intcomma'); $type = GETPOST('type', 'alpha'); $param = GETPOST('param', 'alpha'); -if ($type == 'double' && strpos($extrasize, ',') === false) $extrasize = '24,8'; -if ($type == 'date') $extrasize = ''; -if ($type == 'datetime') $extrasize = ''; -if ($type == 'select') $extrasize = ''; +if ($type == 'double' && strpos($extrasize, ',') === false) { + $extrasize = '24,8'; +} +if ($type == 'date') { + $extrasize = ''; +} +if ($type == 'datetime') { + $extrasize = ''; +} +if ($type == 'select') { + $extrasize = ''; +} // Add attribute -if ($action == 'add') -{ - if (GETPOST("button") != $langs->trans("Cancel")) - { +if ($action == 'add') { + if (GETPOST("button") != $langs->trans("Cancel")) { // Check values - if (!$type) - { + if (!$type) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")); $action = 'create'; } - if ($type == 'varchar' && $extrasize <= 0) - { + if ($type == 'varchar' && $extrasize <= 0) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Size")); $action = 'edit'; } - if ($type == 'varchar' && $extrasize > $maxsizestring) - { + if ($type == 'varchar' && $extrasize > $maxsizestring) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorSizeTooLongForVarcharType", $maxsizestring); $action = 'create'; } - if ($type == 'int' && $extrasize > $maxsizeint) - { + if ($type == 'int' && $extrasize > $maxsizeint) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorSizeTooLongForIntType", $maxsizeint); $action = 'create'; } - if ($type == 'select' && !$param) - { + if ($type == 'select' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForSelectType"); $action = 'create'; } - if ($type == 'sellist' && !$param) - { + if ($type == 'sellist' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForSelectListType"); $action = 'create'; } - if ($type == 'checkbox' && !$param) - { + if ($type == 'checkbox' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForCheckBoxType"); $action = 'create'; } - if ($type == 'link' && !$param) - { + if ($type == 'link' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForLinkType"); $action = 'create'; } - if ($type == 'radio' && !$param) - { + if ($type == 'radio' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForRadioType"); $action = 'create'; } - if ((($type == 'radio') || ($type == 'checkbox')) && $param) - { + if ((($type == 'radio') || ($type == 'checkbox')) && $param) { // Construct array for parameter (value of select list) $parameters = $param; $parameters_array = explode("\r\n", $parameters); - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { if (!empty($param_ligne)) { - if (preg_match_all('/,/', $param_ligne, $matches)) - { + if (preg_match_all('/,/', $param_ligne, $matches)) { if (count($matches[0]) > 1) { $error++; $langs->load("errors"); @@ -160,14 +154,12 @@ if ($action == 'add') $parameters_array = explode("\r\n", $parameters); //In sellist we have only one line and it can have come to do SQL expression if ($type == 'sellist' || $type == 'chkbxlst') { - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { $params['options'] = array($parameters=>null); } } else { // Else it's separated key/value and coma list - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { list($key, $value) = explode(',', $param_ligne); $params['options'][$key] = $value; } @@ -175,7 +167,9 @@ if ($action == 'add') // Visibility: -1=not visible by default in list, 1=visible, 0=hidden $visibility = GETPOST('list', 'alpha'); - if ($type == 'separate') $visibility = 3; + if ($type == 'separate') { + $visibility = 3; + } $result = $extrafields->addExtraField( GETPOST('attrname', 'aZ09'), @@ -199,8 +193,7 @@ if ($action == 'add') (GETPOST('totalizable', 'alpha') ? 1 : 0), GETPOST('printable', 'alpha') ); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans('SetupSaved'), null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"]); exit; @@ -223,77 +216,64 @@ if ($action == 'add') } // Rename field -if ($action == 'update') -{ - if (GETPOST("button") != $langs->trans("Cancel")) - { +if ($action == 'update') { + if (GETPOST("button") != $langs->trans("Cancel")) { // Check values - if (!$type) - { + if (!$type) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Type")); $action = 'edit'; } - if ($type == 'varchar' && $extrasize <= 0) - { + if ($type == 'varchar' && $extrasize <= 0) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Size")); $action = 'edit'; } - if ($type == 'varchar' && $extrasize > $maxsizestring) - { + if ($type == 'varchar' && $extrasize > $maxsizestring) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorSizeTooLongForVarcharType", $maxsizestring); $action = 'edit'; } - if ($type == 'int' && $extrasize > $maxsizeint) - { + if ($type == 'int' && $extrasize > $maxsizeint) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorSizeTooLongForIntType", $maxsizeint); $action = 'edit'; } - if ($type == 'select' && !$param) - { + if ($type == 'select' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForSelectType"); $action = 'edit'; } - if ($type == 'sellist' && !$param) - { + if ($type == 'sellist' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForSelectListType"); $action = 'edit'; } - if ($type == 'checkbox' && !$param) - { + if ($type == 'checkbox' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForCheckBoxType"); $action = 'edit'; } - if ($type == 'radio' && !$param) - { + if ($type == 'radio' && !$param) { $error++; $langs->load("errors"); $mesg[] = $langs->trans("ErrorNoValueForRadioType"); $action = 'edit'; } - if ((($type == 'radio') || ($type == 'checkbox')) && $param) - { + if ((($type == 'radio') || ($type == 'checkbox')) && $param) { // Construct array for parameter (value of select list) $parameters = $param; $parameters_array = explode("\r\n", $parameters); - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { if (!empty($param_ligne)) { - if (preg_match_all('/,/', $param_ligne, $matches)) - { + if (preg_match_all('/,/', $param_ligne, $matches)) { if (count($matches[0]) > 1) { $error++; $langs->load("errors"); @@ -329,24 +309,20 @@ if ($action == 'update') } } - if (!$error) - { - if (GETPOSTISSET("attrname") && preg_match("/^\w[a-zA-Z0-9-_]*$/", GETPOST('attrname', 'aZ09')) && !is_numeric(GETPOST('attrname', 'aZ09'))) - { + if (!$error) { + if (GETPOSTISSET("attrname") && preg_match("/^\w[a-zA-Z0-9-_]*$/", GETPOST('attrname', 'aZ09')) && !is_numeric(GETPOST('attrname', 'aZ09'))) { $pos = GETPOST('pos', 'int'); // Construct array for parameter (value of select list) $parameters = $param; $parameters_array = explode("\r\n", $parameters); //In sellist we have only one line and it can have come to do SQL expression if ($type == 'sellist' || $type == 'chkbxlst') { - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { $params['options'] = array($parameters=>null); } } else { //Esle it's separated key/value and coma list - foreach ($parameters_array as $param_ligne) - { + foreach ($parameters_array as $param_ligne) { list($key, $value) = explode(',', $param_ligne); $params['options'][$key] = $value; } @@ -354,7 +330,9 @@ if ($action == 'update') // Visibility: -1=not visible by default in list, 1=visible, 0=hidden $visibility = GETPOST('list', 'alpha'); - if ($type == 'separate') $visibility = 3; + if ($type == 'separate') { + $visibility = 3; + } // Example: is_object($object) ? ($object->id < 10 ? round($object->id / 2, 2) : (2 * $user->id) * (int) substr($mysoc->zip, 1, 2)) : 'objnotdefined' $computedvalue = GETPOST('computed_value', 'nohtml'); @@ -409,7 +387,9 @@ if ($action == 'delete') { if ($result >= 0) { header("Location: ".$_SERVER["PHP_SELF"]); exit; - } else $mesg = $extrafields->error; + } else { + $mesg = $extrafields->error; + } } else { $error++; $langs->load("errors"); diff --git a/htdocs/core/actions_fetchobject.inc.php b/htdocs/core/actions_fetchobject.inc.php index c881b335f18..3ca797a9bb3 100644 --- a/htdocs/core/actions_fetchobject.inc.php +++ b/htdocs/core/actions_fetchobject.inc.php @@ -28,20 +28,15 @@ // $cancel must be defined // $id or $ref must be defined (object is loaded in this file with fetch) -if (($id > 0 || (!empty($ref) && !in_array($action, array('create', 'createtask', 'add')))) && (empty($cancel) || $id > 0)) -{ - if (($id > 0 && is_numeric($id)) || !empty($ref)) // To discard case when id is list of ids like '1,2,3...' - { +if (($id > 0 || (!empty($ref) && !in_array($action, array('create', 'createtask', 'add')))) && (empty($cancel) || $id > 0)) { + if (($id > 0 && is_numeric($id)) || !empty($ref)) { // To discard case when id is list of ids like '1,2,3...' $ret = $object->fetch($id, $ref); - if ($ret > 0) - { + if ($ret > 0) { $object->fetch_thirdparty(); $id = $object->id; } else { - if (empty($object->error) && !count($object->errors)) - { - if ($ret < 0) // if $ret == 0, it means not found. - { + if (empty($object->error) && !count($object->errors)) { + if ($ret < 0) { // if $ret == 0, it means not found. setEventMessages('Fetch on object (type '.get_class($object).') return an error without filling $object->error nor $object->errors', null, 'errors'); } } else { diff --git a/htdocs/core/actions_lineupdown.inc.php b/htdocs/core/actions_lineupdown.inc.php index e5507eeafc0..5aee952292b 100644 --- a/htdocs/core/actions_lineupdown.inc.php +++ b/htdocs/core/actions_lineupdown.inc.php @@ -28,15 +28,18 @@ // $langs must be defined // $hidedetails, $hidedesc, $hideref must de defined -if ($action == 'up' && $permissiontoedit) -{ +if ($action == 'up' && $permissiontoedit) { $object->line_up(GETPOST('rowid')); // Define output language $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 ($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); @@ -50,15 +53,18 @@ if ($action == 'up' && $permissiontoedit) exit(); } -if ($action == 'down' && $permissiontoedit) -{ +if ($action == 'down' && $permissiontoedit) { $object->line_down(GETPOST('rowid')); // Define output language $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 ($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); diff --git a/htdocs/core/actions_linkedfiles.inc.php b/htdocs/core/actions_linkedfiles.inc.php index b0671bbf555..af60583118d 100644 --- a/htdocs/core/actions_linkedfiles.inc.php +++ b/htdocs/core/actions_linkedfiles.inc.php @@ -27,17 +27,16 @@ // Submit file/link -if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC)) -{ - if (!empty($_FILES)) - { - if (is_array($_FILES['userfile']['tmp_name'])) $userfiles = $_FILES['userfile']['tmp_name']; - else $userfiles = array($_FILES['userfile']['tmp_name']); +if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC)) { + if (!empty($_FILES)) { + if (is_array($_FILES['userfile']['tmp_name'])) { + $userfiles = $_FILES['userfile']['tmp_name']; + } else { + $userfiles = array($_FILES['userfile']['tmp_name']); + } - foreach ($userfiles as $key => $userfile) - { - if (empty($_FILES['userfile']['tmp_name'][$key])) - { + foreach ($userfiles as $key => $userfile) { + if (empty($_FILES['userfile']['tmp_name'][$key])) { $error++; if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) { setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors'); @@ -47,27 +46,24 @@ if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC)) } } - if (!$error) - { + if (!$error) { // Define if we have to generate thumbs or not $generatethumbs = 1; - if (GETPOST('section_dir', 'alpha')) $generatethumbs = 0; + if (GETPOST('section_dir', 'alpha')) { + $generatethumbs = 0; + } $allowoverwrite = (GETPOST('overwritefile', 'int') ? 1 : 0); - if (!empty($upload_dirold) && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) - { + if (!empty($upload_dirold) && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { $result = dol_add_file_process($upload_dirold, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object); - } elseif (!empty($upload_dir)) - { + } elseif (!empty($upload_dir)) { $result = dol_add_file_process($upload_dir, $allowoverwrite, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs, $object); } } } -} elseif (GETPOST('linkit', 'restricthtml') && !empty($conf->global->MAIN_UPLOAD_DOC)) -{ +} elseif (GETPOST('linkit', 'restricthtml') && !empty($conf->global->MAIN_UPLOAD_DOC)) { $link = GETPOST('link', 'alpha'); - if ($link) - { + if ($link) { if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://') { $link = 'http://'.$link; } @@ -77,17 +73,18 @@ if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC)) // Delete file/link -if ($action == 'confirm_deletefile' && $confirm == 'yes') -{ +if ($action == 'confirm_deletefile' && $confirm == 'yes') { $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP). if (GETPOST('section', 'alpha')) { // For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile; } else // For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile. { - $urlfile = basename($urlfile); - $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile; - if (!empty($upload_dirold)) $fileold = $upload_dirold."/".$urlfile; + $urlfile = basename($urlfile); + $file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile; + if (!empty($upload_dirold)) { + $fileold = $upload_dirold."/".$urlfile; + } } $linkid = GETPOST('linkid', 'int'); @@ -97,21 +94,20 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image) $ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null)); - if (!empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path + if (!empty($fileold)) { + dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path + } // If it exists, remove thumb. $regs = array(); - if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs)) - { + if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs)) { $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]); - if (file_exists(dol_osencode($dirthumb.$photo_vignette))) - { + if (file_exists(dol_osencode($dirthumb.$photo_vignette))) { dol_delete_file($dirthumb.$photo_vignette); } $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]); - if (file_exists(dol_osencode($dirthumb.$photo_vignette))) - { + if (file_exists(dol_osencode($dirthumb.$photo_vignette))) { dol_delete_file($dirthumb.$photo_vignette); } } @@ -149,33 +145,27 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') exit; } } -} elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha')) -{ +} elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha')) { require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; $langs->load('link'); $link = new Link($db); $f = $link->fetch(GETPOST('linkid', 'int')); - if ($f) - { + if ($f) { $link->url = GETPOST('link', 'alpha'); - if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') - { + if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://') { $link->url = 'http://'.$link->url; } $link->label = GETPOST('label', 'alphanohtml'); $res = $link->update($user); - if (!$res) - { + if (!$res) { setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs'); } } else { //error fetching } -} elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha')) -{ +} elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha')) { // For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile. - if (!empty($upload_dir)) - { + if (!empty($upload_dir)) { $filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents $filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents @@ -183,24 +173,23 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') // this function is also applied when we upload and when we make try to download file (by the GETPOST(filename, 'alphanohtml') call). $filenameto = dol_string_nohtmltag($filenameto); - if ($filenamefrom != $filenameto) - { + if ($filenamefrom != $filenameto) { // Security: // Disallow file with some extensions. We rename them. // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code. - if (isAFileWithExecutableContent($filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) - { + if (isAFileWithExecutableContent($filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED)) { // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too. $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity]; - if (!preg_match('/\/$/', $publicmediasdirwithslash)) $publicmediasdirwithslash .= '/'; + if (!preg_match('/\/$/', $publicmediasdirwithslash)) { + $publicmediasdirwithslash .= '/'; + } if (strpos($upload_dir, $publicmediasdirwithslash) !== 0) { // We never add .noexe on files into media directory $filenameto .= '.noexe'; } } - if ($filenamefrom && $filenameto) - { + if ($filenamefrom && $filenameto) { $srcpath = $upload_dir.'/'.$filenamefrom; $destpath = $upload_dir.'/'.$filenameto; @@ -208,26 +197,24 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir); $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object); - if (empty($reshook)) - { + if (empty($reshook)) { if (preg_match('/^\./', $filenameto)) { $langs->load("errors"); // lang must be loaded because we can't rely on loading during output, we need var substitution to be done now. setEventMessages($langs->trans("ErrorFilenameCantStartWithDot", $filenameto), null, 'errors'); } elseif (!file_exists($destpath)) { $result = dol_move($srcpath, $destpath); - if ($result) - { + if ($result) { // Define if we have to generate thumbs or not $generatethumbs = 1; // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here) // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case) // but when we rename from a tab "Documents", we must regenerate thumbs - if (GETPOST('modulepart') == 'medias') $generatethumbs = 0; + if (GETPOST('modulepart') == 'medias') { + $generatethumbs = 0; + } - if ($generatethumbs) - { - if ($object->id) - { + if ($generatethumbs) { + if ($object->id) { $object->addThumbs($destpath); } @@ -250,19 +237,15 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') } // Update properties in ECM table - if (GETPOST('ecmfileid', 'int') > 0) - { + if (GETPOST('ecmfileid', 'int') > 0) { $shareenabled = GETPOST('shareenabled', 'alpha'); include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile = new EcmFiles($db); $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int')); - if ($result > 0) - { - if ($shareenabled) - { - if (empty($ecmfile->share)) - { + if ($result > 0) { + if ($shareenabled) { + if (empty($ecmfile->share)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php'; $ecmfile->share = getRandomPassword(true); } @@ -270,8 +253,7 @@ if ($action == 'confirm_deletefile' && $confirm == 'yes') $ecmfile->share = ''; } $result = $ecmfile->update($user); - if ($result < 0) - { + if ($result < 0) { setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings'); } } diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 892cb8ae4e0..057443d09b4 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -37,37 +37,38 @@ // Protection -if (empty($objectclass) || empty($uploaddir)) -{ +if (empty($objectclass) || empty($uploaddir)) { dol_print_error(null, 'include of actions_massactions.inc.php is done but var $objectclass or $uploaddir was not defined'); exit; } // For backward compatibility -if (!empty($permtoread) && empty($permissiontoread)) $permissiontoread = $permtoread; -if (!empty($permtocreate) && empty($permissiontoadd)) $permissiontoadd = $permtocreate; -if (!empty($permtodelete) && empty($permissiontodelete)) $permissiontodelete = $permtodelete; +if (!empty($permtoread) && empty($permissiontoread)) { + $permissiontoread = $permtoread; +} +if (!empty($permtocreate) && empty($permissiontoadd)) { + $permissiontoadd = $permtocreate; +} +if (!empty($permtodelete) && empty($permissiontodelete)) { + $permissiontodelete = $permtodelete; +} // Mass actions. Controls on number of lines checked. $maxformassaction = (empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS) ? 1000 : $conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS); -if (!empty($massaction) && is_array($toselect) && count($toselect) < 1) -{ +if (!empty($massaction) && is_array($toselect) && count($toselect) < 1) { $error++; setEventMessages($langs->trans("NoRecordSelected"), null, "warnings"); } -if (!$error && is_array($toselect) && count($toselect) > $maxformassaction) -{ +if (!$error && is_array($toselect) && count($toselect) > $maxformassaction) { setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors'); $error++; } -if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail')) // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form -{ +if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail')) { // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form $massaction = 'presend'; } -if (!$error && $massaction == 'confirm_presend') -{ +if (!$error && $massaction == 'confirm_presend') { $resaction = ''; $nbsent = 0; $nbignored = 0; @@ -82,27 +83,36 @@ if (!$error && $massaction == 'confirm_presend') $attachedfilesThirdpartyObj = array(); $oneemailperrecipient = (GETPOST('oneemailperrecipient') == 'on' ? 1 : 0); - if (!$error) - { + if (!$error) { $thirdparty = new Societe($db); $objecttmp = new $objectclass($db); - if ($objecttmp->element == 'expensereport') $thirdparty = new User($db); - if ($objecttmp->element == 'holiday') $thirdparty = new User($db); + if ($objecttmp->element == 'expensereport') { + $thirdparty = new User($db); + } + if ($objecttmp->element == 'holiday') { + $thirdparty = new User($db); + } - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $listofobjectid[$toselectid] = $toselectid; $thirdpartyid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid); - if ($objecttmp->element == 'societe') $thirdpartyid = $objecttmp->id; - if ($objecttmp->element == 'expensereport') $thirdpartyid = $objecttmp->fk_user_author; - if ($objecttmp->element == 'holiday') $thirdpartyid = $objecttmp->fk_user; - if (empty($thirdpartyid)) $thirdpartyid = 0; + if ($objecttmp->element == 'societe') { + $thirdpartyid = $objecttmp->id; + } + if ($objecttmp->element == 'expensereport') { + $thirdpartyid = $objecttmp->fk_user_author; + } + if ($objecttmp->element == 'holiday') { + $thirdpartyid = $objecttmp->fk_user; + } + if (empty($thirdpartyid)) { + $thirdpartyid = 0; + } if ($objectclass == 'Facture') { $tmparraycontact = array(); @@ -121,41 +131,37 @@ if (!$error && $massaction == 'confirm_presend') } // Check mandatory parameters - if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) - { + if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email)) { $error++; setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings'); $massaction = 'presend'; } $receiver = $_POST['receiver']; - if (!is_array($receiver)) - { - if (empty($receiver) || $receiver == '-1') $receiver = array(); - else $receiver = array($receiver); + if (!is_array($receiver)) { + if (empty($receiver) || $receiver == '-1') { + $receiver = array(); + } else { + $receiver = array($receiver); + } } - if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) // if only one recipient, receiver is mandatory - { - $error++; - setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings'); - $massaction = 'presend'; + if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) { // if only one recipient, receiver is mandatory + $error++; + setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings'); + $massaction = 'presend'; } - if (!GETPOST('subject', 'restricthtml')) - { + if (!GETPOST('subject', 'restricthtml')) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings'); $massaction = 'presend'; } // Loop on each recipient/thirdparty - if (!$error) - { - foreach ($listofobjectthirdparties as $thirdpartyid) - { + if (!$error) { + foreach ($listofobjectthirdparties as $thirdpartyid) { $result = $thirdparty->fetch($thirdpartyid); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db); exit; } @@ -167,21 +173,16 @@ if (!$error && $massaction == 'confirm_presend') // Define $sendto $tmparray = array(); - if (trim($_POST['sendto'])) - { + if (trim($_POST['sendto'])) { // Recipients are provided into free text $tmparray[] = trim($_POST['sendto']); } - if (count($receiver) > 0) - { - foreach ($receiver as $key=>$val) - { + if (count($receiver) > 0) { + foreach ($receiver as $key => $val) { // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party or user - { + if ($val == 'thirdparty') { // Id of third party or user $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } elseif ($val && method_exists($thirdparty, 'contact_get_property')) // Id of contact - { + } elseif ($val && method_exists($thirdparty, 'contact_get_property')) { // Id of contact $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email'); $sendtoid[] = $val; } @@ -191,26 +192,23 @@ if (!$error && $massaction == 'confirm_presend') // Define $sendtocc $receivercc = $_POST['receivercc']; - if (!is_array($receivercc)) - { - if ($receivercc == '-1') $receivercc = array(); - else $receivercc = array($receivercc); + if (!is_array($receivercc)) { + if ($receivercc == '-1') { + $receivercc = array(); + } else { + $receivercc = array($receivercc); + } } $tmparray = array(); - if (trim($_POST['sendtocc'])) - { + if (trim($_POST['sendtocc'])) { $tmparray[] = trim($_POST['sendtocc']); } - if (count($receivercc) > 0) - { - foreach ($receivercc as $key=>$val) - { + if (count($receivercc) > 0) { + foreach ($receivercc as $key => $val) { // Recipient was provided from combo list - if ($val == 'thirdparty') // Id of third party - { + if ($val == 'thirdparty') { // Id of third party $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>'; - } elseif ($val) // Id du contact - { + } elseif ($val) { // Id du contact $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email'); //$sendtoid[] = $val; TODO Add also id of contact in CC ? } @@ -223,25 +221,21 @@ if (!$error && $massaction == 'confirm_presend') $listofqualifiedref = array(); $thirdpartywithoutemail = array(); - foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) - { + foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj) { //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut); - if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT) - { + if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT) { $langs->load("errors"); $nbignored++; $resaction .= '
    '.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'

    '; continue; // Payment done or started or canceled } - if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT) - { + if ($objectclass == 'Commande' && $objectobj->statut == Commande::STATUS_DRAFT) { $langs->load("errors"); $nbignored++; $resaction .= '
    '.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'

    '; continue; } - if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT) - { + if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT) { $langs->load("errors"); $nbignored++; $resaction .= '
    '.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'

    '; @@ -249,23 +243,18 @@ if (!$error && $massaction == 'confirm_presend') } // Test recipient - if (empty($sendto)) // For the case, no recipient were set (multi thirdparties send) - { - if ($objectobj->element == 'societe') - { + if (empty($sendto)) { // For the case, no recipient were set (multi thirdparties send) + if ($objectobj->element == 'societe') { $sendto = $objectobj->email; - } elseif ($objectobj->element == 'expensereport') - { + } elseif ($objectobj->element == 'expensereport') { $fuser = new User($db); $fuser->fetch($objectobj->fk_user_author); $sendto = $fuser->email; - } elseif ($objectobj->element == 'holiday') - { + } elseif ($objectobj->element == 'holiday') { $fuser = new User($db); $fuser->fetch($objectobj->fk_user); $sendto = $fuser->email; - } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) - { + } elseif ($objectobj->element == 'facture' && !empty($listofobjectcontacts[$objectid])) { $emails_to_sends = array(); $objectobj->fetch_thirdparty(); $contactidtosend = array(); @@ -284,25 +273,22 @@ if (!$error && $massaction == 'confirm_presend') } } - if (empty($sendto)) - { + if (empty($sendto)) { if ($objectobj->element == 'societe') { $objectobj->thirdparty = $objectobj; // Hack so following code is comaptible when objectobj is a thirdparty } - //print "No recipient for thirdparty ".$objectobj->thirdparty->name; - $nbignored++; - if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) - { + //print "No recipient for thirdparty ".$objectobj->thirdparty->name; + $nbignored++; + if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id])) { $resaction .= '
    '.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'

    '; } dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING); $thirdpartywithoutemail[$objectobj->thirdparty->id] = 1; - continue; + continue; } - if ($_POST['addmaindocfile']) - { + if ($_POST['addmaindocfile']) { // TODO Use future field $objectobj->fullpathdoc to know where is stored default file // TODO If not defined, use $objectobj->model_pdf (or defaut invoice config) to know what is template to use to regenerate doc. $filename = dol_sanitizeFileName($objectobj->ref).'.pdf'; @@ -313,16 +299,14 @@ if (!$error && $massaction == 'confirm_presend') $file = $filedir.'/'.$filename; // For supplier invoices, we use the file provided by supplier, not the one we generate - if ($objectobj->element == 'invoice_supplier') - { + if ($objectobj->element == 'invoice_supplier') { $fileparams = dol_most_recent_file($uploaddir.'/'.get_exdir($objectobj->id, 2, 0, 0, $objectobj, $objectobj->element).$objectobj->ref, preg_quote($objectobj->ref, '/').'([^\-])+'); $file = $fileparams['fullname']; } $mime = dol_mimetype($file); - if (dol_is_file($file)) - { + if (dol_is_file($file)) { // Create form object $attachedfilesThirdpartyObj[$thirdpartyid][$objectid] = array( 'paths'=>array($file), @@ -347,8 +331,7 @@ if (!$error && $massaction == 'confirm_presend') } // Send email if there is at least one qualified object for current thirdparty - if (count($listofqualifiedobj) > 0) - { + if (count($listofqualifiedobj) > 0) { $langs->load("commercial"); $reg = array(); @@ -367,8 +350,7 @@ if (!$error && $massaction == 'confirm_presend') $sql = 'SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1]; $resql = $db->query($sql); $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $from = $obj->label.' <'.$obj->email.'>'; } } else { @@ -380,22 +362,34 @@ if (!$error && $massaction == 'confirm_presend') $message = GETPOST('message', 'restricthtml'); $sendtobcc = GETPOST('sendtoccc'); - if ($objectclass == 'Propal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); - if ($objectclass == 'Commande') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)); - if ($objectclass == 'Facture') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)); - if ($objectclass == 'Supplier_Proposal') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)); - if ($objectclass == 'CommandeFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)); - if ($objectclass == 'FactureFournisseur') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)); - if ($objectclass == 'Project') $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO)); + if ($objectclass == 'Propal') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO)); + } + if ($objectclass == 'Commande') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO)); + } + if ($objectclass == 'Facture') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO)); + } + if ($objectclass == 'Supplier_Proposal') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO)); + } + if ($objectclass == 'CommandeFournisseur') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO)); + } + if ($objectclass == 'FactureFournisseur') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO)); + } + if ($objectclass == 'Project') { + $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO)); + } // $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet) // $looparray will be an array with number of email to send for the current thirdparty (so 1 or n if n object for same thirdparty) $looparray = array(); - if (!$oneemailperrecipient) - { + if (!$oneemailperrecipient) { $looparray = $listofqualifiedobj; - foreach ($looparray as $key => $objecttmp) - { + foreach ($looparray as $key => $objecttmp) { $looparray[$key]->thirdparty = $thirdparty; // Force thirdparty on object } } else { @@ -406,11 +400,9 @@ if (!$error && $massaction == 'confirm_presend') //var_dump($looparray);exit; dol_syslog("We have set an array of ".count($looparray)." emails to send. oneemailperrecipient=".$oneemailperrecipient); //var_dump($oneemailperrecipient); var_dump($listofqualifiedobj); var_dump($listofqualifiedref); - foreach ($looparray as $objectid => $objecttmp) // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per object - { + foreach ($looparray as $objectid => $objecttmp) { // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per object // Make substitution in email content - if (!empty($conf->projet->enabled) && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) - { + if (!empty($conf->projet->enabled) && method_exists($objecttmp, 'fetch_projet') && is_null($objecttmp->project)) { $objecttmp->fetch_projet(); } $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp); @@ -434,12 +426,10 @@ if (!$error && $massaction == 'confirm_presend') $messagereplaced = make_substitutions($message, $substitutionarray); $attachedfiles = array('paths'=>array(), 'names'=>array(), 'mimes'=>array()); - if ($oneemailperrecipient) - { + if ($oneemailperrecipient) { // if "one email per recipient" is check we must collate $attachedfiles by thirdparty - if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) - { - foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) { + if (is_array($attachedfilesThirdpartyObj[$thirdparty->id]) && count($attachedfilesThirdpartyObj[$thirdparty->id])) { + foreach ($attachedfilesThirdpartyObj[$thirdparty->id] as $keyObjId => $objAttachedFiles) { // Create form object $attachedfiles = array( 'paths'=>array_merge($attachedfiles['paths'], $objAttachedFiles['paths']), @@ -459,20 +449,37 @@ if (!$error && $massaction == 'confirm_presend') $mimetype = $attachedfiles['mimes']; // Define the trackid when emails sent from the mass action - if ($oneemailperrecipient) - { + if ($oneemailperrecipient) { $trackid = 'thi'.$thirdparty->id; - if ($objecttmp->element == 'expensereport') $trackid = 'use'.$thirdparty->id; - if ($objecttmp->element == 'holiday') $trackid = 'use'.$thirdparty->id; + if ($objecttmp->element == 'expensereport') { + $trackid = 'use'.$thirdparty->id; + } + if ($objecttmp->element == 'holiday') { + $trackid = 'use'.$thirdparty->id; + } } else { $trackid = strtolower(get_class($objecttmp)); - if (get_class($objecttmp) == 'Contrat') $trackid = 'con'; - if (get_class($objecttmp) == 'Propal') $trackid = 'pro'; - if (get_class($objecttmp) == 'Commande') $trackid = 'ord'; - if (get_class($objecttmp) == 'Facture') $trackid = 'inv'; - if (get_class($objecttmp) == 'Supplier_Proposal') $trackid = 'spr'; - if (get_class($objecttmp) == 'CommandeFournisseur') $trackid = 'sor'; - if (get_class($objecttmp) == 'FactureFournisseur') $trackid = 'sin'; + if (get_class($objecttmp) == 'Contrat') { + $trackid = 'con'; + } + if (get_class($objecttmp) == 'Propal') { + $trackid = 'pro'; + } + if (get_class($objecttmp) == 'Commande') { + $trackid = 'ord'; + } + if (get_class($objecttmp) == 'Facture') { + $trackid = 'inv'; + } + if (get_class($objecttmp) == 'Supplier_Proposal') { + $trackid = 'spr'; + } + if (get_class($objecttmp) == 'CommandeFournisseur') { + $trackid = 'sor'; + } + if (get_class($objecttmp) == 'FactureFournisseur') { + $trackid = 'sin'; + } $trackid .= $objecttmp->id; } @@ -480,40 +487,42 @@ if (!$error && $massaction == 'confirm_presend') //var_dump($trackid);exit; //var_dump($subjectreplaced); - if (empty($sendcontext)) $sendcontext = 'standard'; + if (empty($sendcontext)) { + $sendcontext = 'standard'; + } // Send mail (substitutionarray must be done just before this) require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $mailfile = new CMailFile($subjectreplaced, $sendto, $from, $messagereplaced, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext); - if ($mailfile->error) - { + if ($mailfile->error) { $resaction .= '
    '.$mailfile->error.'
    '; } else { $result = $mailfile->sendfile(); - if ($result) - { + if ($result) { $resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)).'
    '; // Must not contain " $error = 0; // Insert logs into agenda - foreach ($listofqualifiedobj as $objid2 => $objectobj2) - { - if ((!$oneemailperrecipient) && $objid2 != $objectid) continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level + foreach ($listofqualifiedobj as $objid2 => $objectobj2) { + if ((!$oneemailperrecipient) && $objid2 != $objectid) { + continue; // We discard this pass to avoid duplicate with other pass in looparray at higher level + } dol_syslog("Try to insert email event into agenda for objid=".$objid2." => objectobj=".get_class($objectobj2)); /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP'; - if ($objectclass == 'Commande') $actiontypecode='AC_COM'; - if ($objectclass == 'Facture') $actiontypecode='AC_FAC'; - if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO'; - if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD'; - if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/ + if ($objectclass == 'Commande') $actiontypecode='AC_COM'; + if ($objectclass == 'Facture') $actiontypecode='AC_FAC'; + if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO'; + if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD'; + if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/ $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto; - if ($message) - { - if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc); + if ($message) { + if ($sendtocc) { + $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc); + } $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subjectreplaced); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":"); $actionmsg = dol_concatdesc($actionmsg, $messagereplaced); @@ -528,24 +537,40 @@ if (!$error && $massaction == 'confirm_presend') $objectobj2->elementtype = $objectobj2->element; $triggername = strtoupper(get_class($objectobj2)).'_SENTBYMAIL'; - if ($triggername == 'SOCIETE_SENTBYMAIL') $triggername = 'COMPANY_SENTBYMAIL'; - if ($triggername == 'CONTRAT_SENTBYMAIL') $triggername = 'CONTRACT_SENTBYMAIL'; - if ($triggername == 'COMMANDE_SENTBYMAIL') $triggername = 'ORDER_SENTBYMAIL'; - if ($triggername == 'FACTURE_SENTBYMAIL') $triggername = 'BILL_SENTBYMAIL'; - if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYMAIL'; - if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL'; - if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYMAIL'; - if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL'; + if ($triggername == 'SOCIETE_SENTBYMAIL') { + $triggername = 'COMPANY_SENTBYMAIL'; + } + if ($triggername == 'CONTRAT_SENTBYMAIL') { + $triggername = 'CONTRACT_SENTBYMAIL'; + } + if ($triggername == 'COMMANDE_SENTBYMAIL') { + $triggername = 'ORDER_SENTBYMAIL'; + } + if ($triggername == 'FACTURE_SENTBYMAIL') { + $triggername = 'BILL_SENTBYMAIL'; + } + if ($triggername == 'EXPEDITION_SENTBYMAIL') { + $triggername = 'SHIPPING_SENTBYMAIL'; + } + if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') { + $triggername = 'ORDER_SUPPLIER_SENTBYMAIL'; + } + if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') { + $triggername = 'BILL_SUPPLIER_SENTBYMAIL'; + } + if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') { + $triggername = 'PROPOSAL_SUPPLIER_SENTBYMAIL'; + } - if (!empty($triggername)) - { + if (!empty($triggername)) { // Call trigger $result = $objectobj2->call_trigger($triggername, $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if ($error) - { + if ($error) { setEventMessages($db->lasterror(), $errors, 'errors'); dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR); } @@ -555,8 +580,7 @@ if (!$error && $massaction == 'confirm_presend') } } else { $langs->load("other"); - if ($mailfile->error) - { + if ($mailfile->error) { $resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto); $resaction .= '
    '.$mailfile->error.'
    '; } else { @@ -574,8 +598,7 @@ if (!$error && $massaction == 'confirm_presend') $resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n
    "; $resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n
    "; - if ($nbsent) - { + if ($nbsent) { $action = ''; // Do not show form post if there was at least one successfull sent //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs'); setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs'); @@ -591,8 +614,7 @@ if (!$error && $massaction == 'confirm_presend') } // TODO Move this action into commande/list.php if called only by this page. -if ($massaction == 'confirm_createbills') // Create bills from orders. -{ +if ($massaction == 'confirm_createbills') { // Create bills from orders. $orders = GETPOST('toselect', 'array'); $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); $validate_invoices = GETPOST('validate_invoices', 'int'); @@ -606,10 +628,11 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $db->begin(); - foreach ($orders as $id_order) - { + foreach ($orders as $id_order) { $cmd = new Commande($db); - if ($cmd->fetch($id_order) <= 0) continue; + if ($cmd->fetch($id_order) <= 0) { + continue; + } $objecttmp = new Facture($db); if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) { @@ -624,11 +647,12 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $objecttmp->mode_reglement_id = $cmd->mode_reglement_id; $objecttmp->fk_project = $cmd->fk_project; $objecttmp->multicurrency_code = $cmd->multicurrency_code; - if (empty($createbills_onebythird)) $objecttmp->ref_client = $cmd->ref_client; + if (empty($createbills_onebythird)) { + $objecttmp->ref_client = $cmd->ref_client; + } $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - if (empty($datefacture)) - { + if (empty($datefacture)) { $datefacture = dol_now(); } @@ -647,8 +671,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. } } - if ($objecttmp->id > 0) - { + if ($objecttmp->id > 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; $sql .= "fk_source"; $sql .= ", sourcetype"; @@ -661,16 +684,13 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $sql .= ", '".$db->escape($objecttmp->element)."'"; $sql .= ")"; - if (!$db->query($sql)) - { + if (!$db->query($sql)) { $error++; } - if (!$error) - { + if (!$error) { $lines = $cmd->lines; - if (empty($lines) && method_exists($cmd, 'fetch_lines')) - { + if (empty($lines) && method_exists($cmd, 'fetch_lines')) { $cmd->fetch_lines(); $lines = $cmd->lines; } @@ -678,17 +698,14 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $desc = ($lines[$i]->desc ? $lines[$i]->desc : ''); // If we build one invoice for several order, we must put the invoice of order on the line - if (!empty($createbills_onebythird)) - { + if (!empty($createbills_onebythird)) { $desc = dol_concatdesc($desc, $langs->trans("Order").' '.$cmd->ref.' - '.dol_print_date($cmd->date, 'day')); } - if ($lines[$i]->subprice < 0) - { + if ($lines[$i]->subprice < 0) { // Negative line, we create a discount line $discount = new DiscountAbsolute($db); $discount->fk_soc = $objecttmp->socid; @@ -699,8 +716,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $discount->fk_user = $user->id; $discount->description = $desc; $discountid = $discount->create($user); - if ($discountid > 0) - { + if ($discountid > 0) { $result = $objecttmp->insert_discount($discountid); //$result=$discount->link_to_invoice($lineid,$id); } else { @@ -713,17 +729,28 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); // Date start $date_start = false; - if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start; + if ($lines[$i]->date_debut_prevue) { + $date_start = $lines[$i]->date_debut_prevue; + } + if ($lines[$i]->date_debut_reel) { + $date_start = $lines[$i]->date_debut_reel; + } + if ($lines[$i]->date_start) { + $date_start = $lines[$i]->date_start; + } //Date end $date_end = false; - if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end; + if ($lines[$i]->date_fin_prevue) { + $date_end = $lines[$i]->date_fin_prevue; + } + if ($lines[$i]->date_fin_reel) { + $date_end = $lines[$i]->date_fin_reel; + } + if ($lines[$i]->date_end) { + $date_end = $lines[$i]->date_end; + } // Reset fk_parent_line for no child products and special product - if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) - { + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { $fk_parent_line = 0; } @@ -762,9 +789,8 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. 100, 0, $lines[$i]->fk_unit - ); - if ($result > 0) - { + ); + if ($result > 0) { $lineid = $result; } else { $lineid = 0; @@ -772,8 +798,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. break; } // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { + if ($result > 0 && $lines[$i]->product_type == 9) { $fk_parent_line = $result; } } @@ -783,23 +808,23 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. //$cmd->classifyBilled($user); // Disabled. This behavior must be set or not using the workflow module. - if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp; - else $TFact[$objecttmp->id] = $objecttmp; + if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) { + $TFactThird[$cmd->socid] = $objecttmp; + } else { + $TFact[$objecttmp->id] = $objecttmp; + } } // Build doc with all invoices $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird; $toselect = array(); - if (!$error && $validate_invoices) - { + if (!$error && $validate_invoices) { $massaction = $action = 'builddoc'; - foreach ($TAllFact as &$objecttmp) - { + foreach ($TAllFact as &$objecttmp) { $result = $objecttmp->validate($user); - if ($result <= 0) - { + if ($result <= 0) { $error++; setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); break; @@ -815,7 +840,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. // Call action to build doc $savobject = $object; - $object = $objecttmp; + $object = $objecttmp; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; $object = $savobject; } @@ -823,8 +848,7 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. $massaction = $action = 'confirm_createbills'; } - if (!$error) - { + if (!$error) { $db->commit(); if ($nb_bills_created == 1) { @@ -837,29 +861,75 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. // Make a redirect to avoid to bill twice if we make a refresh or back $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sall) $param .= '&sall='.urlencode($sall); - if ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($search_orderday) $param .= '&search_orderday='.urlencode($search_orderday); - if ($search_ordermonth) $param .= '&search_ordermonth='.urlencode($search_ordermonth); - if ($search_orderyear) $param .= '&search_orderyear='.urlencode($search_orderyear); - if ($search_deliveryday) $param .= '&search_deliveryday='.urlencode($search_deliveryday); - if ($search_deliverymonth) $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); - if ($search_deliveryyear) $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_company) $param .= '&search_company='.urlencode($search_company); - if ($search_ref_customer) $param .= '&search_ref_customer='.urlencode($search_ref_customer); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht); - if ($search_total_vat != '') $param .= '&search_total_vat='.urlencode($search_total_vat); - if ($search_total_ttc != '') $param .= '&search_total_ttc='.urlencode($search_total_ttc); - if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($billed != '') $param .= '&billed='.urlencode($billed); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($sall) { + $param .= '&sall='.urlencode($sall); + } + if ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); + } + if ($search_orderday) { + $param .= '&search_orderday='.urlencode($search_orderday); + } + if ($search_ordermonth) { + $param .= '&search_ordermonth='.urlencode($search_ordermonth); + } + if ($search_orderyear) { + $param .= '&search_orderyear='.urlencode($search_orderyear); + } + if ($search_deliveryday) { + $param .= '&search_deliveryday='.urlencode($search_deliveryday); + } + if ($search_deliverymonth) { + $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); + } + if ($search_deliveryyear) { + $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } + if ($search_ref_customer) { + $param .= '&search_ref_customer='.urlencode($search_ref_customer); + } + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_total_ht != '') { + $param .= '&search_total_ht='.urlencode($search_total_ht); + } + if ($search_total_vat != '') { + $param .= '&search_total_vat='.urlencode($search_total_vat); + } + if ($search_total_ttc != '') { + $param .= '&search_total_ttc='.urlencode($search_total_ttc); + } + if ($search_project_ref >= 0) { + $param .= "&search_project_ref=".urlencode($search_project_ref); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($billed != '') { + $param .= '&billed='.urlencode($billed); + } header("Location: ".$_SERVER['PHP_SELF'].'?'.$param); exit; @@ -873,22 +943,20 @@ if ($massaction == 'confirm_createbills') // Create bills from orders. } } -if (!$error && $massaction == 'cancelorders') -{ +if (!$error && $massaction == 'cancelorders') { $db->begin(); $nbok = 0; $orders = GETPOST('toselect', 'array'); - foreach ($orders as $id_order) - { + foreach ($orders as $id_order) { $cmd = new Commande($db); - if ($cmd->fetch($id_order) <= 0) + if ($cmd->fetch($id_order) <= 0) { continue; + } - if ($cmd->statut != Commande::STATUS_VALIDATED) - { + if ($cmd->statut != Commande::STATUS_VALIDATED) { $langs->load('errors'); setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors'); $error++; @@ -898,18 +966,20 @@ if (!$error && $massaction == 'cancelorders') $result = $cmd->cancel(); } - if ($result < 0) - { + if ($result < 0) { setEventMessages($cmd->error, $cmd->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } - if (!$error) - { - if ($nbok > 1) + if (!$error) { + if ($nbok > 1) { setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -917,10 +987,8 @@ if (!$error && $massaction == 'cancelorders') } -if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) -{ - if (empty($diroutputmassaction)) - { +if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('button_search')) { + if (empty($diroutputmassaction)) { dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined'); exit; } @@ -933,12 +1001,10 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto $listofobjectid = array(); $listofobjectthirdparties = array(); $listofobjectref = array(); - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $listofobjectid[$toselectid] = $toselectid; $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid; $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid; @@ -947,19 +1013,20 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto } $arrayofinclusion = array(); - foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$'; - foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files + foreach ($listofobjectref as $tmppdf) { + $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$'; + } + foreach ($listofobjectref as $tmppdf) { + $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files + } $listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true); // build list of files with full path $files = array(); - foreach ($listofobjectref as $basename) - { + foreach ($listofobjectref as $basename) { $basename = dol_sanitizeFileName($basename); - foreach ($listoffiles as $filefound) - { - if (strstr($filefound["name"], $basename)) - { + foreach ($listoffiles as $filefound) { + if (strstr($filefound["name"], $basename)) { $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"]; break; } @@ -969,15 +1036,18 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto // Define output language (Here it is not used because we do only merging existing PDF) $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 = $objecttmp->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $objecttmp->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } - if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) - { + if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT)) { // Create output dir if not exists dol_mkdir($diroutputmassaction); @@ -986,16 +1056,21 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto $filename = preg_replace('/\s/', '_', $filename); // Save merged file - if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) - { - if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); - else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); + if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) { + if ($option == 'late') { + $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); + } else { + $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); + } + } + if ($year) { + $filename .= '_'.$year; + } + if ($month) { + $filename .= '_'.$month; } - if ($year) $filename .= '_'.$year; - if ($month) $filename .= '_'.$month; - if (count($files) > 0) - { + if (count($files) > 0) { $now = dol_now(); $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf'; @@ -1009,8 +1084,9 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto // check if pdftk is installed if (file_exists($file)) { - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } $langs->load("exports"); setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs'); @@ -1029,22 +1105,21 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto $pdf = pdf_getInstance($format); - if (class_exists('TCPDF')) - { + if (class_exists('TCPDF')) { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); } $pdf->SetFont(pdf_getPDFFont($outputlangs)); - if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false); + if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) { + $pdf->SetCompression(false); + } // Add all others - foreach ($files as $file) - { + foreach ($files as $file) { // Charge un document PDF depuis un fichier. $pagecount = $pdf->setSourceFile($file); - for ($i = 1; $i <= $pagecount; $i++) - { + for ($i = 1; $i <= $pagecount; $i++) { $tplidx = $pdf->importPage($i); $s = $pdf->getTemplatesize($tplidx); $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); @@ -1060,20 +1135,26 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto $filename = preg_replace('/\s/', '_', $filename); // Save merged file - if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) - { - if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); - else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); + if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED) { + if ($option == 'late') { + $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late"))); + } else { + $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))); + } } - if ($year) $filename .= '_'.$year; - if ($month) $filename .= '_'.$month; - if ($pagecount) - { + if ($year) { + $filename .= '_'.$year; + } + if ($month) { + $filename .= '_'.$month; + } + if ($pagecount) { $now = dol_now(); $file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf'; $pdf->Output($file, 'F'); - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } $langs->load("exports"); setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs'); @@ -1084,47 +1165,43 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto } // Remove a file from massaction area -if ($action == 'remove_file') -{ +if ($action == 'remove_file') { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $langs->load("other"); $upload_dir = $diroutputmassaction; $file = $upload_dir.'/'.GETPOST('file'); $ret = dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + } $action = ''; } // Validate records -if (!$error && $massaction == 'validate' && $permissiontoadd) -{ +if (!$error && $massaction == 'validate' && $permissiontoadd) { $objecttmp = new $objectclass($db); - if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) - { + if (($objecttmp->element == 'facture' || $objecttmp->element == 'invoice') && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL)) { $langs->load("errors"); setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors'); $error++; } - if ($objecttmp->element == 'invoice_supplier' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) - { + if ($objecttmp->element == 'invoice_supplier' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) { $langs->load("errors"); setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $db->begin(); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $result = $objecttmp->validate($user); if ($result == 0) { $langs->load("errors"); @@ -1174,10 +1251,12 @@ if (!$error && $massaction == 'validate' && $permissiontoadd) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1200,7 +1279,9 @@ if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permissio setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -1209,9 +1290,11 @@ if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permissio } if (!$error) { - if ($nbok > 1) + if ($nbok > 1) { setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1221,47 +1304,45 @@ if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permissio //var_dump($_POST);var_dump($massaction);exit; // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before) -if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) -{ +if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) { $db->begin(); $objecttmp = new $objectclass($db); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { // Refuse deletion for some objects/status - if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) - { + if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT) { $langs->load("errors"); $nbignored++; $resaction .= '
    '.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'

    '; continue; } - if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) - { + if ($objectclass == "Task" && $objecttmp->hasChildren() > 0) { $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".$objecttmp->id; $res = $db->query($sql); - if (!$res) - { + if (!$res) { setEventMessage('ErrorRecordParentingNotModified', 'errors'); $error++; } } - if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1); - else $result = $objecttmp->delete($user); + if (in_array($objecttmp->element, array('societe', 'member'))) { + $result = $objecttmp->delete($objecttmp->id, $user, 1); + } else { + $result = $objecttmp->delete($user); + } - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -1269,10 +1350,12 @@ if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == ' } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1282,43 +1365,54 @@ if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == ' // Generate document foreach object according to model linked to object // @todo : propose model selection -if (!$error && $massaction == 'generate_doc' && $permissiontoread) -{ +if (!$error && $massaction == 'generate_doc' && $permissiontoread) { $db->begin(); $objecttmp = new $objectclass($db); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $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) && isset($objecttmp->thirdparty->default_lang)) $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ... - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang = $objecttmp->default_lang; // for thirdparty - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) { + $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ... + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) { + $newlang = $objecttmp->default_lang; // for thirdparty + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } // To be sure vars is defined - if (empty($hidedetails)) $hidedetails = 0; - if (empty($hidedesc)) $hidedesc = 0; - if (empty($hideref)) $hideref = 0; - if (empty($moreparams)) $moreparams = null; + if (empty($hidedetails)) { + $hidedetails = 0; + } + if (empty($hidedesc)) { + $hidedesc = 0; + } + if (empty($hideref)) { + $hideref = 0; + } + if (empty($moreparams)) { + $moreparams = null; + } $result = $objecttmp->generateDocument($objecttmp->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -1326,10 +1420,12 @@ if (!$error && $massaction == 'generate_doc' && $permissiontoread) } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1383,10 +1479,12 @@ if (!$error && ($action == 'affecttag' && $confirm == 'yes') && $permissiontoadd } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null); - else setEventMessages($langs->trans("RecordsModified", $nbok), null); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsModified", $nbok), null); + } else { + setEventMessages($langs->trans("RecordsModified", $nbok), null); + } $db->commit(); $toselect=array(); } else { @@ -1400,4 +1498,6 @@ $parameters['massaction'] = $massaction; $parameters['diroutputmassaction'] = $diroutputmassaction; $reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} diff --git a/htdocs/core/actions_printing.inc.php b/htdocs/core/actions_printing.inc.php index 3838e6963ab..de415bb4ba3 100644 --- a/htdocs/core/actions_printing.inc.php +++ b/htdocs/core/actions_printing.inc.php @@ -55,16 +55,15 @@ if ($action == 'print_file' && $user->rights->printing->read) { $subdir = ''; $module = GETPOST('printer', 'alpha'); - switch ($module) - { - case 'livraison' : + switch ($module) { + case 'livraison': $subdir = 'receipt'; $module = 'expedition'; break; - case 'expedition' : + case 'expedition': $subdir = 'sending'; break; - case 'commande_fournisseur' : + case 'commande_fournisseur': $module = 'fournisseur'; $subdir = 'commande'; break; @@ -75,20 +74,20 @@ if ($action == 'print_file' && $user->rights->printing->read) { //print '
    '.print_r($printer->errors, true).'
    '; setEventMessages($printer->error, $printer->errors, 'errors'); } - if ($ret == 0) - { + if ($ret == 0) { //print '
    '.print_r($printer->errors, true).'
    '; setEventMessages($printer->error, $printer->errors); setEventMessages($langs->transnoentitiesnoconv("FileWasSentToPrinter", basename(GETPOST('file', 'alpha'))).' '.$langs->transnoentitiesnoconv("ViaModule").' '.$printer->name, null); } - } catch (Exception $e) - { + } catch (Exception $e) { $ret = 1; setEventMessages($e->getMessage(), null, 'errors'); } } } - if ($printerfound == 0) setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings'); + if ($printerfound == 0) { + setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings'); + } } else { setEventMessages($langs->trans("NoModuleFound"), null, 'warnings'); } diff --git a/htdocs/core/actions_setmoduleoptions.inc.php b/htdocs/core/actions_setmoduleoptions.inc.php index d662d3c85c9..e56c4a95dcd 100644 --- a/htdocs/core/actions_setmoduleoptions.inc.php +++ b/htdocs/core/actions_setmoduleoptions.inc.php @@ -27,66 +27,60 @@ // $nomessageinupdate can be set to 1 // $nomessageinsetmoduleoptions can be set to 1 -if ($action == 'update' && is_array($arrayofparameters)) -{ +if ($action == 'update' && is_array($arrayofparameters)) { $db->begin(); - foreach ($arrayofparameters as $key => $val) - { + foreach ($arrayofparameters as $key => $val) { // Modify constant only if key was posted (avoid resetting key to the null value) - if (GETPOSTISSET($key)) - { + if (GETPOSTISSET($key)) { $result = dolibarr_set_const($db, $key, GETPOST($key, 'alpha'), 'chaine', 0, '', $conf->entity); - if ($result < 0) - { + if ($result < 0) { $error++; break; } } } - if (!$error) - { + if (!$error) { $db->commit(); - if (empty($nomessageinupdate)) setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + if (empty($nomessageinupdate)) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } } else { $db->rollback(); - if (empty($nomessageinupdate)) setEventMessages($langs->trans("SetupNotSaved"), null, 'errors'); + if (empty($nomessageinupdate)) { + setEventMessages($langs->trans("SetupNotSaved"), null, 'errors'); + } } } // Define constants for submodules that contains parameters (forms with param1, param2, ... and value1, value2, ...) -if ($action == 'setModuleOptions') -{ +if ($action == 'setModuleOptions') { $db->begin(); // Process common param fields - if (is_array($_POST)) - { - foreach ($_POST as $key => $val) - { + if (is_array($_POST)) { + foreach ($_POST as $key => $val) { $reg = array(); - if (preg_match('/^param(\d*)$/', $key, $reg)) // Works for POST['param'], POST['param1'], POST['param2'], ... - { + if (preg_match('/^param(\d*)$/', $key, $reg)) { // Works for POST['param'], POST['param1'], POST['param2'], ... $param = GETPOST("param".$reg[1], 'alpha'); $value = GETPOST("value".$reg[1], 'alpha'); - if ($param) - { + if ($param) { $res = dolibarr_set_const($db, $param, $value, 'chaine', 0, '', $conf->entity); - if (!($res > 0)) $error++; + if (!($res > 0)) { + $error++; + } } } } } // Process upload fields - if (GETPOST('upload', 'alpha') && GETPOST('keyforuploaddir', 'aZ09')) - { + if (GETPOST('upload', 'alpha') && GETPOST('keyforuploaddir', 'aZ09')) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $keyforuploaddir = GETPOST('keyforuploaddir', 'aZ09'); $listofdir = explode(',', preg_replace('/[\r\n]+/', ',', trim($conf->global->$keyforuploaddir))); - foreach ($listofdir as $key=>$tmpdir) - { + foreach ($listofdir as $key => $tmpdir) { $tmpdir = trim($tmpdir); $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); if (!$tmpdir) { @@ -96,24 +90,27 @@ if ($action == 'setModuleOptions') if (empty($nomessageinsetmoduleoptions)) { setEventMessages($langs->trans("ErrorDirNotFound", $tmpdir), null, 'warnings'); } - } - else { + } else { $upload_dir = $tmpdir; } } - if ($upload_dir) - { + if ($upload_dir) { $result = dol_add_file_process($upload_dir, 1, 1, 'uploadfile', ''); - if ($result <= 0) $error++; + if ($result <= 0) { + $error++; + } } } - if (!$error) - { + if (!$error) { $db->commit(); - if (empty($nomessageinsetmoduleoptions)) setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + if (empty($nomessageinsetmoduleoptions)) { + setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); + } } else { $db->rollback(); - if (empty($nomessageinsetmoduleoptions)) setEventMessages($langs->trans("SetupNotSaved"), null, 'errors'); + if (empty($nomessageinsetmoduleoptions)) { + setEventMessages($langs->trans("SetupNotSaved"), null, 'errors'); + } } } diff --git a/htdocs/core/actions_setnotes.inc.php b/htdocs/core/actions_setnotes.inc.php index b9dd4194268..f2426f6523f 100644 --- a/htdocs/core/actions_setnotes.inc.php +++ b/htdocs/core/actions_setnotes.inc.php @@ -28,23 +28,29 @@ // $id must be defined (object is loaded in this file with fetch) // Set public note -if ($action == 'setnote_public' && !empty($permissionnote) && !GETPOST('cancel', 'alpha')) -{ - if (empty($action) || !is_object($object) || empty($id)) dol_print_error('', 'Include of actions_setnotes.inc.php was done but required variable was not set before'); - if (empty($object->id)) $object->fetch($id); // Fetch may not be already done +if ($action == 'setnote_public' && !empty($permissionnote) && !GETPOST('cancel', 'alpha')) { + if (empty($action) || !is_object($object) || empty($id)) { + dol_print_error('', 'Include of actions_setnotes.inc.php was done but required variable was not set before'); + } + if (empty($object->id)) { + $object->fetch($id); // Fetch may not be already done + } $result_update = $object->update_note(dol_html_entity_decode(GETPOST('note_public', 'restricthtml'), ENT_QUOTES | ENT_HTML5, 'UTF-8', 1), '_public'); - if ($result_update < 0) setEventMessages($object->error, $object->errors, 'errors'); - elseif (in_array($object->table_element, array('supplier_proposal', 'propal', 'commande_fournisseur', 'commande', 'facture_fourn', 'facture'))) - { + if ($result_update < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } elseif (in_array($object->table_element, array('supplier_proposal', 'propal', 'commande_fournisseur', 'commande', 'facture_fourn', 'facture'))) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -56,13 +62,21 @@ if ($action == 'setnote_public' && !empty($permissionnote) && !GETPOST('cancel', $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } } } elseif ($action == 'setnote_private' && !empty($permissionnote) && !GETPOST('cancel', 'alpha')) { // Set public note - if (empty($action) || !is_object($object) || empty($id)) dol_print_error('', 'Include of actions_setnotes.inc.php was done but required variable was not set before'); - if (empty($object->id)) $object->fetch($id); // Fetch may not be already done + if (empty($action) || !is_object($object) || empty($id)) { + dol_print_error('', 'Include of actions_setnotes.inc.php was done but required variable was not set before'); + } + if (empty($object->id)) { + $object->fetch($id); // Fetch may not be already done + } $result = $object->update_note(dol_html_entity_decode(GETPOST('note_private', 'restricthtml'), ENT_QUOTES | ENT_HTML5), '_private'); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } diff --git a/htdocs/core/ajax/ajaxdirpreview.php b/htdocs/core/ajax/ajaxdirpreview.php index 9575208f485..43438c66dc4 100644 --- a/htdocs/core/ajax/ajaxdirpreview.php +++ b/htdocs/core/ajax/ajaxdirpreview.php @@ -27,13 +27,20 @@ * ajaxdirpreview.php?mode=nojs&action=preview&module=ecm§ion=0&file=xxx */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} -if (!isset($mode) || $mode != 'noajax') // For ajax call -{ +if (!isset($mode) || $mode != 'noajax') { // For ajax call require_once '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; @@ -50,12 +57,18 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $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 + 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 = "ASC"; - if (!$sortfield) $sortfield = "name"; + if (!$sortorder) { + $sortorder = "ASC"; + } + if (!$sortfield) { + $sortfield = "name"; + } $rootdirfordoc = $conf->ecm->dir_output; @@ -64,8 +77,7 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $ecmdir = new EcmDirectory($db); if ($section > 0) { $result = $ecmdir->fetch($section); - if (!$result > 0) - { + if (!$result > 0) { //dol_print_error($db,$ecmdir->error); //exit; } @@ -76,18 +88,15 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $ecmdir = new EcmDirectory($db); $relativepath = ''; - if ($section > 0) - { + if ($section > 0) { $result = $ecmdir->fetch($section); - if (!$result > 0) - { + if (!$result > 0) { dol_print_error($db, $ecmdir->error); exit; } $relativepath = $ecmdir->getRelativePath(); // Example 'mydir/' - } elseif (GETPOST('section_dir')) - { + } elseif (GETPOST('section_dir')) { $relativepath = GETPOST('section_dir'); } //var_dump($section.'-'.GETPOST('section_dir').'-'.$relativepath); @@ -95,24 +104,27 @@ if (!isset($mode) || $mode != 'noajax') // For ajax call $upload_dir = $rootdirfordoc.'/'.$relativepath; } -if (empty($url)) -{ - if (GETPOSTISSET('website')) $url = DOL_URL_ROOT.'/website/index.php'; - else $url = DOL_URL_ROOT.'/ecm/index.php'; +if (empty($url)) { + if (GETPOSTISSET('website')) { + $url = DOL_URL_ROOT.'/website/index.php'; + } else { + $url = DOL_URL_ROOT.'/ecm/index.php'; + } } // Load translation files required by the page $langs->loadLangs(array("ecm", "companies", "other")); // Security check -if ($user->socid > 0) $socid = $user->socid; +if ($user->socid > 0) { + $socid = $user->socid; +} //print 'xxx'.$upload_dir; // Security: // On interdit les remontees de repertoire ainsi que les pipe dans les noms de fichiers. -if (preg_match('/\.\./', $upload_dir) || preg_match('/[<>|]/', $upload_dir)) -{ +if (preg_match('/\.\./', $upload_dir) || preg_match('/[<>|]/', $upload_dir)) { dol_syslog("Refused to deliver file ".$upload_dir); // Do no show plain path in shown error message dol_print_error(0, $langs->trans("ErrorFileNameInvalid", $upload_dir)); @@ -120,12 +132,12 @@ if (preg_match('/\.\./', $upload_dir) || preg_match('/[<>|]/', $upload_dir)) } // Check permissions -if ($modulepart == 'ecm') -{ - if (!$user->rights->ecm->read) accessforbidden(); +if ($modulepart == 'ecm') { + if (!$user->rights->ecm->read) { + accessforbidden(); + } } -if ($modulepart == 'medias') -{ +if ($modulepart == 'medias') { // Always allowed } @@ -142,8 +154,7 @@ if ($modulepart == 'medias') * View */ -if (!isset($mode) || $mode != 'noajax') -{ +if (!isset($mode) || $mode != 'noajax') { // Ajout directives pour resoudre bug IE header('Cache-Control: Public, must-revalidate'); header('Pragma: public'); @@ -154,25 +165,27 @@ if (!isset($mode) || $mode != 'noajax') $type = 'directory'; // This test if file exists should be useless. We keep it to find bug more easily -if (!dol_is_dir($upload_dir)) -{ +if (!dol_is_dir($upload_dir)) { //dol_mkdir($upload_dir); /*$langs->load("install"); - dol_print_error(0,$langs->trans("ErrorDirDoesNotExists",$upload_dir)); - exit;*/ + dol_print_error(0,$langs->trans("ErrorDirDoesNotExists",$upload_dir)); + exit;*/ } print ''."\n"; //print ''."\n"; $param = ($sortfield ? '&sortfield='.urlencode($sortfield) : '').($sortorder ? '&sortorder='.urlencode($sortorder) : ''); -if (!empty($websitekey)) $param .= '&website='.urlencode($websitekey); -if (!empty($pageid)) $param .= '&pageid='.urlencode($pageid); +if (!empty($websitekey)) { + $param .= '&website='.urlencode($websitekey); +} +if (!empty($pageid)) { + $param .= '&pageid='.urlencode($pageid); +} // Dir scan -if ($type == 'directory') -{ +if ($type == 'directory') { $formfile = new FormFile($db); $maxlengthname = 40; @@ -203,31 +216,48 @@ if ($type == 'directory') $parameters = array('modulepart'=>$module); $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters); - if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray)>0) - { + if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray)>0) { $automodules[]=$hookmanager->resArray['module']; } // TODO change for multicompany sharing - if ($module == 'company') $upload_dir = $conf->societe->dir_output; - elseif ($module == 'invoice') $upload_dir = $conf->facture->dir_output; - elseif ($module == 'invoice_supplier') $upload_dir = $conf->fournisseur->facture->dir_output; - elseif ($module == 'propal') $upload_dir = $conf->propal->dir_output; - elseif ($module == 'supplier_proposal') $upload_dir = $conf->supplier_proposal->dir_output; - elseif ($module == 'order') $upload_dir = $conf->commande->dir_output; - elseif ($module == 'order_supplier') $upload_dir = $conf->fournisseur->commande->dir_output; - elseif ($module == 'contract') $upload_dir = $conf->contrat->dir_output; - elseif ($module == 'product') $upload_dir = $conf->product->dir_output; - elseif ($module == 'tax') $upload_dir = $conf->tax->dir_output; - elseif ($module == 'project') $upload_dir = $conf->projet->dir_output; - elseif ($module == 'fichinter') $upload_dir = $conf->ficheinter->dir_output; - elseif ($module == 'user') $upload_dir = $conf->user->dir_output; - elseif ($module == 'expensereport') $upload_dir = $conf->expensereport->dir_output; - elseif ($module == 'holiday') $upload_dir = $conf->holiday->dir_output; - elseif ($module == 'recruitment-recruitmentcandidature') $upload_dir = $conf->recruitment->dir_output.'/recruitmentcandidature'; - elseif ($module == 'banque') $upload_dir = $conf->bank->dir_output; - elseif ($module == 'mrp-mo') $upload_dir = $conf->mrp->dir_output.'/mo'; - else { + if ($module == 'company') { + $upload_dir = $conf->societe->dir_output; + } elseif ($module == 'invoice') { + $upload_dir = $conf->facture->dir_output; + } elseif ($module == 'invoice_supplier') { + $upload_dir = $conf->fournisseur->facture->dir_output; + } elseif ($module == 'propal') { + $upload_dir = $conf->propal->dir_output; + } elseif ($module == 'supplier_proposal') { + $upload_dir = $conf->supplier_proposal->dir_output; + } elseif ($module == 'order') { + $upload_dir = $conf->commande->dir_output; + } elseif ($module == 'order_supplier') { + $upload_dir = $conf->fournisseur->commande->dir_output; + } elseif ($module == 'contract') { + $upload_dir = $conf->contrat->dir_output; + } elseif ($module == 'product') { + $upload_dir = $conf->product->dir_output; + } elseif ($module == 'tax') { + $upload_dir = $conf->tax->dir_output; + } elseif ($module == 'project') { + $upload_dir = $conf->projet->dir_output; + } elseif ($module == 'fichinter') { + $upload_dir = $conf->ficheinter->dir_output; + } elseif ($module == 'user') { + $upload_dir = $conf->user->dir_output; + } elseif ($module == 'expensereport') { + $upload_dir = $conf->expensereport->dir_output; + } elseif ($module == 'holiday') { + $upload_dir = $conf->holiday->dir_output; + } elseif ($module == 'recruitment-recruitmentcandidature') { + $upload_dir = $conf->recruitment->dir_output.'/recruitmentcandidature'; + } elseif ($module == 'banque') { + $upload_dir = $conf->bank->dir_output; + } elseif ($module == 'mrp-mo') { + $upload_dir = $conf->mrp->dir_output.'/mo'; + } else { $parameters = array('modulepart'=>$module); $reshook = $hookmanager->executeHooks('addSectionECMAuto', $parameters); if ($reshook > 0 && is_array($hookmanager->resArray) && count($hookmanager->resArray) > 0) { @@ -236,14 +266,17 @@ if ($type == 'directory') } // Automatic list - if (in_array($module, $automodules)) - { + if (in_array($module, $automodules)) { $param .= '&module='.$module; - if (isset($search_doc_ref) && $search_doc_ref != '') $param .= '&search_doc_ref='.urlencode($search_doc_ref); + if (isset($search_doc_ref) && $search_doc_ref != '') { + $param .= '&search_doc_ref='.urlencode($search_doc_ref); + } $textifempty = ($section ? $langs->trans("NoFileFound") : ($showonrightsize == 'featurenotyetavailable' ? $langs->trans("FeatureNotYetAvailable") : $langs->trans("NoFileFound"))); - if ($module == 'company') $excludefiles[] = '^contact$'; // The subdir 'contact' contains files of contacts with no id of thirdparty. + if ($module == 'company') { + $excludefiles[] = '^contact$'; // The subdir 'contact' contains files of contacts with no id of thirdparty. + } $filter = preg_quote($search_doc_ref, '/'); $filearray = dol_dir_list($upload_dir, "files", 1, $filter, $excludefiles, $sortfield, $sorting, 1); @@ -254,11 +287,10 @@ if ($type == 'directory') } // Manual list else { - if ($module == 'medias') - { + if ($module == 'medias') { /* - $_POST is array like - 'token' => string '062380e11b7dcd009d07318b57b71750' (length=32) + $_POST is array like + 'token' => string '062380e11b7dcd009d07318b57b71750' (length=32) 'action' => string 'file_manager' (length=12) 'website' => string 'template' (length=8) 'pageid' => string '124' (length=3) @@ -266,15 +298,20 @@ if ($type == 'directory') 'section_id' => string '0' (length=1) 'max_file_size' => string '2097152' (length=7) 'sendit' => string 'Envoyer fichier' (length=15) - */ + */ $relativepath = GETPOST('file', 'alpha') ?GETPOST('file', 'alpha') : GETPOST('section_dir', 'alpha'); - if ($relativepath && $relativepath != '/') $relativepath .= '/'; + if ($relativepath && $relativepath != '/') { + $relativepath .= '/'; + } $upload_dir = $dolibarr_main_data_root.'/'.$module.'/'.$relativepath; - if (GETPOSTISSET('website') || GETPOSTISSET('file_manager')) - { + if (GETPOSTISSET('website') || GETPOSTISSET('file_manager')) { $param .= '&file_manager=1'; - if (!preg_match('/website=/', $param)) $param .= '&website='.urlencode(GETPOST('website', 'alpha')); - if (!preg_match('/pageid=/', $param)) $param .= '&pageid='.urlencode(GETPOST('pageid', 'int')); + if (!preg_match('/website=/', $param)) { + $param .= '&website='.urlencode(GETPOST('website', 'alpha')); + } + if (!preg_match('/pageid=/', $param)) { + $param .= '&pageid='.urlencode(GETPOST('pageid', 'int')); + } //if (!preg_match('/backtopage=/',$param)) $param.='&backtopage='.urlencode($_SERVER["PHP_SELF"].'?file_manager=1&website='.$websitekey.'&pageid='.$pageid); } } else { @@ -283,47 +320,46 @@ if ($type == 'directory') } // If $section defined with value 0 - if (($section === '0' || empty($section)) && ($module != 'medias')) - { + if (($section === '0' || empty($section)) && ($module != 'medias')) { $filearray = array(); } else { $filearray = dol_dir_list($upload_dir, "files", 0, '', array('^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^CVS$'), $sortfield, $sorting, 1); } - if ($section) - { + if ($section) { $param .= '§ion='.$section; - if (isset($search_doc_ref) && $search_doc_ref != '') $param .= '&search_doc_ref='.$search_doc_ref; + if (isset($search_doc_ref) && $search_doc_ref != '') { + $param .= '&search_doc_ref='.$search_doc_ref; + } $textifempty = $langs->trans('NoFileFound'); - } elseif ($section === '0') - { - if ($module == 'ecm') $textifempty = '
    '.$langs->trans("DirNotSynchronizedSyncFirst").'

    '; - else $textifempty = $langs->trans('NoFileFound'); - } else $textifempty = ($showonrightsize == 'featurenotyetavailable' ? $langs->trans("FeatureNotYetAvailable") : $langs->trans("ECMSelectASection")); + } elseif ($section === '0') { + if ($module == 'ecm') { + $textifempty = '
    '.$langs->trans("DirNotSynchronizedSyncFirst").'

    '; + } else { + $textifempty = $langs->trans('NoFileFound'); + } + } else { + $textifempty = ($showonrightsize == 'featurenotyetavailable' ? $langs->trans("FeatureNotYetAvailable") : $langs->trans("ECMSelectASection")); + } - if ($module == 'medias') - { + if ($module == 'medias') { $useinecm = 6; $modulepart = 'medias'; $perm = ($user->rights->website->write || $user->rights->emailing->creer); $title = 'none'; - } elseif ($module == 'ecm') // DMS/ECM -> manual structure - { - if ($user->rights->ecm->read) - { + } elseif ($module == 'ecm') { // DMS/ECM -> manual structure + if ($user->rights->ecm->read) { // Buttons: Preview $useinecm = 2; } - if ($user->rights->ecm->upload) - { + if ($user->rights->ecm->upload) { // Buttons: Preview + Delete $useinecm = 4; } - if ($user->rights->ecm->setup) - { + if ($user->rights->ecm->setup) { // Buttons: Preview + Delete + Edit $useinecm = 5; } @@ -349,18 +385,27 @@ if ($type == 'directory') // Bottom of page $useajax = 1; -if (!empty($conf->dol_use_jmobile)) $useajax = 0; -if (empty($conf->use_javascript_ajax)) $useajax = 0; -if (!empty($conf->global->MAIN_ECM_DISABLE_JS)) $useajax = 0; +if (!empty($conf->dol_use_jmobile)) { + $useajax = 0; +} +if (empty($conf->use_javascript_ajax)) { + $useajax = 0; +} +if (!empty($conf->global->MAIN_ECM_DISABLE_JS)) { + $useajax = 0; +} //$param.=($param?'?':'').(preg_replace('/^&/','',$param)); -if ($useajax || $action == 'delete') -{ +if ($useajax || $action == 'delete') { $urlfile = ''; - if ($action == 'delete') $urlfile = GETPOST('urlfile', 'alpha'); + if ($action == 'delete') { + $urlfile = GETPOST('urlfile', 'alpha'); + } - if (empty($section_dir)) $section_dir = GETPOST("file", "alpha"); + if (empty($section_dir)) { + $section_dir = GETPOST("file", "alpha"); + } $section_id = $section; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; @@ -372,22 +417,26 @@ if ($useajax || $action == 'delete') $formquestion['section_dir'] = array('type'=>'hidden', 'value'=>$section_dir, 'name'=>'section_dir'); // We must always put field, even if empty because it is filled by javascript later $formquestion['sortfield'] = array('type'=>'hidden', 'value'=>$sortfield, 'name'=>'sortfield'); // We must always put field, even if empty because it is filled by javascript later $formquestion['sortorder'] = array('type'=>'hidden', 'value'=>$sortorder, 'name'=>'sortorder'); // We must always put field, even if empty because it is filled by javascript later - if (!empty($action) && $action == 'file_manager') $formquestion['file_manager'] = array('type'=>'hidden', 'value'=>1, 'name'=>'file_manager'); - if (!empty($websitekey)) $formquestion['website'] = array('type'=>'hidden', 'value'=>$websitekey, 'name'=>'website'); - if (!empty($pageid) && $pageid > 0) $formquestion['pageid'] = array('type'=>'hidden', 'value'=>$pageid, 'name'=>'pageid'); + if (!empty($action) && $action == 'file_manager') { + $formquestion['file_manager'] = array('type'=>'hidden', 'value'=>1, 'name'=>'file_manager'); + } + if (!empty($websitekey)) { + $formquestion['website'] = array('type'=>'hidden', 'value'=>$websitekey, 'name'=>'website'); + } + if (!empty($pageid) && $pageid > 0) { + $formquestion['pageid'] = array('type'=>'hidden', 'value'=>$pageid, 'name'=>'pageid'); + } print $form->formconfirm($url, $langs->trans("DeleteFile"), $langs->trans("ConfirmDeleteFile"), 'confirm_deletefile', $formquestion, "no", ($useajax ? 'deletefile' : 0)); } -if ($useajax) -{ +if ($useajax) { print ''."\n"; } - if (empty($found)) - { + if (empty($found)) { $out .= 'Error, unknown value for tool '.$this->tool.' in DolEditor Create function.'; } - if ($noprint) return $out; - else print $out; + if ($noprint) { + return $out; + } else { + print $out; + } } } diff --git a/htdocs/core/class/dolgeoip.class.php b/htdocs/core/class/dolgeoip.class.php index 98fbe62e4c5..0eecbbf6d36 100644 --- a/htdocs/core/class/dolgeoip.class.php +++ b/htdocs/core/class/dolgeoip.class.php @@ -46,54 +46,48 @@ class DolGeoIP global $conf; $geoipversion = '2'; // 'php', or '2' - if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; + if (!empty($conf->global->GEOIP_VERSION)) { + $geoipversion = $conf->global->GEOIP_VERSION; + } - if ($type == 'country') - { + if ($type == 'country') { // geoip may have been already included with PEAR - if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) - { + if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) { require_once DOL_DOCUMENT_ROOT.'/includes/geoip2/geoip2.phar'; } - } elseif ($type == 'city') - { + } elseif ($type == 'city') { // geoip may have been already included with PEAR - if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) - { + if ($geoipversion == '2' || ($geoipversion != 'php' && !function_exists('geoip_country_code_by_name'))) { require_once DOL_DOCUMENT_ROOT.'/includes/geoip2/geoip2.phar'; } - } else { print 'ErrorBadParameterInConstructor'; return 0; } + } else { + print 'ErrorBadParameterInConstructor'; return 0; + } // Here, function exists (embedded into PHP or exists because we made include) - if (empty($type) || empty($datfile)) - { + if (empty($type) || empty($datfile)) { $this->errorlabel = 'Constructor was called with no datafile parameter'; dol_syslog('DolGeoIP '.$this->errorlabel, LOG_ERR); return 0; } - if (!file_exists($datfile) || !is_readable($datfile)) - { + if (!file_exists($datfile) || !is_readable($datfile)) { $this->error = 'ErrorGeoIPClassNotInitialized'; $this->errorlabel = "Datafile ".$datfile." not found"; dol_syslog('DolGeoIP '.$this->errorlabel, LOG_ERR); return 0; } - if ($geoipversion == '2') - { + if ($geoipversion == '2') { try { $this->gi = new GeoIp2\Database\Reader($datfile); // '/usr/local/share/GeoIP/GeoIP2-City.mmdb' - } catch (Exception $e) - { + } catch (Exception $e) { $this->error = $e->getMessage(); dol_syslog('DolGeoIP '.$this->errorlabel, LOG_ERR); return 0; } - } elseif (function_exists('geoip_open')) - { + } elseif (function_exists('geoip_open')) { $this->gi = geoip_open($datfile, GEOIP_STANDARD); - } - elseif (function_exists('geoip_country_code_by_name')) { + } elseif (function_exists('geoip_country_code_by_name')) { $this->gi = 'NOGI'; // We are using embedded php geoip functions //print 'function_exists(geoip_country_code_by_name))='.function_exists('geoip_country_code_by_name'); //print geoip_database_info(); @@ -113,21 +107,19 @@ class DolGeoIP global $conf; $geoipversion = '2'; // 'php', or '2' - if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; + if (!empty($conf->global->GEOIP_VERSION)) { + $geoipversion = $conf->global->GEOIP_VERSION; + } - if (empty($this->gi)) - { + if (empty($this->gi)) { return ''; } - if ($this->gi == 'NOGI') - { + if ($this->gi == 'NOGI') { // geoip_country_code_by_addr does not exists return strtolower(geoip_country_code_by_name($ip)); } else { - if (preg_match('/^[0-9]+.[0-9]+\.[0-9]+\.[0-9]+/', $ip)) - { - if ($geoipversion == '2') - { + if (preg_match('/^[0-9]+.[0-9]+\.[0-9]+\.[0-9]+/', $ip)) { + if ($geoipversion == '2') { try { $record = $this->gi->country($ip); return strtolower($record->country->isoCode); @@ -136,12 +128,13 @@ class DolGeoIP return ''; } } else { - if (!function_exists('geoip_country_code_by_addr')) return strtolower(geoip_country_code_by_name($this->gi, $ip)); + if (!function_exists('geoip_country_code_by_addr')) { + return strtolower(geoip_country_code_by_name($this->gi, $ip)); + } return strtolower(geoip_country_code_by_addr($this->gi, $ip)); } } else { - if ($geoipversion == '2') - { + if ($geoipversion == '2') { try { $record = $this->gi->country($ip); return strtolower($record->country->isoCode); @@ -150,7 +143,9 @@ class DolGeoIP return ''; } } else { - if (!function_exists('geoip_country_code_by_addr_v6')) return strtolower(geoip_country_code_by_name_v6($this->gi, $ip)); + if (!function_exists('geoip_country_code_by_addr_v6')) { + return strtolower(geoip_country_code_by_name_v6($this->gi, $ip)); + } return strtolower(geoip_country_code_by_addr_v6($this->gi, $ip)); } } @@ -168,15 +163,15 @@ class DolGeoIP global $conf; $geoipversion = '2'; // 'php', or '2' - if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; + if (!empty($conf->global->GEOIP_VERSION)) { + $geoipversion = $conf->global->GEOIP_VERSION; + } - if (empty($this->gi)) - { + if (empty($this->gi)) { return ''; } - if ($geoipversion == '2') - { + if ($geoipversion == '2') { try { $record = $this->gi->country($name); return $record->country->isoCode; @@ -199,12 +194,16 @@ class DolGeoIP global $conf; $geoipversion = '2'; // 'php', or '2' - if (!empty($conf->global->GEOIP_VERSION)) $geoipversion = $conf->global->GEOIP_VERSION; + if (!empty($conf->global->GEOIP_VERSION)) { + $geoipversion = $conf->global->GEOIP_VERSION; + } - if ($geoipversion == 'php') - { - if ($this->gi == 'NOGI') return geoip_database_info(); - else return 'geoip_database_info() function not available'; + if ($geoipversion == 'php') { + if ($this->gi == 'NOGI') { + return geoip_database_info(); + } else { + return 'geoip_database_info() function not available'; + } } return 'Not available (not using PHP internal geo functions - We are using embedded Geoip v'.$geoipversion.')'; diff --git a/htdocs/core/class/dolgraph.class.php b/htdocs/core/class/dolgraph.class.php index fada0975938..607993dc325 100644 --- a/htdocs/core/class/dolgraph.class.php +++ b/htdocs/core/class/dolgraph.class.php @@ -114,9 +114,15 @@ class DolGraph $color_file = DOL_DOCUMENT_ROOT . '/theme/' . $conf->theme . '/theme_vars.inc.php'; if (is_readable($color_file)) { include_once $color_file; - if (isset($theme_bordercolor)) $this->bordercolor = $theme_bordercolor; - if (isset($theme_datacolor)) $this->datacolor = $theme_datacolor; - if (isset($theme_bgcolor)) $this->bgcolor = $theme_bgcolor; + if (isset($theme_bordercolor)) { + $this->bordercolor = $theme_bordercolor; + } + if (isset($theme_datacolor)) { + $this->datacolor = $theme_datacolor; + } + if (isset($theme_bgcolor)) { + $this->bgcolor = $theme_bgcolor; + } } //print 'bgcolor: '.join(',',$this->bgcolor).'
    '; @@ -597,7 +603,9 @@ class DolGraph public function GetMaxValueInData() { // phpcs:enable - if (!is_array($this->data)) return 0; + if (!is_array($this->data)) { + return 0; + } $k = 0; $vals = array(); @@ -624,7 +632,9 @@ class DolGraph public function GetMinValueInData() { // phpcs:enable - if (!is_array($this->data)) return 0; + if (!is_array($this->data)) { + return 0; + } $k = 0; $vals = array(); @@ -652,7 +662,9 @@ class DolGraph { // phpcs:enable $max = $this->GetMaxValueInData(); - if ($max != 0) $max++; + if ($max != 0) { + $max++; + } $size = dol_strlen(abs(ceil($max))); $factor = 1; for ($i = 0; $i < ($size - 1); $i++) { @@ -660,7 +672,9 @@ class DolGraph } $res = 0; - if (is_numeric($max)) $res = ceil($max / $factor) * $factor; + if (is_numeric($max)) { + $res = ceil($max / $factor) * $factor; + } //print "max=".$max." res=".$res; return $res; @@ -676,8 +690,12 @@ class DolGraph { // phpcs:enable $min = $this->GetMinValueInData(); - if ($min == '') $min = 0; - if ($min != 0) $min--; + if ($min == '') { + $min = 0; + } + if ($min != 0) { + $min--; + } $size = dol_strlen(abs(floor($min))); $factor = 1; for ($i = 0; $i < ($size - 1); $i++) { @@ -751,22 +769,22 @@ class DolGraph if (is_array($this->data) && is_array($this->data[0])) { $nblot = count($this->data[0]) - 1; // -1 to remove legend } - if ($nblot < 0) dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING); + if ($nblot < 0) { + dol_syslog('Bad value for property ->data. Must be set by mydolgraph->SetData before calling mydolgrapgh->draw', LOG_WARNING); + } $firstlot = 0; // Works with line but not with bars //if ($nblot > 2) $firstlot = ($nblot - 2); // We limit nblot to 2 because jflot can't manage more than 2 bars on same x $i = $firstlot; $serie = array(); - while ($i < $nblot) // Loop on each serie - { + while ($i < $nblot) { // Loop on each serie $values = array(); // Array with horizontal y values (specific values of a serie) for each abscisse x $serie[$i] = "var d" . $i . " = [];\n"; // Fill array $values $x = 0; - foreach ($this->data as $valarray) // Loop on each x - { + foreach ($this->data as $valarray) { // Loop on each x $legends[$x] = $valarray[0]; $values[$x] = (is_numeric($valarray[$i + 1]) ? $valarray[$i + 1] : null); $x++; @@ -774,11 +792,15 @@ class DolGraph if (isset($this->type[$firstlot]) && in_array($this->type[$firstlot], array('pie', 'piesemicircle', 'polar'))) { foreach ($values as $x => $y) { - if (isset($y)) $serie[$i] .= 'd' . $i . '.push({"label":"' . dol_escape_js($legends[$x]) . '", "data":' . $y . '});' . "\n"; + if (isset($y)) { + $serie[$i] .= 'd' . $i . '.push({"label":"' . dol_escape_js($legends[$x]) . '", "data":' . $y . '});' . "\n"; + } } } else { foreach ($values as $x => $y) { - if (isset($y)) $serie[$i] .= 'd' . $i . '.push([' . $x . ', ' . $y . ']);' . "\n"; + if (isset($y)) { + $serie[$i] .= 'd' . $i . '.push([' . $x . ', ' . $y . ']);' . "\n"; + } } } @@ -788,7 +810,9 @@ class DolGraph $tag = dol_escape_htmltag(dol_string_unaccent(dol_string_nospecial(basename($file), '_', array('-', '.')))); $this->stringtoshow = '' . "\n"; - if (!empty($this->title)) $this->stringtoshow .= '
    ' . $this->title . '
    '; + if (!empty($this->title)) { + $this->stringtoshow .= '
    ' . $this->title . '
    '; + } if (!empty($this->shownographyet)) { $this->stringtoshow .= '
    '; $this->stringtoshow .= '
    ' . $langs->trans("NotEnoughDataYet") . '...
    '; @@ -797,7 +821,9 @@ class DolGraph // Start the div that will contains all the graph $dolxaxisvertical = ''; - if (count($this->data) > 20) $dolxaxisvertical = 'dol-xaxis-vertical'; + if (count($this->data) > 20) { + $dolxaxisvertical = 'dol-xaxis-vertical'; + } $this->stringtoshow .= '
    ' . "\n"; $this->stringtoshow .= '";*/ + $retstring.=img_object($langs->trans("SelectDate"),'calendarday','id="'.$prefix.'id" class="datecallink"'); + $retstring.="";*/ } else { $retstringbutton = ''; $retsring = $retstringbutton.$retstring; @@ -5818,27 +6148,23 @@ class Form // Day $retstring .= ''; - if ($emptydate || $set_time == -1) - { + if ($emptydate || $set_time == -1) { $retstring .= ''; } - for ($day = 1; $day <= 31; $day++) - { + for ($day = 1; $day <= 31; $day++) { $retstring .= ''; } $retstring .= ""; $retstring .= ''; - if ($emptydate || $set_time == -1) - { + if ($emptydate || $set_time == -1) { $retstring .= ''; } // Month - for ($month = 1; $month <= 12; $month++) - { + for ($month = 1; $month <= 12; $month++) { $retstring .= '"; @@ -5846,14 +6172,12 @@ class Form $retstring .= ""; // Year - if ($emptydate || $set_time == -1) - { + if ($emptydate || $set_time == -1) { $retstring .= ''; } else { $retstring .= ''; - for ($year = $syear - 10; $year < $syear + 10; $year++) - { + for ($year = $syear - 10; $year < $syear + 10; $year++) { $retstring .= ''; } $retstring .= "\n"; @@ -5866,39 +6190,47 @@ class Form $retstring .= ''; } - if ($h) - { + if ($h) { $hourstart = 0; $hourend = 24; if ($openinghours != '') { $openinghours = explode(',', $openinghours); $hourstart = $openinghours[0]; $hourend = $openinghours[1]; - if ($hourend < $hourstart) $hourend = $hourstart; + if ($hourend < $hourstart) { + $hourend = $hourstart; + } } // Show hour $retstring .= ''; - if ($emptyhours) $retstring .= ''; - for ($hour = $hourstart; $hour < $hourend; $hour++) - { - if (strlen($hour) < 2) $hour = "0".$hour; + if ($emptyhours) { + $retstring .= ''; + } + for ($hour = $hourstart; $hour < $hourend; $hour++) { + if (strlen($hour) < 2) { + $hour = "0".$hour; + } $retstring .= ''; } $retstring .= ''; //if ($m && empty($conf->dol_optimize_smallscreen)) $retstring .= ":"; - if ($m) $retstring .= ":"; + if ($m) { + $retstring .= ":"; + } } - if ($m) - { + if ($m) { // Show minutes $retstring .= ''; - if ($emptyhours) $retstring .= ''; - for ($min = 0; $min < 60; $min += $stepminutes) - { - if (strlen($min) < 2) $min = "0".$min; + if ($emptyhours) { + $retstring .= ''; + } + for ($min = 0; $min < 60; $min += $stepminutes) { + if (strlen($min) < 2) { + $min = "0".$min; + } $retstring .= ''; } $retstring .= ''; @@ -5911,8 +6243,7 @@ class Form } // Add a "Now" link - if ($conf->use_javascript_ajax && $addnowlink) - { + if ($conf->use_javascript_ajax && $addnowlink) { // Script which will be inserted in the onClick of the "Now" link $reset_scripts = ""; if ($addnowlink == 2) { // local computer time @@ -5933,64 +6264,65 @@ class Form $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');'; } elseif ($addnowlink == 2) { /* Disabled because the output does not use the string format defined by FormatDateShort key to forge the value into #prefix. - * This break application for foreign languages. - $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);'; - $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());'; - */ + * This break application for foreign languages. + $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(d.toLocaleDateString(\''.str_replace('_', '-', $langs->defaultlang).'\'));'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(d.getDate().pad());'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(parseInt(d.getMonth().pad()) + 1);'; + $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(d.getFullYear());'; + */ $reset_scripts .= 'jQuery(\'#'.$prefix.'\').val(\''.dol_print_date($nowgmt, 'day', 'tzuserrel').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'day\').val(\''.dol_print_date($nowgmt, '%d', 'tzuserrel').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');'; } /*if ($usecalendar == "eldy") - { - $base=DOL_URL_ROOT.'/core/'; - $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');'; - } - else - { - $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); '; - $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); '; - $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); '; - }*/ - // Update the hour part - if ($h) { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + $base=DOL_URL_ROOT.'/core/'; + $reset_scripts .= 'resetDP(\''.$base.'\',\''.$prefix.'\',\''.$langs->trans("FormatDateShortJavaInput").'\',\''.$langs->defaultlang.'\');'; + } + else + { + $reset_scripts .= 'this.form.elements[\''.$prefix.'day\'].value=formatDate(new Date(), \'d\'); '; + $reset_scripts .= 'this.form.elements[\''.$prefix.'month\'].value=formatDate(new Date(), \'M\'); '; + $reset_scripts .= 'this.form.elements[\''.$prefix.'year\'].value=formatDate(new Date(), \'yyyy\'); '; + }*/ + // Update the hour part + if ($h) { + if ($fullday) { + $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + } //$reset_scripts .= 'this.form.elements[\''.$prefix.'hour\'].value=formatDate(new Date(), \'HH\'); '; - if ($addnowlink == 1) - { + if ($addnowlink == 1) { $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; - } elseif ($addnowlink == 2) - { + } elseif ($addnowlink == 2) { $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(d.getHours().pad());'; $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').change();'; } - if ($fullday) $reset_scripts .= ' } '; + if ($fullday) { + $reset_scripts .= ' } '; + } } // Update the minute part - if ($m) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + if ($m) { + if ($fullday) { + $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + } //$reset_scripts .= 'this.form.elements[\''.$prefix.'min\'].value=formatDate(new Date(), \'mm\'); '; - if ($addnowlink == 1) - { + if ($addnowlink == 1) { $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; - } elseif ($addnowlink == 2) - { + } elseif ($addnowlink == 2) { $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(d.getMinutes().pad());'; $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').change();'; } - if ($fullday) $reset_scripts .= ' } '; + if ($fullday) { + $reset_scripts .= ' } '; + } } // If reset_scripts is not empty, print the link with the reset_scripts in the onClick - if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) - { + if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) { $retstring .= ' '; @@ -5998,8 +6330,7 @@ class Form } // Add a "Plus one hour" link - if ($conf->use_javascript_ajax && $addplusone) - { + if ($conf->use_javascript_ajax && $addplusone) { // Script which will be inserted in the onClick of the "Add plusone" link $reset_scripts = ""; @@ -6009,22 +6340,27 @@ class Form $reset_scripts .= 'jQuery(\'#'.$prefix.'month\').val(\''.dol_print_date($nowgmt, '%m', 'tzuserrel').'\');'; $reset_scripts .= 'jQuery(\'#'.$prefix.'year\').val(\''.dol_print_date($nowgmt, '%Y', 'tzuserrel').'\');'; // Update the hour part - if ($h) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + if ($h) { + if ($fullday) { + $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + } $reset_scripts .= 'jQuery(\'#'.$prefix.'hour\').val(\''.dol_print_date($nowgmt, '%H', 'tzuserrel').'\');'; - if ($fullday) $reset_scripts .= ' } '; + if ($fullday) { + $reset_scripts .= ' } '; + } } // Update the minute part - if ($m) - { - if ($fullday) $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + if ($m) { + if ($fullday) { + $reset_scripts .= " if (jQuery('#fullday:checked').val() == null) {"; + } $reset_scripts .= 'jQuery(\'#'.$prefix.'min\').val(\''.dol_print_date($nowgmt, '%M', 'tzuserrel').'\');'; - if ($fullday) $reset_scripts .= ' } '; + if ($fullday) { + $reset_scripts .= ' } '; + } } // If reset_scripts is not empty, print the link with the reset_scripts in the onClick - if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) - { + if ($reset_scripts && empty($conf->dol_optimize_smallscreen)) { $retstring .= ' '; @@ -6032,10 +6368,11 @@ class Form } // Add a link to set data - if ($conf->use_javascript_ajax && $adddateof) - { + if ($conf->use_javascript_ajax && $adddateof) { $tmparray = dol_getdate($adddateof); - if (empty($labeladddateof)) $labeladddateof = $langs->trans("DateInvoice"); + if (empty($labeladddateof)) { + $labeladddateof = $langs->trans("DateInvoice"); + } $retstring .= ' -
    '.$langs->trans("None").'
    '; - if (!empty($compatibleImportElementsList)) - { + if (!empty($compatibleImportElementsList)) { $res = @include dol_buildpath('core/tpl/ajax/objectlinked_lineimport.tpl.php'); } @@ -7199,19 +7601,23 @@ class Form $linktoelemlist = ''; $listofidcompanytoscan = ''; - if (!is_object($object->thirdparty)) $object->fetch_thirdparty(); + if (!is_object($object->thirdparty)) { + $object->fetch_thirdparty(); + } $possiblelinks = array(); - if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) - { + if (is_object($object->thirdparty) && !empty($object->thirdparty->id) && $object->thirdparty->id > 0) { $listofidcompanytoscan = $object->thirdparty->id; - if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) $listofidcompanytoscan .= ','.$object->thirdparty->parent; - if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) - { + if (($object->thirdparty->parent > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PARENT_IN_LINKTO)) { + $listofidcompanytoscan .= ','.$object->thirdparty->parent; + } + if (($object->fk_project > 0) && !empty($conf->global->THIRDPARTY_INCLUDE_PROJECT_THIRDPARY_IN_LINKTO)) { include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $tmpproject = new Project($this->db); $tmpproject->fetch($object->fk_project); - if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) $listofidcompanytoscan .= ','.$tmpproject->socid; + if ($tmpproject->socid > 0 && ($tmpproject->socid != $object->thirdparty->id)) { + $listofidcompanytoscan .= ','.$tmpproject->socid; + } unset($tmpproject); } @@ -7234,39 +7640,33 @@ class Form $hookmanager->initHooks(array('commonobject')); $parameters = array('listofidcompanytoscan' => $listofidcompanytoscan); - if (!empty($listofidcompanytoscan)) // If empty, we don't have criteria to scan the object we can link to - { + if (!empty($listofidcompanytoscan)) { // If empty, we don't have criteria to scan the object we can link to $reshook = $hookmanager->executeHooks('showLinkToObjectBlock', $parameters, $object, $action); // Note that $action and $object may have been modified by hook } - if (empty($reshook)) - { - if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) - { + if (empty($reshook)) { + if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) { $possiblelinks = array_merge($possiblelinks, $hookmanager->resArray); } - } elseif ($reshook > 0) - { - if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) - { + } elseif ($reshook > 0) { + if (is_array($hookmanager->resArray) && count($hookmanager->resArray)) { $possiblelinks = $hookmanager->resArray; } } - foreach ($possiblelinks as $key => $possiblelink) - { + foreach ($possiblelinks as $key => $possiblelink) { $num = 0; - if (empty($possiblelink['enabled'])) continue; + if (empty($possiblelink['enabled'])) { + continue; + } - if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) - { + if (!empty($possiblelink['perms']) && (empty($restrictlinksto) || in_array($key, $restrictlinksto)) && (empty($excludelinksto) || !in_array($key, $excludelinksto))) { print '
    use_javascript_ajax) ? '' : ' style="display:none"').'>'; $sql = $possiblelink['sql']; $resqllist = $this->db->query($sql); - if ($resqllist) - { + if ($resqllist) { $num = $this->db->num_rows($resqllist); $i = 0; @@ -7284,8 +7684,7 @@ class Form print '
    '.$langs->trans("AmountHTShort").''.$langs->trans("Company").'
    '; - if (!empty($actioncomm->userownerid)) - { - if (isset($cacheusers[$actioncomm->userownerid]) && is_object($cacheusers[$actioncomm->userownerid])) - { + if (!empty($actioncomm->userownerid)) { + if (isset($cacheusers[$actioncomm->userownerid]) && is_object($cacheusers[$actioncomm->userownerid])) { $tmpuser = $cacheusers[$actioncomm->userownerid]; } else { $tmpuser = new User($this->db); $tmpuser->fetch($actioncomm->userownerid); $cacheusers[$actioncomm->userownerid] = $tmpuser; } - if ($tmpuser->id > 0) - { + if ($tmpuser->id > 0) { print $tmpuser->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); } } @@ -276,14 +289,16 @@ class FormActions // Date print ''.dol_print_date($actioncomm->datep, 'dayhour', 'tzuserrel'); - if ($actioncomm->datef) - { + if ($actioncomm->datef) { $tmpa = dol_getdate($actioncomm->datep); $tmpb = dol_getdate($actioncomm->datef); - if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) - { - if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) print '-'.dol_print_date($actioncomm->datef, 'hour', 'tzuserrel'); - } else print '-'.dol_print_date($actioncomm->datef, 'dayhour', 'tzuserrel'); + if ($tmpa['mday'] == $tmpb['mday'] && $tmpa['mon'] == $tmpb['mon'] && $tmpa['year'] == $tmpb['year']) { + if ($tmpa['hours'] != $tmpb['hours'] || $tmpa['minutes'] != $tmpb['minutes'] && $tmpa['seconds'] != $tmpb['seconds']) { + print '-'.dol_print_date($actioncomm->datef, 'hour', 'tzuserrel'); + } + } else { + print '-'.dol_print_date($actioncomm->datef, 'dayhour', 'tzuserrel'); + } } print ''; @@ -297,8 +312,7 @@ class FormActions print '
    '.$langs->trans("None").'
    '.$langs->trans("More").'...
    '.$langs->trans('Margins').''.$langs->trans('SellingPrice').''.$langs->trans('BuyingPrice').''.$langs->trans('CostPrice').''.$langs->trans('CostPrice').''.$langs->trans('Margin').''.$langs->trans('MarginRate').''.$langs->trans('MarkRate').'
    '.$langs->trans('MarginOnProducts').''.price($marginInfo['pv_products']).''.price($marginInfo['pa_products']).''.price($marginInfo['margin_on_products']).''.(($marginInfo['margin_rate_products'] == '') ? '' : price($marginInfo['margin_rate_products'], null, null, null, null, 2).'%').''.(($marginInfo['mark_rate_products'] == '') ? '' : price($marginInfo['mark_rate_products'], null, null, null, null, 2).'%').'
    '.$langs->trans('MarginOnServices').''.price($marginInfo['pv_services']).''.price($marginInfo['pa_services']).''.price($marginInfo['margin_on_services']).''.(($marginInfo['margin_rate_services'] == '') ? '' : price($marginInfo['margin_rate_services'], null, null, null, null, 2).'%').''.(($marginInfo['mark_rate_services'] == '') ? '' : price($marginInfo['mark_rate_services'], null, null, null, null, 2).'%').'
    '.$langs->trans('TotalMargin').''.price($marginInfo['pv_total']).''.price($marginInfo['pa_total']).''.price($marginInfo['total_margin']).''.(($marginInfo['total_margin_rate'] == '') ? '' : price($marginInfo['total_margin_rate'], null, null, null, null, 2).'%').''.(($marginInfo['total_mark_rate'] == '') ? '' : price($marginInfo['total_mark_rate'], null, null, null, null, 2).'%').'
    '; diff --git a/htdocs/core/class/html.formorder.class.php b/htdocs/core/class/html.formorder.class.php index be169106621..9c75d15bae5 100644 --- a/htdocs/core/class/html.formorder.class.php +++ b/htdocs/core/class/html.formorder.class.php @@ -62,8 +62,11 @@ class FormOrder extends Form $options[$value] = $tmpsupplierorder->getLibStatut($short); } - if (is_array($selected)) $selectedarray = $selected; - else $selectedarray = explode(',', $selected); + if (is_array($selected)) { + $selectedarray = $selected; + } else { + $selectedarray = explode(',', $selected); + } print Form::multiselectarray($hmlname, $options, $selectedarray, 0); } diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php index dc6820c56fc..6fee9eb1000 100644 --- a/htdocs/core/class/html.formother.class.php +++ b/htdocs/core/class/html.formother.class.php @@ -76,21 +76,20 @@ class FormOther $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 + 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) - { + if ($result) { print ''; - if ($useempty) - { + if ($useempty) { print ''; } $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $label = $obj->label; @@ -165,8 +162,7 @@ class FormOther $label .= ' ('.$tmpuser->getFullName($langs).')'; } - if ($selected == $obj->rowid) - { + if ($selected == $obj->rowid) { print ''."\n"; - if ($num) - { - while ($i < $num) - { + if ($num) { + while ($i < $num) { $obj = $this->db->fetch_object($resql); - if (($selected && $selected == $obj->taux) || $num == 1) - { + if (($selected && $selected == $obj->taux) || $num == 1) { $out .= ''."\n"; //$moreforfilter .= ''; // Should use -1 to say nothing } - if (is_array($tab_categs)) - { - foreach ($tab_categs as $categ) - { + if (is_array($tab_categs)) { + foreach ($tab_categs as $categ) { $moreforfilter .= ''; } @@ -418,13 +407,11 @@ class FormOther $out = ''; // Enhance with select2 - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { include_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php'; $comboenhancement = ajax_combobox($htmlname); - if ($comboenhancement) - { + if ($comboenhancement) { $out .= $comboenhancement; } } @@ -435,8 +422,12 @@ class FormOther $out .= ''; - if ($useempty) print ''; + if ($useempty) { + print ''; + } $j = 0; $level = 0; $this->_pLineSelect($j, 0, $tasksarray, $level, $selectedtask, $projectid, $disablechildoftaskid); @@ -620,13 +618,15 @@ class FormOther //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 ''; + 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 '
    '; print 'withnotifytiersatcreate ? ' checked="checked"' : '').'>'; print '
    '; print img_picto('', 'project').$formproject->select_projects(-1, GETPOST('projectid', 'int'), 'projectid', 0, 0, 1, 1, 0, 0, 0, '', 1, 0, 'maxwidth500'); @@ -429,14 +428,15 @@ class FormTicket // Other attributes $parameters = array(); $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $ticketstat, $this->action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { print $ticketstat->showOptionals($extrafields, 'create'); } print '
    '; - if ($withdolfichehead) print dol_get_fiche_end(); + if ($withdolfichehead) { + print dol_get_fiche_end(); + } print '
    '; print ''; @@ -761,7 +761,9 @@ class FormTicket // Set tmp user directory $vardir = $conf->user->dir_output."/".$user->id; $upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path - if (is_dir($upload_dir)) dol_delete_dir_recursive($upload_dir); + if (is_dir($upload_dir)) { + dol_delete_dir_recursive($upload_dir); + } $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined unset($_SESSION["listofpaths".$keytoavoidconflict]); @@ -782,23 +784,25 @@ class FormTicket $formmail = new FormMail($this->db); $addfileaction = 'addfile'; - if (!is_object($form)) $form = new Form($this->db); + if (!is_object($form)) { + $form = new Form($this->db); + } // Load translation files required by the page $langs->loadLangs(array('other', 'mails')); // Clear temp files. Must be done at beginning, before call of triggers - if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) - { + if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) { $this->clear_attached_files(); } // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $this->param['langsmodels']; - if (!empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $this->param['langsmodels']; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); $outputlangs->load('other'); @@ -806,11 +810,9 @@ class FormTicket // Get message template for $this->param["models"] into c_email_templates $arraydefaultmessage = -1; - if ($this->param['models'] != 'none') - { + if ($this->param['models'] != 'none') { $model_id = 0; - if (array_key_exists('models_id', $this->param)) - { + if (array_key_exists('models_id', $this->param)) { $model_id = $this->param["models_id"]; } @@ -823,20 +825,23 @@ class FormTicket $listofmimes = array(); $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined - if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) - { - if (!empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit'])) - { - foreach ($this->param['fileinit'] as $file) - { + if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) { + if (!empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit'])) { + foreach ($this->param['fileinit'] as $file) { $this->add_attached_files($file, basename($file), dol_mimetype($file)); } } } - if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]); - if (!empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]); - if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]); + if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) { + $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]); + } + if (!empty($_SESSION["listofnames".$keytoavoidconflict])) { + $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]); + } + if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) { + $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]); + } // Define output language $outputlangs = $langs; @@ -902,8 +907,7 @@ class FormTicket print ''; // External users can't send message email - if ($user->rights->ticket->write && !$user->socid) - { + if ($user->rights->ticket->write && !$user->socid) { print '
    '; $checkbox_selected = (GETPOST('send_email') == "1" ? ' checked' : ''); print ' '; diff --git a/htdocs/core/class/html.formwebsite.class.php b/htdocs/core/class/html.formwebsite.class.php index 8cbb7967415..9f1afab13f7 100644 --- a/htdocs/core/class/html.formwebsite.class.php +++ b/htdocs/core/class/html.formwebsite.class.php @@ -68,21 +68,17 @@ class FormWebsite $sql .= " WHERE 1 = 1"; $sql .= " ORDER BY rowid"; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $out .= ''; - if ($useempty == 1 || ($useempty == 2 && $num > 1)) - { + if ($useempty == 1 || ($useempty == 2 && $num > 1)) { print ''; } - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); - if ($selected == $obj->rowid || $selected == $obj->code) - { + if ($selected == $obj->rowid || $selected == $obj->code) { print '
    '; + } } @@ -514,10 +696,14 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0 $urlregex = ''; // SCHEME - if ($http) $urlregex .= "^(http:\/\/|https:\/\/)"; + if ($http) { + $urlregex .= "^(http:\/\/|https:\/\/)"; + } // USER AND PASS - if ($pass) $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)"; + if ($pass) { + $urlregex .= "([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)"; + } // HOSTNAME OR IP //$urlregex .= "[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*"; // x allowed (ex. http://localhost, http://routerlogin) @@ -526,17 +712,24 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0 //use only one of the above // PORT - if ($port) $urlregex .= "(\:[0-9]{2,5})"; + if ($port) { + $urlregex .= "(\:[0-9]{2,5})"; + } // PATH - if ($path) $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/"; + if ($path) { + $urlregex .= "(\/([a-z0-9+\$_-]\.?)+)*\/"; + } // GET Query - if ($query) $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)"; + if ($query) { + $urlregex .= "(\?[a-z+&\$_.-][a-z0-9;:@\/&%=+\$_.-]*)"; + } // ANCHOR - if ($anchor) $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$"; + if ($anchor) { + $urlregex .= "(#[a-z_.-][a-z0-9+\$_.-]*)$"; + } // check - if (preg_match('/'.$urlregex.'/i', $url)) - { + if (preg_match('/'.$urlregex.'/i', $url)) { $ValidUrl = 1; } //print $urlregex.' - '.$url.' - '.$ValidUrl; @@ -552,16 +745,14 @@ function isValidUrl($url, $http = 0, $pass = 0, $port = 0, $path = 0, $query = 0 */ function isValidVATID($company) { - if ($company->isInEEC()) // Syntax check rules for EEC countries - { + if ($company->isInEEC()) { // Syntax check rules for EEC countries /* Disabled because some companies can have an address in Irland and a vat number in France. - $vatprefix = $company->country_code; - if ($vatprefix == 'GR') $vatprefix = '(EL|GR)'; - elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers - else $vatprefix = preg_quote($vatprefix, '/');*/ + $vatprefix = $company->country_code; + if ($vatprefix == 'GR') $vatprefix = '(EL|GR)'; + elseif ($vatprefix == 'MC') $vatprefix = 'FR'; // Monaco is using french VAT numbers + else $vatprefix = preg_quote($vatprefix, '/');*/ $vatprefix = '[a-zA-Z][a-zA-Z]'; - if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) - { + if (!preg_match('/^'.$vatprefix.'[a-zA-Z0-9\-\.]{5,14}$/i', str_replace(' ', '', $company->tva_intra))) { return 0; } } @@ -582,8 +773,7 @@ function clean_url($url, $http = 1) // To include the minus sign in a char class, we must not escape it but put it at the end of the class // Also, there's no need of escape a dot sign in a class $regs = array(); - if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs)) - { + if (preg_match('/^(https?:[\\/]+)?([0-9A-Z.-]+\.[A-Z]{2,4})(:[0-9]+)?/i', $url, $regs)) { $proto = $regs[1]; $domain = $regs[2]; $port = isset($regs[3]) ? $regs[3] : ''; @@ -593,10 +783,8 @@ function clean_url($url, $http = 1) // Si http: defini on supprime le http (Si https on ne supprime pas) $newproto = $proto; - if ($http == 0) - { - if (preg_match('/^http:[\\/]+/i', $url)) - { + if ($http == 0) { + if (preg_match('/^http:[\\/]+/i', $url)) { $url = preg_replace('/^http:[\\/]+/i', '', $url); $newproto = ''; } @@ -606,7 +794,9 @@ function clean_url($url, $http = 1) $CleanUrl = preg_replace('/^'.preg_quote($proto.$domain, '/').'/i', $newproto.strtolower($domain), $url); return $CleanUrl; - } else return $url; + } else { + return $url; + } } @@ -624,7 +814,9 @@ function clean_url($url, $http = 1) */ function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail = 4, $nbdisplaydomain = 3, $displaytld = true) { - if (!isValidEmail($mail))return ''; + if (!isValidEmail($mail)) { + return ''; + } $tab = explode('@', $mail); $tab2 = explode('.', $tab[1]); $string_replace = ''; @@ -633,8 +825,7 @@ function dolObfuscateEmail($mail, $replace = "*", $nbreplace = 8, $nbdisplaymail $mail_tld = ''; $nbofelem = count($tab2); - for ($i = 1; $i < $nbofelem && $displaytld; $i++) - { + for ($i = 1; $i < $nbofelem && $displaytld; $i++) { $mail_tld .= '.'.$tab2[$i]; } @@ -686,7 +877,9 @@ function array2tr($data, $troptions = '', $tdoptions = '') function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = '', $tdoptions = '') { $text = ''; - if ($tableMarkup) $text = ''; + if ($tableMarkup) { + $text = '
    '; + } foreach ($data as $key => $item) { if (is_array($item)) { $text .= array2tr($item, $troptions, $tdoptions); @@ -697,7 +890,9 @@ function array2table($data, $tableMarkup = 1, $tableoptions = '', $troptions = ' $text .= ''; } } - if ($tableMarkup) $text .= '
    '; + if ($tableMarkup) { + $text .= ''; + } return $text; } @@ -721,15 +916,23 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ { global $conf, $user; - if (!is_object($objsoc)) $valueforccc = $objsoc; - elseif ($table == "commande_fournisseur" || $table == "facture_fourn") $valueforccc = dol_string_unaccent($objsoc->code_fournisseur); - else $valueforccc = dol_string_unaccent($objsoc->code_client); + if (!is_object($objsoc)) { + $valueforccc = $objsoc; + } elseif ($table == "commande_fournisseur" || $table == "facture_fourn") { + $valueforccc = dol_string_unaccent($objsoc->code_fournisseur); + } else { + $valueforccc = dol_string_unaccent($objsoc->code_client); + } $sharetable = $table; - if ($table == 'facture' || $table == 'invoice') $sharetable = 'invoicenumber'; // for getEntity function + if ($table == 'facture' || $table == 'invoice') { + $sharetable = 'invoicenumber'; // for getEntity function + } // Clean parameters - if ($date == '') $date = dol_now(); // We use local year and month of PHP server to search numbers + if ($date == '') { + $date = dol_now(); // We use local year and month of PHP server to search numbers + } // but we should use local year and month of user // For debugging @@ -742,8 +945,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $hasglobalcounter = false; $reg = array(); // Extract value for mask counter, mask raz and mask offset - if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg)) - { + if (preg_match('/\{(0+)([@\+][0-9\-\+\=]+)?([@\+][0-9\-\+\=]+)?\}/i', $mask, $reg)) { $masktri = $reg[1].(!empty($reg[2]) ? $reg[2] : '').(!empty($reg[3]) ? $reg[3] : ''); $maskcounter = $reg[1]; $hasglobalcounter = true; @@ -756,12 +958,13 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskraz = -1; $maskoffset = 0; $resetEveryMonth = false; - if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) return 'ErrorCounterMustHaveMoreThan3Digits'; + if (dol_strlen($maskcounter) < 3 && empty($conf->global->MAIN_COUNTER_WITH_LESS_3_DIGITS)) { + return 'ErrorCounterMustHaveMoreThan3Digits'; + } // Extract value for third party mask counter $regClientRef = array(); - if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) - { + if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) { $maskrefclient = $regClientRef[1].$regClientRef[2]; $maskrefclient_maskclientcode = $regClientRef[1]; $maskrefclient_maskcounter = $regClientRef[2]; @@ -769,19 +972,21 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskrefclient_clientcode = substr($valueforccc, 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code where n is length in mask $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like - if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits'; - } else $maskrefclient = ''; + if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) { + return 'ErrorCounterMustHaveMoreThan3Digits'; + } + } else { + $maskrefclient = ''; + } // fail if there is neither a global nor a third party counter - if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) - { + if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) { return 'ErrorBadMask'; } // Extract value for third party type $regType = array(); - if (preg_match('/\{(t+)\}/i', $mask, $regType)) - { + if (preg_match('/\{(t+)\}/i', $mask, $regType)) { $masktype = $regType[1]; $masktype_value = substr(preg_replace('/^TE_/', '', $objsoc->typent_code), 0, dol_strlen($regType[1])); // get n first characters of thirdpaty typent_code (where n is length in mask) $masktype_value = str_pad($masktype_value, dol_strlen($regType[1]), "#", STR_PAD_RIGHT); // we fill on right with # to have same number of char than into mask @@ -791,10 +996,12 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } // Extract value for user - $regType = array(); + $regType = array(); if (preg_match('/\{(u+)\}/i', $mask, $regType)) { $lastname = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; - if (is_object($objuser)) $lastname = $objuser->lastname; + if (is_object($objuser)) { + $lastname = $objuser->lastname; + } $maskuser = $regType[1]; $maskuser_value = substr($lastname, 0, dol_strlen($regType[1])); // get n first characters of user firstname (where n is length in mask) @@ -809,15 +1016,13 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskpersonew = array(); $tmpmask = $mask; $regKey = array(); - while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey)) - { + while (preg_match('/\{([A-Z]+)\-([1-9])\}/', $tmpmask, $regKey)) { $maskperso[$regKey[1]] = '{'.$regKey[1].'-'.$regKey[2].'}'; $maskpersonew[$regKey[1]] = str_pad('', $regKey[2], '_', STR_PAD_RIGHT); $tmpmask = preg_replace('/\{'.$regKey[1].'\-'.$regKey[2].'\}/i', $maskpersonew[$regKey[1]], $tmpmask); } - if (strstr($mask, 'user_extra_')) - { + if (strstr($mask, 'user_extra_')) { $start = "{user_extra_"; $end = "\}"; $extra = get_string_between($mask, "user_extra_", "}"); @@ -831,8 +1036,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskwithonlyymcode = preg_replace('/\{(c+)(0*)\}/i', $maskrefclient, $maskwithonlyymcode); $maskwithonlyymcode = preg_replace('/\{(t+)\}/i', $masktype_value, $maskwithonlyymcode); $maskwithonlyymcode = preg_replace('/\{(u+)\}/i', $maskuser_value, $maskwithonlyymcode); - foreach ($maskperso as $key => $val) - { + foreach ($maskperso as $key => $val) { $maskwithonlyymcode = preg_replace('/'.preg_quote($val, '/').'/i', $maskpersonew[$key], $maskwithonlyymcode); } $maskwithnocode = $maskwithonlyymcode; @@ -846,8 +1050,12 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ //var_dump($reg); // If an offset is asked - if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]); - if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) { + $maskoffset = preg_replace('/^\+/', '', $reg[2]); + } + if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) { + $maskoffset = preg_replace('/^\+/', '', $reg[3]); + } // Define $sqlwhere $sqlwhere = ''; @@ -855,14 +1063,19 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $yearoffsettype = false; // false: no reset, 0,-,=,+: reset at offset SOCIETE_FISCAL_MONTH_START, x=reset at offset x // If a restore to zero after a month is asked we check if there is already a value for this year. - if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) $yearoffsettype = preg_replace('/^@/', '', $reg[2]); - if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) $yearoffsettype = preg_replace('/^@/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) { + $yearoffsettype = preg_replace('/^@/', '', $reg[2]); + } + if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) { + $yearoffsettype = preg_replace('/^@/', '', $reg[3]); + } //print "yearoffset=".$yearoffset." yearoffsettype=".$yearoffsettype; - if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) + if (is_numeric($yearoffsettype) && $yearoffsettype >= 1) { $maskraz = $yearoffsettype; // For backward compatibility - elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) + } elseif ($yearoffsettype === '0' || (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $conf->global->SOCIETE_FISCAL_MONTH_START > 1)) { $maskraz = $conf->global->SOCIETE_FISCAL_MONTH_START; + } //print "maskraz=".$maskraz; // -1=no reset if ($maskraz > 0) { // A reset is required @@ -870,27 +1083,44 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskraz = date('m', $date); $resetEveryMonth = true; } - if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth'; + if ($maskraz > 12) { + return 'ErrorBadMaskBadRazMonth'; + } // Define posy, posm and reg - if ($maskraz > 1) // if reset is not first month, we need month and year into mask - { - if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; } else return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; + if ($maskraz > 1) { // if reset is not first month, we need month and year into mask + if (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 2; $posm = 3; + } elseif (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 3; $posm = 2; + } else { + return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; + } - if (dol_strlen($reg[$posy]) < 2) return 'ErrorCantUseRazWithYearOnOneDigit'; + if (dol_strlen($reg[$posy]) < 2) { + return 'ErrorCantUseRazWithYearOnOneDigit'; + } } else // if reset is for a specific month in year, we need year { - if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 3; $posm = 2; } elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 3; } elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { $posy = 2; $posm = 0; } else return 'ErrorCantUseRazIfNoYearInMask'; + if (preg_match('/^(.*)\{(m+)\}\{(y+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 3; $posm = 2; + } elseif (preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 2; $posm = 3; + } elseif (preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { + $posy = 2; $posm = 0; + } else { + return 'ErrorCantUseRazIfNoYearInMask'; + } } // Define length $yearlen = $posy ?dol_strlen($reg[$posy]) : 0; $monthlen = $posm ?dol_strlen($reg[$posm]) : 0; // Define pos - $yearpos = (dol_strlen($reg[1]) + 1); + $yearpos = (dol_strlen($reg[1]) + 1); $monthpos = ($yearpos + $yearlen); if ($posy == 3 && $posm == 2) { // if month is before year - $monthpos = (dol_strlen($reg[1]) + 1); - $yearpos = ($monthpos + $monthlen); + $monthpos = (dol_strlen($reg[1]) + 1); + $yearpos = ($monthpos + $monthlen); } //print "xxx ".$maskwithonlyymcode." maskraz=".$maskraz." posy=".$posy." yearlen=".$yearlen." yearpos=".$yearpos." posm=".$posm." monthlen=".$monthlen." monthpos=".$monthpos." yearoffsettype=".$yearoffsettype." resetEveryMonth=".$resetEveryMonth."\n"; @@ -898,8 +1128,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $monthcomp = $maskraz; $yearcomp = 0; - if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') // $yearoffsettype is - or + - { + if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // $yearoffsettype is - or + $currentyear = date("Y", $date); $fiscaldate = dol_mktime('0', '0', '0', $maskraz, '1', $currentyear); $newyeardate = dol_mktime('0', '0', '0', '1', '1', $currentyear); @@ -907,22 +1136,33 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ //echo 'currentyear='.$currentyear.' date='.dol_print_date($date, 'day').' fiscaldate='.dol_print_date($fiscaldate, 'day').'
    '; // If after or equal of current fiscal date - if ($date >= $fiscaldate) - { + if ($date >= $fiscaldate) { // If before of next new year date - if ($date < $nextnewyeardate && $yearoffsettype == '+') $yearoffset = 1; + if ($date < $nextnewyeardate && $yearoffsettype == '+') { + $yearoffset = 1; + } } // If after or equal of current new year date - elseif ($date >= $newyeardate && $yearoffsettype == '-') $yearoffset = -1; + elseif ($date >= $newyeardate && $yearoffsettype == '-') { + $yearoffset = -1; + } } // For backward compatibility - elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) { $yearoffset = -1; } // If current month lower that month of return to zero, year is previous year + elseif (date("m", $date) < $maskraz && empty($resetEveryMonth)) { + $yearoffset = -1; + } // If current month lower that month of return to zero, year is previous year - if ($yearlen == 4) $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset); - elseif ($yearlen == 2) $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset); - elseif ($yearlen == 1) $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset; - if ($monthcomp > 1 && empty($resetEveryMonth)) // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0) - { - if ($yearlen == 4) $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1); - elseif ($yearlen == 2) $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1); + if ($yearlen == 4) { + $yearcomp = sprintf("%04d", date("Y", $date) + $yearoffset); + } elseif ($yearlen == 2) { + $yearcomp = sprintf("%02d", date("y", $date) + $yearoffset); + } elseif ($yearlen == 1) { + $yearcomp = substr(date("y", $date), 2, 1) + $yearoffset; + } + if ($monthcomp > 1 && empty($resetEveryMonth)) { // Test with month is useless if monthcomp = 0 or 1 (0 is same as 1) (regis: $monthcomp can't equal 0) + if ($yearlen == 4) { + $yearcomp1 = sprintf("%04d", date("Y", $date) + $yearoffset + 1); + } elseif ($yearlen == 2) { + $yearcomp1 = sprintf("%02d", date("y", $date) + $yearoffset + 1); + } $sqlwhere .= "("; $sqlwhere .= " (SUBSTRING(".$field.", ".$yearpos.", ".$yearlen.") = '".$db->escape($yearcomp)."'"; @@ -947,7 +1187,9 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } else { $posnumstart = strrpos($maskwithnocode, $maskcounter); } // Pos of counter in final string (from 0 to ...) - if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence'; + if ($posnumstart < 0) { + return 'ErrorBadMaskFailedToLocatePosOfSequence'; + } $sqlstring = 'SUBSTRING('.$field.', '.($posnumstart + 1).', '.dol_strlen($maskcounter).')'; // Define $maskLike @@ -961,11 +1203,16 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike); $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike); $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), str_pad("", dol_strlen($maskcounter), "_"), $maskLike); - if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike); - if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike); - if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike); - foreach ($maskperso as $key => $val) - { + if ($maskrefclient) { + $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike); + } + if ($masktype) { + $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike); + } + if ($maskuser) { + $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike); + } + foreach ($maskperso as $key => $val) { $maskLike = str_replace(dol_string_nospecial($maskperso[$key]), $maskpersonew[$key], $maskLike); } @@ -975,32 +1222,39 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $sql .= " FROM ".MAIN_DB_PREFIX.$table; $sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike)."'"; $sql .= " AND ".$field." NOT LIKE '(PROV%)'"; - if ($bentityon) // only if entity enable + if ($bentityon) { // only if entity enable $sql .= " AND entity IN (".getEntity($sharetable).")"; - elseif (!empty($forceentity)) + } elseif (!empty($forceentity)) { $sql .= " AND entity IN (".$forceentity.")"; - if ($where) $sql .= $where; - if ($sqlwhere) $sql .= ' AND '.$sqlwhere; + } + if ($where) { + $sql .= $where; + } + if ($sqlwhere) { + $sql .= ' AND '.$sqlwhere; + } //print $sql.'
    '; dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $counter = $obj->val; - } else dol_print_error($db); + } else { + dol_print_error($db); + } // Check if we must force counter to maskoffset - if (empty($counter)) $counter = $maskoffset; - elseif (preg_match('/[^0-9]/i', $counter)) - { + if (empty($counter)) { + $counter = $maskoffset; + } elseif (preg_match('/[^0-9]/i', $counter)) { $counter = 0; dol_syslog("Error, the last counter found is '".$counter."' so is not a numeric value. We will restart to 1.", LOG_ERR); - } elseif ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) $counter = $maskoffset; + } elseif ($counter < $maskoffset && empty($conf->global->MAIN_NUMBERING_OFFSET_ONLY_FOR_FIRST)) { + $counter = $maskoffset; + } - if ($mode == 'last') // We found value for counter = last counter value. Now need to get corresponding ref of invoice. - { + if ($mode == 'last') { // We found value for counter = last counter value. Now need to get corresponding ref of invoice. $counterpadded = str_pad($counter, dol_strlen($maskcounter), "0", STR_PAD_LEFT); // Define $maskLike @@ -1013,47 +1267,61 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskLike = preg_replace('/\{mm\}/i', '__', $maskLike); $maskLike = preg_replace('/\{dd\}/i', '__', $maskLike); $maskLike = str_replace(dol_string_nospecial('{'.$masktri.'}'), $counterpadded, $maskLike); - if ($maskrefclient) $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike); - if ($masktype) $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike); - if ($maskuser) $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike); + if ($maskrefclient) { + $maskLike = str_replace(dol_string_nospecial('{'.$maskrefclient.'}'), str_pad("", dol_strlen($maskrefclient), "_"), $maskLike); + } + if ($masktype) { + $maskLike = str_replace(dol_string_nospecial('{'.$masktype.'}'), $masktype_value, $maskLike); + } + if ($maskuser) { + $maskLike = str_replace(dol_string_nospecial('{'.$maskuser.'}'), $maskuser_value, $maskLike); + } $ref = ''; $sql = "SELECT ".$field." as ref"; $sql .= " FROM ".MAIN_DB_PREFIX.$table; $sql .= " WHERE ".$field." LIKE '".$db->escape($maskLike)."'"; $sql .= " AND ".$field." NOT LIKE '%PROV%'"; - if ($bentityon) // only if entity enable + if ($bentityon) { // only if entity enable $sql .= " AND entity IN (".getEntity($sharetable).")"; - elseif (!empty($forceentity)) + } elseif (!empty($forceentity)) { $sql .= " AND entity IN (".$forceentity.")"; - if ($where) $sql .= $where; - if ($sqlwhere) $sql .= ' AND '.$sqlwhere; + } + if ($where) { + $sql .= $where; + } + if ($sqlwhere) { + $sql .= ' AND '.$sqlwhere; + } dol_syslog("functions2::get_next_value mode=".$mode."", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $ref = $obj->ref; - } else dol_print_error($db); + if ($obj) { + $ref = $obj->ref; + } + } else { + dol_print_error($db); + } $numFinal = $ref; } elseif ($mode == 'next') { $counter++; // If value for $counter has a length higher than $maskcounter chars - if ($counter >= pow(10, dol_strlen($maskcounter))) - { + if ($counter >= pow(10, dol_strlen($maskcounter))) { $counter = 'ErrorMaxNumberReachForThisMask'; } - if (!empty($maskrefclient_maskcounter)) - { + if (!empty($maskrefclient_maskcounter)) { //print "maskrefclient_maskcounter=".$maskrefclient_maskcounter." maskwithnocode=".$maskwithnocode." maskrefclient=".$maskrefclient."\n
    "; // Define $sqlstring $maskrefclient_posnumstart = strpos($maskwithnocode, $maskrefclient_maskcounter, strpos($maskwithnocode, $maskrefclient)); // Pos of counter in final string (from 0 to ...) - if ($maskrefclient_posnumstart <= 0) return 'ErrorBadMask'; + if ($maskrefclient_posnumstart <= 0) { + return 'ErrorBadMask'; + } $maskrefclient_sqlstring = 'SUBSTRING('.$field.', '.($maskrefclient_posnumstart + 1).', '.dol_strlen($maskrefclient_maskcounter).')'; //print "x".$sqlstring; @@ -1075,23 +1343,31 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $maskrefclient_sql .= " FROM ".MAIN_DB_PREFIX.$table; //$sql.= " WHERE ".$field." not like '(%'"; $maskrefclient_sql .= " WHERE ".$field." LIKE '".$db->escape($maskrefclient_maskLike)."'"; - if ($bentityon) // only if entity enable + if ($bentityon) { // only if entity enable $maskrefclient_sql .= " AND entity IN (".getEntity($sharetable).")"; - elseif (!empty($forceentity)) + } elseif (!empty($forceentity)) { $sql .= " AND entity IN (".$forceentity.")"; - if ($where) $maskrefclient_sql .= $where; //use the same optional where as general mask - if ($sqlwhere) $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask + } + if ($where) { + $maskrefclient_sql .= $where; //use the same optional where as general mask + } + if ($sqlwhere) { + $maskrefclient_sql .= ' AND '.$sqlwhere; //use the same sqlwhere as general mask + } $maskrefclient_sql .= ' AND (SUBSTRING('.$field.', '.(strpos($maskwithnocode, $maskrefclient) + 1).', '.dol_strlen($maskrefclient_maskclientcode).")='".$db->escape($maskrefclient_clientcode)."')"; dol_syslog("functions2::get_next_value maskrefclient", LOG_DEBUG); $maskrefclient_resql = $db->query($maskrefclient_sql); - if ($maskrefclient_resql) - { + if ($maskrefclient_resql) { $maskrefclient_obj = $db->fetch_object($maskrefclient_resql); $maskrefclient_counter = $maskrefclient_obj->val; - } else dol_print_error($db); + } else { + dol_print_error($db); + } - if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) $maskrefclient_counter = $maskrefclient_maskoffset; + if (empty($maskrefclient_counter) || preg_match('/[^0-9]/i', $maskrefclient_counter)) { + $maskrefclient_counter = $maskrefclient_maskoffset; + } $maskrefclient_counter++; } @@ -1099,8 +1375,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $numFinal = $mask; // We replace special codes except refclient - if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') // yearoffsettype is - or +, so we don't want current year - { + if (!empty($yearoffsettype) && !is_numeric($yearoffsettype) && $yearoffsettype != '=') { // yearoffsettype is - or +, so we don't want current year $numFinal = preg_replace('/\{yyyy\}/i', date("Y", $date) + $yearoffset, $numFinal); $numFinal = preg_replace('/\{yy\}/i', date("y", $date) + $yearoffset, $numFinal); $numFinal = preg_replace('/\{y\}/i', substr(date("y", $date), 1, 1) + $yearoffset, $numFinal); @@ -1120,8 +1395,7 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ $numFinal = str_replace($maskbefore, $maskafter, $numFinal); // Now we replace the refclient - if ($maskrefclient) - { + if ($maskrefclient) { //print "maskrefclient=".$maskrefclient." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskrefclient_clientcode=".$maskrefclient_clientcode."\n
    ";exit; $maskrefclient_maskbefore = '{'.$maskrefclient.'}'; $maskrefclient_maskafter = $maskrefclient_clientcode.str_pad($maskrefclient_counter, dol_strlen($maskrefclient_maskcounter), "0", STR_PAD_LEFT); @@ -1129,16 +1403,14 @@ function get_next_value($db, $mask, $table, $field, $where = '', $objsoc = '', $ } // Now we replace the type - if ($masktype) - { + if ($masktype) { $masktype_maskbefore = '{'.$masktype.'}'; $masktype_maskafter = $masktype_value; $numFinal = str_replace($masktype_maskbefore, $masktype_maskafter, $numFinal); } // Now we replace the user - if ($maskuser) - { + if ($maskuser) { $maskuser_maskbefore = '{'.$maskuser.'}'; $maskuser_maskafter = $maskuser_value; $numFinal = str_replace($maskuser_maskbefore, $maskuser_maskafter, $numFinal); @@ -1161,7 +1433,9 @@ function get_string_between($string, $start, $end) { $string = " ".$string; $ini = strpos($string, $start); - if ($ini == 0) return ""; + if ($ini == 0) { + return ""; + } $ini += strlen($start); $len = strpos($string, $end, $ini) - $ini; return substr($string, $ini, $len); @@ -1192,12 +1466,13 @@ function check_value($mask, $value) } $maskraz = -1; $maskoffset = 0; - if (dol_strlen($maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits'; + if (dol_strlen($maskcounter) < 3) { + return 'ErrorCounterMustHaveMoreThan3Digits'; + } // Extract value for third party mask counter $regClientRef = array(); - if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) - { + if (preg_match('/\{(c+)(0*)\}/i', $mask, $regClientRef)) { $maskrefclient = $regClientRef[1].$regClientRef[2]; $maskrefclient_maskclientcode = $regClientRef[1]; $maskrefclient_maskcounter = $regClientRef[2]; @@ -1205,12 +1480,15 @@ function check_value($mask, $value) $maskrefclient_clientcode = substr('', 0, dol_strlen($maskrefclient_maskclientcode)); //get n first characters of client code to form maskrefclient_clientcode $maskrefclient_clientcode = str_pad($maskrefclient_clientcode, dol_strlen($maskrefclient_maskclientcode), "#", STR_PAD_RIGHT); //padding maskrefclient_clientcode for having exactly n characters in maskrefclient_clientcode $maskrefclient_clientcode = dol_string_nospecial($maskrefclient_clientcode); //sanitize maskrefclient_clientcode for sql insert and sql select like - if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) return 'ErrorCounterMustHaveMoreThan3Digits'; - } else $maskrefclient = ''; + if (dol_strlen($maskrefclient_maskcounter) > 0 && dol_strlen($maskrefclient_maskcounter) < 3) { + return 'ErrorCounterMustHaveMoreThan3Digits'; + } + } else { + $maskrefclient = ''; + } // fail if there is neither a global nor a third party counter - if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) - { + if (!$hasglobalcounter && ($maskrefclient_maskcounter == '')) { return 'ErrorBadMask'; } @@ -1228,46 +1506,62 @@ function check_value($mask, $value) //print "maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode."\n
    "; // If an offset is asked - if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) $maskoffset = preg_replace('/^\+/', '', $reg[2]); - if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) $maskoffset = preg_replace('/^\+/', '', $reg[3]); + if (!empty($reg[2]) && preg_match('/^\+/', $reg[2])) { + $maskoffset = preg_replace('/^\+/', '', $reg[2]); + } + if (!empty($reg[3]) && preg_match('/^\+/', $reg[3])) { + $maskoffset = preg_replace('/^\+/', '', $reg[3]); + } // Define $sqlwhere // If a restore to zero after a month is asked we check if there is already a value for this year. - if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) $maskraz = preg_replace('/^@/', '', $reg[2]); - if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) $maskraz = preg_replace('/^@/', '', $reg[3]); - if ($maskraz >= 0) - { + if (!empty($reg[2]) && preg_match('/^@/', $reg[2])) { + $maskraz = preg_replace('/^@/', '', $reg[2]); + } + if (!empty($reg[3]) && preg_match('/^@/', $reg[3])) { + $maskraz = preg_replace('/^@/', '', $reg[3]); + } + if ($maskraz >= 0) { if ($maskraz == 99) { $maskraz = date('m'); $resetEveryMonth = true; } - if ($maskraz > 12) return 'ErrorBadMaskBadRazMonth'; + if ($maskraz > 12) { + return 'ErrorBadMaskBadRazMonth'; + } // Define reg - if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; - if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) return 'ErrorCantUseRazIfNoYearInMask'; + if ($maskraz > 1 && !preg_match('/^(.*)\{(y+)\}\{(m+)\}/i', $maskwithonlyymcode, $reg)) { + return 'ErrorCantUseRazInStartedYearIfNoYearMonthInMask'; + } + if ($maskraz <= 1 && !preg_match('/^(.*)\{(y+)\}/i', $maskwithonlyymcode, $reg)) { + return 'ErrorCantUseRazIfNoYearInMask'; + } //print "x".$maskwithonlyymcode." ".$maskraz; } //print "masktri=".$masktri." maskcounter=".$maskcounter." maskwithonlyymcode=".$maskwithonlyymcode." maskwithnocode=".$maskwithnocode." maskraz=".$maskraz." maskoffset=".$maskoffset."
    \n"; if (function_exists('mb_strrpos')) { $posnumstart = mb_strrpos($maskwithnocode, $maskcounter, 0, 'UTF-8'); - } - else { + } else { $posnumstart = strrpos($maskwithnocode, $maskcounter); } // Pos of counter in final string (from 0 to ...) - if ($posnumstart < 0) return 'ErrorBadMaskFailedToLocatePosOfSequence'; + if ($posnumstart < 0) { + return 'ErrorBadMaskFailedToLocatePosOfSequence'; + } // Check we have a number in $value at position ($posnumstart+1).', '.dol_strlen($maskcounter) // TODO - // Check length - $len = dol_strlen($maskwithnocode); - if (dol_strlen($value) != $len) $result = -1; + // Check length + $len = dol_strlen($maskwithnocode); + if (dol_strlen($value) != $len) { + $result = -1; + } - dol_syslog("functions2::check_value result=".$result, LOG_DEBUG); - return $result; + dol_syslog("functions2::check_value result=".$result, LOG_DEBUG); + return $result; } /** @@ -1281,10 +1575,18 @@ function check_value($mask, $value) function binhex($bin, $pad = false, $upper = false) { $last = dol_strlen($bin) - 1; - for ($i = 0; $i <= $last; $i++) { $x += $bin[$last - $i] * pow(2, $i); } + for ($i = 0; $i <= $last; $i++) { + $x += $bin[$last - $i] * pow(2, $i); + } $x = dechex($x); - if ($pad) { while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) { $x = "0$x"; } } - if ($upper) { $x = strtoupper($x); } + if ($pad) { + while (dol_strlen($x) < intval(dol_strlen($bin)) / 4) { + $x = "0$x"; + } + } + if ($upper) { + $x = strtoupper($x); + } return $x; } @@ -1298,8 +1600,7 @@ function hexbin($hexa) { $bin = ''; $strLength = dol_strlen($hexa); - for ($i = 0; $i < $strLength; $i++) - { + for ($i = 0; $i < $strLength; $i++) { $bin .= str_pad(decbin(hexdec($hexa[$i])), 4, '0', STR_PAD_LEFT); } return $bin; @@ -1315,8 +1616,7 @@ function numero_semaine($time) { $stime = strftime('%Y-%m-%d', $time); - if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg)) - { + if (preg_match('/^([0-9]+)\-([0-9]+)\-([0-9]+)\s?([0-9]+)?:?([0-9]+)?/i', $stime, $reg)) { // Date est au format 'YYYY-MM-DD' ou 'YYYY-MM-DD HH:MM:SS' $annee = $reg[1]; $mois = $reg[2]; @@ -1324,31 +1624,29 @@ function numero_semaine($time) } /* - * Norme ISO-8601: - * - La semaine 1 de toute annee est celle qui contient le 4 janvier ou que la semaine 1 de toute annee est celle qui contient le 1er jeudi de janvier. - * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53. - * - Le 1er jour de la semaine est le Lundi - */ + * Norme ISO-8601: + * - La semaine 1 de toute annee est celle qui contient le 4 janvier ou que la semaine 1 de toute annee est celle qui contient le 1er jeudi de janvier. + * - La majorite des annees ont 52 semaines mais les annees qui commence un jeudi et les annees bissextiles commencant un mercredi en possede 53. + * - Le 1er jour de la semaine est le Lundi + */ // Definition du Jeudi de la semaine - if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) // Dimanche - $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60; - elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) // du Lundi au Mercredi - $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60; - elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) // du Vendredi au Samedi - $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60; - else // Jeudi - $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee); + if (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) == 0) { // Dimanche + $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - 3 * 24 * 60 * 60; + } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) < 4) { // du Lundi au Mercredi + $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) + (4 - date("w", mktime(12, 0, 0, $mois, $jour, $annee))) * 24 * 60 * 60; + } elseif (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) > 4) { // du Vendredi au Samedi + $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee) - (date("w", mktime(12, 0, 0, $mois, $jour, $annee)) - 4) * 24 * 60 * 60; + } else { // Jeudi + $jeudiSemaine = mktime(12, 0, 0, $mois, $jour, $annee); + } // Definition du premier Jeudi de l'annee - if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) // Dimanche - { + if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 0) { // Dimanche $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + 4 * 24 * 60 * 60; - } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) // du Lundi au Mercredi - { + } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) < 4) { // du Lundi au Mercredi $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (4 - date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)))) * 24 * 60 * 60; - } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) // du Vendredi au Samedi - { + } elseif (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) > 4) { // du Vendredi au Samedi $premierJeudiAnnee = mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine)) + (7 - (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) - 4)) * 24 * 60 * 60; } else // Jeudi { @@ -1365,11 +1663,9 @@ function numero_semaine($time) ) + 1; // Cas particulier de la semaine 53 - if ($numeroSemaine == 53) - { + if ($numeroSemaine == 53) { // Les annees qui commence un Jeudi et les annees bissextiles commencant un Mercredi en possede 53 - if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365)) - { + if (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 4 || (date("w", mktime(12, 0, 0, 1, 1, date("Y", $jeudiSemaine))) == 3 && date("z", mktime(12, 0, 0, 12, 31, date("Y", $jeudiSemaine))) == 365)) { $numeroSemaine = 53; } else { $numeroSemaine = 1; @@ -1392,20 +1688,17 @@ function numero_semaine($time) function weight_convert($weight, &$from_unit, $to_unit) { /* Pour convertire 320 gr en Kg appeler - * $f = -3 - * weigh_convert(320, $f, 0) retournera 0.32 - * - */ - while ($from_unit <> $to_unit) - { - if ($from_unit > $to_unit) - { + * $f = -3 + * weigh_convert(320, $f, 0) retournera 0.32 + * + */ + while ($from_unit <> $to_unit) { + if ($from_unit > $to_unit) { $weight = $weight * 10; $from_unit = $from_unit - 1; $weight = weight_convert($weight, $from_unit, $to_unit); } - if ($from_unit < $to_unit) - { + if ($from_unit < $to_unit) { $weight = $weight / 10; $from_unit = $from_unit + 1; $weight = weight_convert($weight, $from_unit, $to_unit); @@ -1429,7 +1722,9 @@ function weight_convert($weight, &$from_unit, $to_unit) function dol_set_user_param($db, $conf, &$user, $tab) { // Verification parametres - if (count($tab) < 1) return -1; + if (count($tab) < 1) { + return -1; + } $db->begin(); @@ -1439,9 +1734,10 @@ function dol_set_user_param($db, $conf, &$user, $tab) $sql .= " AND entity = ".$conf->entity; $sql .= " AND param in ("; $i = 0; - foreach ($tab as $key => $value) - { - if ($i > 0) $sql .= ','; + foreach ($tab as $key => $value) { + if ($i > 0) { + $sql .= ','; + } $sql .= "'".$db->escape($key)."'"; $i++; } @@ -1449,26 +1745,22 @@ function dol_set_user_param($db, $conf, &$user, $tab) dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); $db->rollback(); return -1; } - foreach ($tab as $key => $value) - { + foreach ($tab as $key => $value) { // Set new parameters - if ($value) - { + if ($value) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."user_param(fk_user,entity,param,value)"; $sql .= " VALUES (".$user->id.",".$conf->entity.","; $sql .= " '".$db->escape($key)."','".$db->escape($value)."')"; dol_syslog("functions2.lib::dol_set_user_param", LOG_DEBUG); $result = $db->query($sql); - if (!$result) - { + if (!$result) { dol_print_error($db); $db->rollback(); return -1; @@ -1494,8 +1786,7 @@ function dol_set_user_param($db, $conf, &$user, $tab) function dol_print_reduction($reduction, $langs) { $string = ''; - if ($reduction == 100) - { + if ($reduction == 100) { $string = $langs->transnoentities("Offered"); } else { $string = vatrate($reduction, true); @@ -1513,8 +1804,11 @@ function dol_print_reduction($reduction, $langs) */ function version_os($option = '') { - if ($option == 'smr') $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r'); - else $osversion = php_uname(); + if ($option == 'smr') { + $osversion = php_uname('s').' '.php_uname('m').' '.php_uname('r'); + } else { + $osversion = php_uname(); + } return $osversion; } @@ -1573,20 +1867,17 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) dol_syslog('/core/lib/function2.lib.php::getListOfModels', LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $found = 1; $obj = $db->fetch_object($resql); // If this generation module needs to scan a directory, then description field is filled // with the constant that contains list of directories to scan (COMPANY_ADDON_PDF_ODT_PATH, ...). - if (!empty($obj->description)) // A list of directories to scan is defined - { + if (!empty($obj->description)) { // A list of directories to scan is defined include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $const = $obj->description; @@ -1597,23 +1888,23 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) // Now we add models found in directories scanned $listofdir = explode(',', $dirtoscan); - foreach ($listofdir as $key=>$tmpdir) - { + foreach ($listofdir as $key => $tmpdir) { $tmpdir = trim($tmpdir); $tmpdir = preg_replace('/DOL_DATA_ROOT/', DOL_DATA_ROOT, $tmpdir); - if (!$tmpdir) { unset($listofdir[$key]); continue; } - if (is_dir($tmpdir)) - { + if (!$tmpdir) { + unset($listofdir[$key]); continue; + } + if (is_dir($tmpdir)) { // all type of template is allowed $tmpfiles = dol_dir_list($tmpdir, 'files', 0, '', '', 'name', SORT_ASC, 0); - if (count($tmpfiles)) $listoffiles = array_merge($listoffiles, $tmpfiles); + if (count($tmpfiles)) { + $listoffiles = array_merge($listoffiles, $tmpfiles); + } } } - if (count($listoffiles)) - { - foreach ($listoffiles as $record) - { + if (count($listoffiles)) { + foreach ($listoffiles as $record) { $max = ($maxfilenamelength ? $maxfilenamelength : 28); $liste[$obj->id.':'.$record['fullname']] = dol_trunc($record['name'], $max, 'middle'); } @@ -1621,12 +1912,10 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) $liste[0] = $obj->label.': '.$langs->trans("None"); } } else { - if ($type == 'member' && $obj->doc_template_name == 'standard') // Special case, if member template, we add variant per format - { + if ($type == 'member' && $obj->doc_template_name == 'standard') { // Special case, if member template, we add variant per format global $_Avery_Labels; include_once DOL_DOCUMENT_ROOT.'/core/lib/format_cards.lib.php'; - foreach ($_Avery_Labels as $key => $val) - { + foreach ($_Avery_Labels as $key => $val) { $liste[$obj->id.':'.$key] = ($obj->label ? $obj->label : $obj->doc_template_name).' '.$val['name']; } } else { @@ -1641,8 +1930,11 @@ function getListOfModels($db, $type, $maxfilenamelength = 0) return -1; } - if ($found) return $liste; - else return 0; + if ($found) { + return $liste; + } else { + return 0; + } } /** @@ -1657,10 +1949,14 @@ function is_ip($ip) // First we test if it is a valid IPv4 if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { // Then we test if it is a private range - if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) return 2; + if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE)) { + return 2; + } // Then we test if it is a reserved range - if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) return 0; + if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE)) { + return 0; + } return 1; } @@ -1715,8 +2011,7 @@ function getSoapParams() $timeout = (empty($conf->global->MAIN_USE_CONNECT_TIMEOUT) ? 10 : $conf->global->MAIN_USE_CONNECT_TIMEOUT); // Connection timeout $response_timeout = (empty($conf->global->MAIN_USE_RESPONSE_TIMEOUT) ? 30 : $conf->global->MAIN_USE_RESPONSE_TIMEOUT); // Response timeout //print extension_loaded('soap'); - if ($proxyuse) - { + if ($proxyuse) { $params = array('connection_timeout'=>$timeout, 'response_timeout'=>$response_timeout, 'proxy_use' => 1, @@ -1761,12 +2056,10 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') if (preg_match('/^([^@]+)@([^@]+)$/i', $objecttype, $regs)) { $myobject = $regs[1]; $module = $regs[2]; - } - else { + } else { // Parse $objecttype (ex: project_task) $module = $myobject = $objecttype; - if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) { $module = $regs[1]; $myobject = $regs[2]; } @@ -1844,26 +2137,21 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') $classname = 'CommandeFournisseur'; $classpath = 'fourn/class'; $module = 'fournisseur'; - } - elseif ($objecttype == 'supplier_proposal') { + } elseif ($objecttype == 'supplier_proposal') { $classfile = 'supplier_proposal'; $classname = 'SupplierProposal'; $classpath = 'supplier_proposal/class'; $module = 'supplier_proposal'; - } - elseif ($objecttype == 'stock') { + } elseif ($objecttype == 'stock') { $classpath = 'product/stock/class'; $classfile = 'entrepot'; $classname = 'Entrepot'; } - if (!empty($conf->$module->enabled)) - { + if (!empty($conf->$module->enabled)) { $res = dol_include_once('/'.$classpath.'/'.$classfile.'.class.php'); - if ($res) - { - if (class_exists($classname)) - { + if ($res) { + if (class_exists($classname)) { $object = new $classname($db); $res = $object->fetch($objectid); if ($res > 0) { @@ -1872,7 +2160,9 @@ function dolGetElementUrl($objectid, $objecttype, $withpicto = 0, $option = '') $ret = $langs->trans('Deleted'); } unset($object); - } else dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR); + } else { + dol_syslog("Class with classname ".$classname." is unknown even after the include", LOG_ERR); + } } } return $ret; @@ -1896,33 +2186,30 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) // Get list of all id in array listofid and all parents in array listofparentid $sql = 'SELECT rowid, '.$fieldfkparent.' as parent_id FROM '.MAIN_DB_PREFIX.$tabletocleantree; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $listofid[] = $obj->rowid; - if ($obj->parent_id > 0) $listofparentid[$obj->rowid] = $obj->parent_id; + if ($obj->parent_id > 0) { + $listofparentid[$obj->rowid] = $obj->parent_id; + } $i++; } } else { dol_print_error($db); } - if (count($listofid)) - { + if (count($listofid)) { print 'Code requested to clean tree (may be to solve data corruption), so we check/clean orphelins and loops.'."
    \n"; // Check loops on each other $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree." SET ".$fieldfkparent." = 0 WHERE ".$fieldfkparent." = rowid"; // So we update only records linked to themself $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $nb = $db->affected_rows($sql); - if ($nb > 0) - { + if ($nb > 0) { print '
    Some record that were parent of themself were cleaned.'; } @@ -1932,17 +2219,14 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) // Check other loops $listofidtoclean = array(); - foreach ($listofparentid as $id => $pid) - { + foreach ($listofparentid as $id => $pid) { // Check depth //print 'Analyse record id='.$id.' with parent '.$pid.'
    '; $cursor = $id; $arrayidparsed = array(); // We start from child $id - while ($cursor > 0) - { + while ($cursor > 0) { $arrayidparsed[$cursor] = 1; - if ($arrayidparsed[$listofparentid[$cursor]]) // We detect a loop. A record with a parent that was already into child - { + if ($arrayidparsed[$listofparentid[$cursor]]) { // We detect a loop. A record with a parent that was already into child print 'Found a loop between id '.$id.' - '.$cursor.'
    '; unset($arrayidparsed); $listofidtoclean[$cursor] = $id; @@ -1951,18 +2235,18 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) $cursor = $listofparentid[$cursor]; } - if (count($listofidtoclean)) break; + if (count($listofidtoclean)) { + break; + } } $sql = "UPDATE ".MAIN_DB_PREFIX.$tabletocleantree; $sql .= " SET ".$fieldfkparent." = 0"; $sql .= " WHERE rowid IN (".join(',', $listofidtoclean).")"; // So we update only records detected wrong $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $nb = $db->affected_rows($sql); - if ($nb > 0) - { + if ($nb > 0) { // Removed orphelins records print '
    Some records were detected to have parent that is a child, we set them as root record for id: '; print join(',', $listofidtoclean); @@ -1977,11 +2261,9 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) $sql .= " SET ".$fieldfkparent." = 0"; $sql .= " WHERE ".$fieldfkparent." NOT IN (".join(',', $listofid).")"; // So we update only records linked to a non existing parent $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $nb = $db->affected_rows($sql); - if ($nb > 0) - { + if ($nb > 0) { // Removed orphelins records print '
    Some orphelins were found and modified to be parent so records are visible again for id: '; print join(',', $listofid); @@ -2008,8 +2290,12 @@ function cleanCorruptedTree($db, $tabletocleantree, $fieldfkparent) */ function colorArrayToHex($arraycolor, $colorifnotfound = '888888') { - if (!is_array($arraycolor)) return $colorifnotfound; - if (empty($arraycolor)) return $colorifnotfound; + if (!is_array($arraycolor)) { + return $colorifnotfound; + } + if (empty($arraycolor)) { + return $colorifnotfound; + } return sprintf("%02s", dechex($arraycolor[0])).sprintf("%02s", dechex($arraycolor[1])).sprintf("%02s", dechex($arraycolor[2])); } @@ -2025,13 +2311,16 @@ function colorArrayToHex($arraycolor, $colorifnotfound = '888888') */ function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88)) { - if (is_array($stringcolor)) return $stringcolor; // If already into correct output format, we return as is + if (is_array($stringcolor)) { + return $stringcolor; // If already into correct output format, we return as is + } $reg = array(); $tmp = preg_match('/^#?([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/', $stringcolor, $reg); - if (!$tmp) - { + if (!$tmp) { $tmp = explode(',', $stringcolor); - if (count($tmp) < 3) return $colorifnotfound; + if (count($tmp) < 3) { + return $colorifnotfound; + } return $tmp; } return array(hexdec($reg[1]), hexdec($reg[2]), hexdec($reg[3])); @@ -2044,10 +2333,11 @@ function colorStringToArray($stringcolor, $colorifnotfound = array(88, 88, 88)) */ function colorValidateHex($color, $allow_white = true) { - if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) return false; + if (!$allow_white && ($color === '#fff' || $color === '#ffffff')) { + return false; + } - if (preg_match('/^#[a-f0-9]{6}$/i', $color)) //hex color is valid - { + if (preg_match('/^#[a-f0-9]{6}$/i', $color)) { //hex color is valid return true; } return false; @@ -2064,7 +2354,9 @@ function colorValidateHex($color, $allow_white = true) */ function colorAgressiveness($hex, $ratio = -50, $brightness = 0) { - if (empty($ratio)) $ratio = 0; // To avoid null + if (empty($ratio)) { + $ratio = 0; // To avoid null + } // Steps should be between -255 and 255. Negative = darker, positive = lighter $ratio = max(-100, min(100, $ratio)); @@ -2081,17 +2373,23 @@ function colorAgressiveness($hex, $ratio = -50, $brightness = 0) foreach ($color_parts as $color) { $color = hexdec($color); // Convert to decimal - if ($ratio > 0) // We increase aggressivity - { - if ($color > 127) $color += ((255 - $color) * ($ratio / 100)); - if ($color < 128) $color -= ($color * ($ratio / 100)); + if ($ratio > 0) { // We increase aggressivity + if ($color > 127) { + $color += ((255 - $color) * ($ratio / 100)); + } + if ($color < 128) { + $color -= ($color * ($ratio / 100)); + } } else // We decrease agressiveness { - if ($color > 128) $color -= (($color - 128) * (abs($ratio) / 100)); - if ($color < 127) $color += ((128 - $color) * (abs($ratio) / 100)); + if ($color > 128) { + $color -= (($color - 128) * (abs($ratio) / 100)); + } + if ($color < 127) { + $color += ((128 - $color) * (abs($ratio) / 100)); + } } - if ($brightness > 0) - { + if ($brightness > 0) { $color = ($color * (100 + abs($brightness)) / 100); } else { $color = ($color * (100 - abs($brightness)) / 100); @@ -2228,7 +2526,9 @@ function cartesianArray(array $input) function getModuleDirForApiClass($moduleobject) { $moduledirforclass = $moduleobject; - if ($moduledirforclass != 'api') $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass); + if ($moduledirforclass != 'api') { + $moduledirforclass = preg_replace('/api$/i', '', $moduledirforclass); + } if ($moduleobject == 'contracts') { $moduledirforclass = 'contrat'; @@ -2298,8 +2598,7 @@ function randomColor($min = 0, $max = 255) } -if (!function_exists('dolEscapeXML')) -{ +if (!function_exists('dolEscapeXML')) { /** * Encode string for xml usage * @@ -2325,25 +2624,40 @@ function autoOrManual($automaticmanual, $case = 1, $color = 0) { global $langs; $result = 'unknown'; $classname = ''; - if ($automaticmanual == 1 || strtolower($automaticmanual) == 'automatic' || strtolower($automaticmanual) == 'true') // A mettre avant test sur no a cause du == 0 - { + if ($automaticmanual == 1 || strtolower($automaticmanual) == 'automatic' || strtolower($automaticmanual) == 'true') { // A mettre avant test sur no a cause du == 0 $result = $langs->trans('automatic'); - if ($case == 1 || $case == 3) $result = $langs->trans("Automatic"); - if ($case == 2) $result = ''; - if ($case == 3) $result = ' '.$result; + if ($case == 1 || $case == 3) { + $result = $langs->trans("Automatic"); + } + if ($case == 2) { + $result = ''; + } + if ($case == 3) { + $result = ' '.$result; + } $classname = 'ok'; - } elseif ($automaticmanual == 0 || strtolower($automaticmanual) == 'manual' || strtolower($automaticmanual) == 'false') - { + } elseif ($automaticmanual == 0 || strtolower($automaticmanual) == 'manual' || strtolower($automaticmanual) == 'false') { $result = $langs->trans("manual"); - if ($case == 1 || $case == 3) $result = $langs->trans("Manual"); - if ($case == 2) $result = ''; - if ($case == 3) $result = ' '.$result; + if ($case == 1 || $case == 3) { + $result = $langs->trans("Manual"); + } + if ($case == 2) { + $result = ''; + } + if ($case == 3) { + $result = ' '.$result; + } - if ($color == 2) $classname = 'ok'; - else $classname = 'error'; + if ($color == 2) { + $classname = 'ok'; + } else { + $classname = 'error'; + } + } + if ($color) { + return ''.$result.''; } - if ($color) return ''.$result.''; return $result; } @@ -2378,7 +2692,9 @@ function price2fec($amount) global $conf; // Clean parameters - if (empty($amount)) $amount = 0; // To have a numeric value if amount not defined or = '' + if (empty($amount)) { + $amount = 0; // To have a numeric value if amount not defined or = '' + } $amount = (is_numeric($amount) ? $amount : 0); // Check if amount is numeric, for example, an error occured when amount value = o (letter) instead 0 (number) // Output decimal number by default @@ -2402,9 +2718,15 @@ function price2fec($amount) */ function phpSyntaxError($code) { - if (!defined("CR")) define("CR", "\r"); - if (!defined("LF")) define("LF", "\n"); - if (!defined("CRLF")) define("CRLF", "\r\n"); + if (!defined("CR")) { + define("CR", "\r"); + } + if (!defined("LF")) { + define("LF", "\n"); + } + if (!defined("CRLF")) { + define("CRLF", "\r\n"); + } $braces = 0; $inString = 0; @@ -2413,27 +2735,39 @@ function phpSyntaxError($code) switch ($token[0]) { case T_CURLY_OPEN: case T_DOLLAR_OPEN_CURLY_BRACES: - case T_START_HEREDOC: ++$inString; break; - case T_END_HEREDOC: --$inString; break; + case T_START_HEREDOC: + ++$inString; + break; + case T_END_HEREDOC: + --$inString; + break; } } elseif ($inString & 1) { switch ($token) { case '`': case '\'': - case '"': --$inString; break; + case '"': + --$inString; + break; } } else { switch ($token) { case '`': case '\'': - case '"': ++$inString; break; - case '{': ++$braces; break; + case '"': + ++$inString; + break; + case '{': + ++$braces; + break; case '}': if ($inString) { --$inString; } else { --$braces; - if ($braces < 0) break 2; + if ($braces < 0) { + break 2; + } } break; } @@ -2458,7 +2792,9 @@ function phpSyntaxError($code) $code = $code[2] <= $braces ? array($code[1], $code[2]) : array('unexpected $end'.substr($code[1], 14), $braces); - } else $code = array('syntax error', 0); + } else { + $code = array('syntax error', 0); + } } else { ob_end_clean(); $code = false; diff --git a/htdocs/core/lib/functions_ch.lib.php b/htdocs/core/lib/functions_ch.lib.php index 04e74837853..cb683ceec1f 100644 --- a/htdocs/core/lib/functions_ch.lib.php +++ b/htdocs/core/lib/functions_ch.lib.php @@ -158,8 +158,7 @@ function dol_ch_controle_bvrb($bvrb) // Make control $report = 0; - while (dol_strlen($bv) > 1) - { + while (dol_strlen($bv) > 1) { $match = substr($bv, 0, 1); $report = $tableau[$report][$match]; $bv = substr($bv, 1); diff --git a/htdocs/core/lib/functionsnumtoword.lib.php b/htdocs/core/lib/functionsnumtoword.lib.php index 930c6d06a9e..6de1e69de1f 100644 --- a/htdocs/core/lib/functionsnumtoword.lib.php +++ b/htdocs/core/lib/functionsnumtoword.lib.php @@ -142,10 +142,14 @@ function dol_convertToWord($num, $langs, $currency = '', $centimes = false) $decimalpart = empty($TNum[1]) ? '' : preg_replace('/0+$/', '', $TNum[1]); if ($decimalpart) { - if (!empty($currency)) $concatWords .= ' '.$langs->transnoentities('and'); + if (!empty($currency)) { + $concatWords .= ' '.$langs->transnoentities('and'); + } $concatWords .= ' '.dol_convertToWord($decimalpart, $langs, '', true); - if (!empty($currency)) $concatWords .= ' '.$langs->transnoentities('centimes'); + if (!empty($currency)) { + $concatWords .= ' '.$langs->transnoentities('centimes'); + } } return $concatWords; } @@ -164,7 +168,9 @@ function dol_convertToWord($num, $langs, $currency = '', $centimes = false) function dolNumberToWord($numero, $langs, $numorcurrency = 'number') { // If the number is negative convert to positive and return -1 if it is too long - if ($numero < 0) $numero *= -1; + if ($numero < 0) { + $numero *= -1; + } if ($numero >= 1000000000001) { return -1; } @@ -172,8 +178,7 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number') // Get 2 decimals to cents, another functions round or truncate $strnumber = number_format($numero, 10); $len = strlen($strnumber); - for ($i = 0; $i < $len; $i++) - { + for ($i = 0; $i < $len; $i++) { if ($strnumber[$i] == '.') { $parte_decimal = $strnumber[$i + 1].$strnumber[$i + 2]; break; @@ -182,8 +187,7 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number') /*In dolibarr 3.6.2 (my current version) doesn't have $langs->default and in case exist why ask $lang like a parameter?*/ - if (((is_object($langs) && $langs->default == 'es_MX') || (!is_object($langs) && $langs == 'es_MX')) && $numorcurrency == 'currency') - { + if (((is_object($langs) && $langs->default == 'es_MX') || (!is_object($langs) && $langs == 'es_MX')) && $numorcurrency == 'currency') { if ($numero >= 1 && $numero < 2) { return ("UN PESO ".$parte_decimal." / 100 M.N."); } elseif ($numero >= 0 && $numero < 1) { @@ -213,9 +217,11 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number') $udMILLON = (int) ($numero / 1000000); $numero = $numero - $udMILLON * 1000000; $entexto .= hundreds2text($CdMILLON, $DdMILLON, $udMILLON); - if (!$CdMMillon && !$DdMMillon && !$UdMMillon && !$CdMILLON && !$DdMILLON && $udMILLON == 1) + if (!$CdMMillon && !$DdMMillon && !$UdMMillon && !$CdMILLON && !$DdMILLON && $udMILLON == 1) { $entexto .= " MILLÓN "; - else $entexto .= " MILLONES "; + } else { + $entexto .= " MILLONES "; + } } if ($number >= 1000) { $cdm = (int) ($numero / 100000); @@ -225,16 +231,18 @@ function dolNumberToWord($numero, $langs, $numorcurrency = 'number') $udm = (int) ($numero / 1000); $numero = $numero - $udm * 1000; $entexto .= hundreds2text($cdm, $ddm, $udm); - if ($cdm || $ddm || $udm) + if ($cdm || $ddm || $udm) { $entexto .= " MIL "; + } } $c = (int) ($numero / 100); $numero = $numero - $c * 100; $d = (int) ($numero / 10); $u = (int) $numero - $d * 10; $entexto .= hundreds2text($c, $d, $u); - if (!$cdm && !$ddm && !$udm && !$c && !$d && !$u && $number > 1000000) + if (!$cdm && !$ddm && !$udm && !$c && !$d && !$u && $number > 1000000) { $entexto .= " DE"; + } $entexto .= " PESOS ".$parte_decimal." / 100 M.N."; } return $entexto; @@ -264,7 +272,9 @@ function hundreds2text($hundreds, $tens, $units) $entexto .= $centenas[$hundreds - 1]; } if ($tens > 2) { - if ($hundreds != 0) $entexto .= " "; + if ($hundreds != 0) { + $entexto .= " "; + } $entexto .= $decenas[$tens - 1]; if ($units != 0) { $entexto .= " Y "; @@ -272,16 +282,22 @@ function hundreds2text($hundreds, $tens, $units) } return $entexto; } elseif ($tens == 2) { - if ($hundreds != 0) $entexto .= " "; + if ($hundreds != 0) { + $entexto .= " "; + } $entexto .= " ".$veintis[$units]; return $entexto; } elseif ($tens == 1) { - if ($hundreds != 0) $entexto .= " "; + if ($hundreds != 0) { + $entexto .= " "; + } $entexto .= $diecis[$units]; return $entexto; } if ($units != 0) { - if ($hundreds != 0 || $tens != 0) $entexto .= " "; + if ($hundreds != 0 || $tens != 0) { + $entexto .= " "; + } $entexto .= $unidades[$units - 1]; } return $entexto; diff --git a/htdocs/core/lib/geturl.lib.php b/htdocs/core/lib/geturl.lib.php index 7e93623f3c1..d624e2e0ace 100644 --- a/htdocs/core/lib/geturl.lib.php +++ b/htdocs/core/lib/geturl.lib.php @@ -51,9 +51,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = $ch = curl_init(); /*print $API_Endpoint."-".$API_version."-".$PAYPAL_API_USER."-".$PAYPAL_API_PASSWORD."-".$PAYPAL_API_SIGNATURE."
    "; - print $USE_PROXY."-".$gv_ApiErrorURL."
    "; - print $nvpStr; - exit;*/ + print $USE_PROXY."-".$gv_ApiErrorURL."
    "; + print $nvpStr; + exit;*/ curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_USERAGENT, 'Dolibarr geturl function'); @@ -61,12 +61,16 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = // We force value to false so we will manage redirection ourself later. @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); - if (is_array($addheaders) && count($addheaders)) curl_setopt($ch, CURLOPT_HTTPHEADER, $addheaders); + if (is_array($addheaders) && count($addheaders)) { + curl_setopt($ch, CURLOPT_HTTPHEADER, $addheaders); + } curl_setopt($ch, CURLINFO_HEADER_OUT, true); // To be able to retrieve request header and log it // By default use tls decied by PHP. // You can force, if supported a version like TLSv1 or TLSv1.2 - if (!empty($conf->global->MAIN_CURL_SSLVERSION)) curl_setopt($ch, CURLOPT_SSLVERSION, $conf->global->MAIN_CURL_SSLVERSION); + if (!empty($conf->global->MAIN_CURL_SSLVERSION)) { + curl_setopt($ch, CURLOPT_SSLVERSION, $conf->global->MAIN_CURL_SSLVERSION); + } //curl_setopt($ch, CURLOPT_SSLVERSION, 6); for tls 1.2 // Turning off the server and peer verification(TrustManager Concept). @@ -77,8 +81,12 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = $protocols = 0; if (is_array($allowedschemes)) { foreach ($allowedschemes as $allowedscheme) { - if ($allowedscheme == 'http') $protocols |= CURLPROTO_HTTP; - if ($allowedscheme == 'https') $protocols |= CURLPROTO_HTTPS; + if ($allowedscheme == 'http') { + $protocols |= CURLPROTO_HTTP; + } + if ($allowedscheme == 'https') { + $protocols |= CURLPROTO_HTTPS; + } } curl_setopt($ch, CURLOPT_PROTOCOLS, $protocols); curl_setopt($ch, CURLOPT_REDIR_PROTOCOLS, $protocols); @@ -98,8 +106,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = } elseif ($postorget == 'PUT') { $array_param = null; curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // HTTP request is 'PUT' - if (!is_array($param)) parse_str($param, $array_param); - else { + if (!is_array($param)) { + parse_str($param, $array_param); + } else { dol_syslog("parameter param must be a string", LOG_WARNING); $array_param = $param; } @@ -121,7 +130,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = dol_syslog("getURLContent set proxy to ".$PROXY_HOST.":".$PROXY_PORT." - ".$PROXY_USER.":".$PROXY_PASS); //curl_setopt ($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); // Curl 7.10 curl_setopt($ch, CURLOPT_PROXY, $PROXY_HOST.":".$PROXY_PORT); - if ($PROXY_USER) curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS); + if ($PROXY_USER) { + curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_USER.":".$PROXY_PASS); + } } $newUrl = $url; @@ -130,7 +141,9 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = $response = ''; do { - if ($maxRedirection < 1) break; + if ($maxRedirection < 1) { + break; + } curl_setopt($ch, CURLOPT_URL, $newUrl); @@ -185,8 +198,7 @@ function getURLContent($url, $postorget = 'GET', $param = '', $followlocation = } else { $http_code = 0; } - } - while ($http_code); + } while ($http_code); $request = curl_getinfo($ch, CURLINFO_HEADER_OUT); // Reading of request must be done after sending request @@ -263,7 +275,9 @@ function getRootURLFromURL($url) $prefix = ''; $tmpurl = $url; $reg = null; - if (preg_match('/^(https?:\/\/)/i', $tmpurl, $reg)) $prefix = $reg[1]; + if (preg_match('/^(https?:\/\/)/i', $tmpurl, $reg)) { + $prefix = $reg[1]; + } $tmpurl = preg_replace('/^https?:\/\//i', '', $tmpurl); // Remove http(s):// $tmpurl = preg_replace('/\/.*$/i', '', $tmpurl); // Remove part after domain diff --git a/htdocs/core/lib/holiday.lib.php b/htdocs/core/lib/holiday.lib.php index 7b9c5d46da2..4f6da9f6d51 100644 --- a/htdocs/core/lib/holiday.lib.php +++ b/htdocs/core/lib/holiday.lib.php @@ -47,7 +47,9 @@ function holiday_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/holiday/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; diff --git a/htdocs/core/lib/images.lib.php b/htdocs/core/lib/images.lib.php index bd392760cc5..ed7d5b1efcc 100644 --- a/htdocs/core/lib/images.lib.php +++ b/htdocs/core/lib/images.lib.php @@ -47,23 +47,41 @@ function image_format_supported($file, $acceptsvg = 0) // Case filename is not a format image $reg = array(); - if (!preg_match('/('.$regeximgext.')$/i', $file, $reg)) return -1; + if (!preg_match('/('.$regeximgext.')$/i', $file, $reg)) { + return -1; + } // Case filename is a format image but not supported by this PHP $imgfonction = ''; - if (strtolower($reg[1]) == '.gif') $imgfonction = 'imagecreatefromgif'; - if (strtolower($reg[1]) == '.jpg') $imgfonction = 'imagecreatefromjpeg'; - if (strtolower($reg[1]) == '.jpeg') $imgfonction = 'imagecreatefromjpeg'; - if (strtolower($reg[1]) == '.png') $imgfonction = 'imagecreatefrompng'; - if (strtolower($reg[1]) == '.bmp') $imgfonction = 'imagecreatefromwbmp'; - if (strtolower($reg[1]) == '.webp') $imgfonction = 'imagecreatefromwebp'; - if (strtolower($reg[1]) == '.xpm') $imgfonction = 'imagecreatefromxpm'; - if (strtolower($reg[1]) == '.xbm') $imgfonction = 'imagecreatefromxbm'; - if (strtolower($reg[1]) == '.svg') $imgfonction = 'imagecreatefromsvg'; // Never available - if ($imgfonction) - { - if (!function_exists($imgfonction)) - { + if (strtolower($reg[1]) == '.gif') { + $imgfonction = 'imagecreatefromgif'; + } + if (strtolower($reg[1]) == '.jpg') { + $imgfonction = 'imagecreatefromjpeg'; + } + if (strtolower($reg[1]) == '.jpeg') { + $imgfonction = 'imagecreatefromjpeg'; + } + if (strtolower($reg[1]) == '.png') { + $imgfonction = 'imagecreatefrompng'; + } + if (strtolower($reg[1]) == '.bmp') { + $imgfonction = 'imagecreatefromwbmp'; + } + if (strtolower($reg[1]) == '.webp') { + $imgfonction = 'imagecreatefromwebp'; + } + if (strtolower($reg[1]) == '.xpm') { + $imgfonction = 'imagecreatefromxpm'; + } + if (strtolower($reg[1]) == '.xbm') { + $imgfonction = 'imagecreatefromxbm'; + } + if (strtolower($reg[1]) == '.svg') { + $imgfonction = 'imagecreatefromsvg'; // Never available + } + if ($imgfonction) { + if (!function_exists($imgfonction)) { // Fonctions of conversion not available in this PHP return 0; } @@ -87,16 +105,16 @@ function dol_getImageSize($file, $url = false) { $ret = array(); - if (image_format_supported($file) < 0) return $ret; + if (image_format_supported($file) < 0) { + return $ret; + } $filetoread = $file; - if (!$url) - { + if (!$url) { $filetoread = realpath(dol_osencode($file)); // Chemin canonique absolu de l'image } - if ($filetoread) - { + if ($filetoread) { $infoImg = getimagesize($filetoread); // Recuperation des infos de l'image $ret['width'] = $infoImg[0]; // Largeur de l'image $ret['height'] = $infoImg[1]; // Hauteur de l'image @@ -129,25 +147,19 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $file = trim($file); // Check parameters - if (!$file) - { + if (!$file) { // Si le fichier n'a pas ete indique return 'Bad parameter file'; - } elseif (!file_exists($file)) - { + } elseif (!file_exists($file)) { // Si le fichier passe en parametre n'existe pas return $langs->trans("ErrorFileNotFound", $file); - } elseif (image_format_supported($file) < 0) - { + } elseif (image_format_supported($file) < 0) { return 'This filename '.$file.' does not seem to be an image filename.'; - } elseif (!is_numeric($newWidth) && !is_numeric($newHeight)) - { + } elseif (!is_numeric($newWidth) && !is_numeric($newHeight)) { return 'Wrong value for parameter newWidth or newHeight'; - } elseif ($mode == 0 && $newWidth <= 0 && $newHeight <= 0) - { + } elseif ($mode == 0 && $newWidth <= 0 && $newHeight <= 0) { return 'At least newHeight or newWidth must be defined for resizing'; - } elseif ($mode == 1 && ($newWidth <= 0 || $newHeight <= 0)) - { + } elseif ($mode == 1 && ($newWidth <= 0 || $newHeight <= 0)) { return 'Both newHeight or newWidth must be defined for croping'; } @@ -157,21 +169,17 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $imgWidth = $infoImg[0]; // Largeur de l'image $imgHeight = $infoImg[1]; // Hauteur de l'image - if ($mode == 0) // If resize, we check parameters - { - if ($newWidth <= 0) - { + if ($mode == 0) { // If resize, we check parameters + if ($newWidth <= 0) { $newWidth = intval(($newHeight / $imgHeight) * $imgWidth); // Keep ratio } - if ($newHeight <= 0) - { + if ($newHeight <= 0) { $newHeight = intval(($newWidth / $imgWidth) * $imgHeight); // Keep ratio } } $imgfonction = ''; - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case 1: // IMG_GIF $imgfonction = 'imagecreatefromgif'; break; @@ -188,18 +196,15 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $imgfonction = 'imagecreatefromwebp'; break; } - if ($imgfonction) - { - if (!function_exists($imgfonction)) - { + if ($imgfonction) { + if (!function_exists($imgfonction)) { // Fonctions de conversion non presente dans ce PHP return 'Resize not possible. This PHP does not support GD functions '.$imgfonction; } } // Initialisation des variables selon l'extension de l'image - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case 1: // Gif $img = imagecreatefromgif($filetoread); $extImg = '.gif'; // File name extension of image @@ -228,8 +233,7 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, } // Create empty image - if ($infoImg[2] == 1) - { + if ($infoImg[2] == 1) { // Compatibilite image GIF $imgThumb = imagecreate($newWidth, $newHeight); } else { @@ -237,20 +241,17 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, } // Activate antialiasing for better quality - if (function_exists('imageantialias')) - { + if (function_exists('imageantialias')) { imageantialias($imgThumb, true); } // This is to keep transparent alpha channel if exists (PHP >= 4.2) - if (function_exists('imagesavealpha')) - { + if (function_exists('imagesavealpha')) { imagesavealpha($imgThumb, true); } // Initialisation des variables selon l'extension de l'image - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case 1: // Gif $trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF imagecolortransparent($imgThumb, $trans_colour); @@ -269,7 +270,9 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, $trans_colour = imagecolorallocatealpha($imgThumb, 255, 255, 255, 127); break; } - if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour); + if (function_exists("imagefill")) { + imagefill($imgThumb, 0, 0, $trans_colour); + } dol_syslog("dol_imageResizeOrCrop: convert image from ($imgWidth x $imgHeight) at position ($src_x x $src_y) to ($newWidth x $newHeight) as $extImg, newquality=$newquality"); //imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee @@ -282,8 +285,7 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, //fclose($fp); // Create image on disk - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case 1: // Gif imagegif($imgThumb, $imgThumbName); break; @@ -302,7 +304,9 @@ function dol_imageResizeOrCrop($file, $mode, $newWidth, $newHeight, $src_x = 0, } // Set permissions on file - if (!empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK)); + if (!empty($conf->global->MAIN_UMASK)) { + @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK)); + } // Free memory. This does not delete image. imagedestroy($img); @@ -359,8 +363,7 @@ function correctExifImageOrientation($fileSource, $fileDest, $quality = 95) break; } if ($deg) { - if ($infoImg[2] === 'IMAGETYPE_PNG') // In fact there is no exif on PNG but just in case - { + if ($infoImg[2] === 'IMAGETYPE_PNG') { // In fact there is no exif on PNG but just in case imagealphablending($img, false); imagesavealpha($img, true); $img = imagerotate($img, $deg, imageColorAllocateAlpha($img, 0, 0, 0, 127)); @@ -378,8 +381,7 @@ function correctExifImageOrientation($fileSource, $fileDest, $quality = 95) // Create image on disk $image = false; - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case IMAGETYPE_GIF: // 1 $image = imagegif($img, $fileDest); break; @@ -434,17 +436,14 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $file = trim($file); // Check parameters - if (!$file) - { + if (!$file) { // Si le fichier n'a pas ete indique return 'ErrorBadParameters'; - } elseif (!file_exists($file)) - { + } elseif (!file_exists($file)) { // Si le fichier passe en parametre n'existe pas dol_syslog($langs->trans("ErrorFileNotFound", $file), LOG_ERR); return $langs->trans("ErrorFileNotFound", $file); - } elseif (image_format_supported($file) < 0) - { + } elseif (image_format_supported($file) < 0) { dol_syslog('This file '.$file.' does not seem to be an image format file name.', LOG_WARNING); return 'ErrorBadImageFormat'; } elseif (!is_numeric($maxWidth) || empty($maxWidth) || $maxWidth < -1) { @@ -471,20 +470,22 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } } - if ($maxWidth == -1) $maxWidth = $infoImg[0]; // If size is -1, we keep unchanged - if ($maxHeight == -1) $maxHeight = $infoImg[1]; // If size is -1, we keep unchanged + if ($maxWidth == -1) { + $maxWidth = $infoImg[0]; // If size is -1, we keep unchanged + } + if ($maxHeight == -1) { + $maxHeight = $infoImg[1]; // If size is -1, we keep unchanged + } // Si l'image est plus petite que la largeur et la hauteur max, on ne cree pas de vignette - if ($infoImg[0] < $maxWidth && $infoImg[1] < $maxHeight) - { + if ($infoImg[0] < $maxWidth && $infoImg[1] < $maxHeight) { // On cree toujours les vignettes dol_syslog("File size is smaller than thumb size", LOG_DEBUG); //return 'Le fichier '.$file.' ne necessite pas de creation de vignette'; } $imgfonction = ''; - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case IMAGETYPE_GIF: // 1 $imgfonction = 'imagecreatefromgif'; break; @@ -501,10 +502,8 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $imgfonction = 'imagecreatefromwbmp'; break; } - if ($imgfonction) - { - if (!function_exists($imgfonction)) - { + if ($imgfonction) { + if (!function_exists($imgfonction)) { // Fonctions de conversion non presente dans ce PHP return 'Error: Creation of thumbs not possible. This PHP does not support GD function '.$imgfonction; } @@ -516,8 +515,7 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', // Initialisation des variables selon l'extension de l'image $img = null; - switch ($infoImg[2]) - { + switch ($infoImg[2]) { case IMAGETYPE_GIF: // 1 $img = imagecreatefromgif($filetoread); $extImg = '.gif'; // Extension de l'image @@ -540,16 +538,14 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', break; } - if (!is_resource($img)) - { + if (!is_resource($img)) { dol_syslog('Failed to detect type of image. We found infoImg[2]='.$infoImg[2], LOG_WARNING); return 0; } $exifAngle = false; if ($ort && !empty($conf->global->MAIN_USE_EXIF_ROTATION)) { - switch ($ort) - { + switch ($ort) { case 3: // 180 rotate left $exifAngle = 180; break; @@ -568,12 +564,10 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } } - if ($exifAngle) - { + if ($exifAngle) { $rotated = false; - if ($infoImg[2] === 'IMAGETYPE_PNG') // In fact there is no exif on PNG but just in case - { + if ($infoImg[2] === 'IMAGETYPE_PNG') { // In fact there is no exif on PNG but just in case imagealphablending($img, false); imagesavealpha($img, true); $rotated = imagerotate($img, $exifAngle, imageColorAllocateAlpha($img, 0, 0, 0, 127)); @@ -592,15 +586,18 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } // Initialisation des dimensions de la vignette si elles sont superieures a l'original - if ($maxWidth > $imgWidth) { $maxWidth = $imgWidth; } - if ($maxHeight > $imgHeight) { $maxHeight = $imgHeight; } + if ($maxWidth > $imgWidth) { + $maxWidth = $imgWidth; + } + if ($maxHeight > $imgHeight) { + $maxHeight = $imgHeight; + } $whFact = $maxWidth / $maxHeight; // Facteur largeur/hauteur des dimensions max de la vignette $imgWhFact = $imgWidth / $imgHeight; // Facteur largeur/hauteur de l'original // Fixe les dimensions de la vignette - if ($whFact < $imgWhFact) - { + if ($whFact < $imgWhFact) { // Si largeur determinante $thumbWidth = $maxWidth; $thumbHeight = $thumbWidth / $imgWhFact; @@ -613,11 +610,12 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $thumbWidth = round($thumbWidth); // Define target format - if (empty($targetformat)) $targetformat = $infoImg[2]; + if (empty($targetformat)) { + $targetformat = $infoImg[2]; + } // Create empty image - if ($targetformat == IMAGETYPE_GIF) - { + if ($targetformat == IMAGETYPE_GIF) { // Compatibilite image GIF $imgThumb = imagecreate($thumbWidth, $thumbHeight); } else { @@ -625,21 +623,18 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } // Activate antialiasing for better quality - if (function_exists('imageantialias')) - { + if (function_exists('imageantialias')) { imageantialias($imgThumb, true); } // This is to keep transparent alpha channel if exists (PHP >= 4.2) - if (function_exists('imagesavealpha')) - { + if (function_exists('imagesavealpha')) { imagesavealpha($imgThumb, true); } // Initialisation des variables selon l'extension de l'image // $targetformat is 0 by default, in such case, we keep original extension - switch ($targetformat) - { + switch ($targetformat) { case IMAGETYPE_GIF: // 1 $trans_colour = imagecolorallocate($imgThumb, 255, 255, 255); // On procede autrement pour le format GIF imagecolortransparent($imgThumb, $trans_colour); @@ -669,7 +664,9 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', $newquality = 'NU'; break; } - if (function_exists("imagefill")) imagefill($imgThumb, 0, 0, $trans_colour); + if (function_exists("imagefill")) { + imagefill($imgThumb, 0, 0, $trans_colour); + } dol_syslog("vignette: convert image from ($imgWidth x $imgHeight) to ($thumbWidth x $thumbHeight) as $extImg, newquality=$newquality"); //imagecopyresized($imgThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $imgWidth, $imgHeight); // Insere l'image de base redimensionnee @@ -686,8 +683,7 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', //fclose($fp); // Create image on disk - switch ($targetformat) - { + switch ($targetformat) { case IMAGETYPE_GIF: // 1 imagegif($imgThumb, $imgThumbName); break; @@ -706,7 +702,9 @@ function vignette($file, $maxWidth = 160, $maxHeight = 120, $extName = '_small', } // Set permissions on file - if (!empty($conf->global->MAIN_UMASK)) @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK)); + if (!empty($conf->global->MAIN_UMASK)) { + @chmod($imgThumbName, octdec($conf->global->MAIN_UMASK)); + } // Free memory. This does not delete image. imagedestroy($img); diff --git a/htdocs/core/lib/import.lib.php b/htdocs/core/lib/import.lib.php index 385dee32a86..a9663795988 100644 --- a/htdocs/core/lib/import.lib.php +++ b/htdocs/core/lib/import.lib.php @@ -36,13 +36,14 @@ function import_prepare_head($param, $maxstep = 0) { global $langs; - if (empty($maxstep)) $maxstep = 6; + if (empty($maxstep)) { + $maxstep = 6; + } $h = 0; $head = array(); $i = 1; - while ($i <= $maxstep) - { + while ($i <= $maxstep) { if ($i < 6) { $head[$h][0] = DOL_URL_ROOT.'/imports/import.php?step='.$i.$param; } else { diff --git a/htdocs/core/lib/invoice.lib.php b/htdocs/core/lib/invoice.lib.php index eda1a901986..89e7f8c8e55 100644 --- a/htdocs/core/lib/invoice.lib.php +++ b/htdocs/core/lib/invoice.lib.php @@ -45,32 +45,37 @@ function facture_prepare_head($object) $head[$h][2] = 'compta'; $h++; - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/compta/facture/contact.php?facid='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } - if (!empty($conf->prelevement->enabled)) - { + if (!empty($conf->prelevement->enabled)) { $nbStandingOrders = 0; $sql = "SELECT COUNT(pfd.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd"; $sql .= " WHERE pfd.fk_facture = ".$object->id; $sql .= " AND pfd.ext_payment_id IS NULL"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $nbStandingOrders = $obj->nb; - } else dol_print_error($db); + if ($obj) { + $nbStandingOrders = $obj->nb; + } + } else { + dol_print_error($db); + } $head[$h][0] = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$object->id; $head[$h][1] = $langs->trans('StandingOrders'); - if ($nbStandingOrders > 0) $head[$h][1] .= ''.$nbStandingOrders.''; + if ($nbStandingOrders > 0) { + $head[$h][1] .= ''.$nbStandingOrders.''; + } $head[$h][2] = 'standingorders'; $h++; } @@ -81,14 +86,19 @@ function facture_prepare_head($object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'invoice'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/compta/facture/note.php?facid='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -100,7 +110,9 @@ function facture_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/compta/facture/document.php?facid='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; diff --git a/htdocs/core/lib/invoice2.lib.php b/htdocs/core/lib/invoice2.lib.php index f38292cb50d..ca5fc61b60a 100644 --- a/htdocs/core/lib/invoice2.lib.php +++ b/htdocs/core/lib/invoice2.lib.php @@ -53,85 +53,106 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte $sql .= " FROM ".MAIN_DB_PREFIX."facture as f"; $sqlwhere = ''; $sqlorder = ''; - if (in_array('all', $filter)) - { + if (in_array('all', $filter)) { $sqlorder = " ORDER BY f.ref ASC"; } - if (in_array('date', $filter)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('date', $filter)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= " f.fk_statut > 0"; $sqlwhere .= " AND f.datef >= '".$db->idate($dateafterdate)."'"; $sqlwhere .= " AND f.datef <= '".$db->idate($datebeforedate)."'"; $sqlorder = " ORDER BY f.datef ASC"; } - if (in_array('nopayment', $filter)) - { + if (in_array('nopayment', $filter)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiement_facture as pf ON f.rowid = pf.fk_facture"; - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= " f.fk_statut > 0"; $sqlwhere .= " AND pf.fk_paiement IS NULL"; } - if (in_array('payments', $filter) || in_array('bank', $filter)) - { + if (in_array('payments', $filter) || in_array('bank', $filter)) { $sql .= ", ".MAIN_DB_PREFIX."paiement_facture as pf, ".MAIN_DB_PREFIX."paiement as p"; - if (in_array('bank', $filter)) $sql .= ", ".MAIN_DB_PREFIX."bank as b"; - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('bank', $filter)) { + $sql .= ", ".MAIN_DB_PREFIX."bank as b"; + } + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= " f.fk_statut > 0"; $sqlwhere .= " AND f.rowid = pf.fk_facture"; $sqlwhere .= " AND pf.fk_paiement = p.rowid"; - if (in_array('payments', $filter)) - { + if (in_array('payments', $filter)) { $sqlwhere .= " AND p.datep >= '".$db->idate($paymentdateafter)."'"; $sqlwhere .= " AND p.datep <= '".$db->idate($paymentdatebefore)."'"; } - if (in_array('bank', $filter)) - { + if (in_array('bank', $filter)) { $sqlwhere .= " AND p.fk_bank = b.rowid"; $sqlwhere .= " AND b.fk_account = ".$paymentbankid; } $sqlorder = " ORDER BY p.datep ASC"; } - if (in_array('nodeposit', $filter)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('nodeposit', $filter)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' type <> 3'; } - if (in_array('noreplacement', $filter)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('noreplacement', $filter)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' type <> 1'; } - if (in_array('nocreditnote', $filter)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('nocreditnote', $filter)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' type <> 2'; } - if (in_array('excludethirdparties', $filter) && is_array($thirdpartiesid)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('excludethirdparties', $filter) && is_array($thirdpartiesid)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' f.fk_soc NOT IN ('.join(',', $thirdpartiesid).')'; } - if (in_array('onlythirdparties', $filter) && is_array($thirdpartiesid)) - { - if (empty($sqlwhere)) $sqlwhere = ' WHERE '; - else $sqlwhere .= " AND"; + if (in_array('onlythirdparties', $filter) && is_array($thirdpartiesid)) { + if (empty($sqlwhere)) { + $sqlwhere = ' WHERE '; + } else { + $sqlwhere .= " AND"; + } $sqlwhere .= ' f.fk_soc IN ('.join(',', $thirdpartiesid).')'; } - if ($sqlwhere) $sql .= $sqlwhere; - if ($sqlorder) $sql .= $sqlorder; + if ($sqlwhere) { + $sql .= $sqlwhere; + } + if ($sqlorder) { + $sql .= $sqlorder; + } //print $sql; exit; dol_syslog("scripts/invoices/rebuild_merge.php:", LOG_DEBUG); - if ($usestdout) print '--- start'."\n"; + if ($usestdout) { + print '--- start'."\n"; + } // Start of transaction //$db->begin(); @@ -141,54 +162,53 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte $files = array(); // liste les fichiers dol_syslog("scripts/invoices/rebuild_merge.php", LOG_DEBUG); - if ($resql = $db->query($sql)) - { + if ($resql = $db->query($sql)) { $num = $db->num_rows($resql); $cpt = 0; $oldemail = ''; $message = ''; $total = ''; - if ($num) - { + if ($num) { // First loop on each resultset to build PDF // ----------------------------------------- - while ($cpt < $num) - { + while ($cpt < $num) { $obj = $db->fetch_object($resql); $fac = new Facture($db); $result = $fac->fetch($obj->rowid); - if ($result > 0) - { + if ($result > 0) { $outputlangs = $langs; - if (!empty($newlangid)) - { - if ($outputlangs->defaultlang != $newlangid) - { + if (!empty($newlangid)) { + if ($outputlangs->defaultlang != $newlangid) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlangid); } } $filename = $conf->facture->dir_output.'/'.$fac->ref.'/'.$fac->ref.'.pdf'; - if ($regenerate || !dol_is_file($filename)) - { - if ($usestdout) print "Build PDF for invoice ".$obj->ref." - Lang = ".$outputlangs->defaultlang."\n"; + if ($regenerate || !dol_is_file($filename)) { + if ($usestdout) { + print "Build PDF for invoice ".$obj->ref." - Lang = ".$outputlangs->defaultlang."\n"; + } $result = $fac->generateDocument($regenerate ? $regenerate : $fac->model_pdf, $outputlangs); } else { - if ($usestdout) print "PDF for invoice ".$obj->ref." already exists\n"; + if ($usestdout) { + print "PDF for invoice ".$obj->ref." already exists\n"; + } } // Add file into files array $files[] = $filename; } - if ($result <= 0) - { + if ($result <= 0) { $error++; - if ($usestdout) print "Error: Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid)."\n"; - else dol_syslog("Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid), LOG_ERR); + if ($usestdout) { + print "Error: Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid)."\n"; + } else { + dol_syslog("Failed to build PDF for invoice ".($fac->ref ? $fac->ref : ' id '.$obj->rowid), LOG_ERR); + } } $cpt++; @@ -201,8 +221,11 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte $page_hauteur = $formatarray['height']; $format = array($page_largeur, $page_hauteur); - if ($usestdout) print "Using output PDF format ".join('x', $format)."\n"; - else dol_syslog("Using output PDF format ".join('x', $format), LOG_ERR); + if ($usestdout) { + print "Using output PDF format ".join('x', $format)."\n"; + } else { + dol_syslog("Using output PDF format ".join('x', $format), LOG_ERR); + } // Now, build a merged files with all files in $files array @@ -210,26 +233,28 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte // Create empty PDF $pdf = pdf_getInstance($format); - if (class_exists('TCPDF')) - { + if (class_exists('TCPDF')) { $pdf->setPrintHeader(false); $pdf->setPrintFooter(false); } $pdf->SetFont(pdf_getPDFFont($langs)); - if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) $pdf->SetCompression(false); + if ($conf->global->MAIN_DISABLE_PDF_COMPRESSION) { + $pdf->SetCompression(false); + } //$pdf->SetCompression(false); // Add all others - foreach ($files as $file) - { - if ($usestdout) print "Merge PDF file for invoice ".$file."\n"; - else dol_syslog("Merge PDF file for invoice ".$file); + foreach ($files as $file) { + if ($usestdout) { + print "Merge PDF file for invoice ".$file."\n"; + } else { + dol_syslog("Merge PDF file for invoice ".$file); + } // Charge un document PDF depuis un fichier. $pagecount = $pdf->setSourceFile($file); - for ($i = 1; $i <= $pagecount; $i++) - { + for ($i = 1; $i <= $pagecount; $i++) { $tplidx = $pdf->importPage($i); $s = $pdf->getTemplatesize($tplidx); $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); @@ -242,27 +267,36 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte // Save merged file $filename = $fileprefix; - if (empty($filename)) $filename = 'mergedpdf'; - if (!empty($filesuffix)) $filename .= '_'.$filesuffix; + if (empty($filename)) { + $filename = 'mergedpdf'; + } + if (!empty($filesuffix)) { + $filename .= '_'.$filesuffix; + } $file = $diroutputpdf.'/'.$filename.'.pdf'; - if (!$error && $pagecount) - { + if (!$error && $pagecount) { $pdf->Output($file, 'F'); - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($file, octdec($conf->global->MAIN_UMASK)); + } } - if ($usestdout) - { - if (!$error) print "Merged PDF has been built in ".$file."\n"; - else print "Can't build PDF ".$file."\n"; + if ($usestdout) { + if (!$error) { + print "Merged PDF has been built in ".$file."\n"; + } else { + print "Can't build PDF ".$file."\n"; + } } $result = 1; } else { - if ($usestdout) print "No invoices found for criteria.\n"; - else dol_syslog("No invoices found for criteria"); + if ($usestdout) { + print "No invoices found for criteria.\n"; + } else { + dol_syslog("No invoices found for criteria"); + } $result = 0; } } else { @@ -271,6 +305,9 @@ function rebuild_merge_pdf($db, $langs, $conf, $diroutputpdf, $newlangid, $filte $error++; } - if ($error) return -1; - else return $result; + if ($error) { + return -1; + } else { + return $result; + } } diff --git a/htdocs/core/lib/json.lib.php b/htdocs/core/lib/json.lib.php index cd48bbcb3c7..fe50503ed99 100644 --- a/htdocs/core/lib/json.lib.php +++ b/htdocs/core/lib/json.lib.php @@ -23,8 +23,7 @@ * \ingroup core */ -if (!function_exists('json_encode')) -{ +if (!function_exists('json_encode')) { /** * Implement json_encode for PHP that does not have module enabled. * @@ -50,26 +49,32 @@ function dol_json_encode($elements) dol_syslog("For better performance, enable the native json in your PHP", LOG_WARNING); $num = 0; - if (is_object($elements)) // Count number of properties for an object - { - foreach ($elements as $key => $value) $num++; + if (is_object($elements)) { // Count number of properties for an object + foreach ($elements as $key => $value) { + $num++; + } } else { $num = count($elements); } //var_dump($num); // determine type - if (is_numeric(key($elements)) && key($elements) == 0) - { + if (is_numeric(key($elements)) && key($elements) == 0) { // indexed (list) $keysofelements = array_keys($elements); // Elements array mus have key that does not start with 0 and end with num-1, so we will use this later. $output = '['; - for ($i = 0, $last = ($num - 1); $i < $num; $i++) - { - if (!isset($elements[$keysofelements[$i]])) continue; - if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) $output .= json_encode($elements[$keysofelements[$i]]); - else $output .= _val($elements[$keysofelements[$i]]); - if ($i !== $last) $output .= ','; + for ($i = 0, $last = ($num - 1); $i < $num; $i++) { + if (!isset($elements[$keysofelements[$i]])) { + continue; + } + if (is_array($elements[$keysofelements[$i]]) || is_object($elements[$keysofelements[$i]])) { + $output .= json_encode($elements[$keysofelements[$i]]); + } else { + $output .= _val($elements[$keysofelements[$i]]); + } + if ($i !== $last) { + $output .= ','; + } } $output .= ']'; } else { @@ -78,14 +83,22 @@ function dol_json_encode($elements) $last = $num - 1; $i = 0; $tmpelements = array(); - if (is_array($elements)) $tmpelements = $elements; - if (is_object($elements)) $tmpelements = get_object_vars($elements); - foreach ($tmpelements as $key => $value) - { + if (is_array($elements)) { + $tmpelements = $elements; + } + if (is_object($elements)) { + $tmpelements = get_object_vars($elements); + } + foreach ($tmpelements as $key => $value) { $output .= '"'.$key.'":'; - if (is_array($value)) $output .= json_encode($value); - else $output .= _val($value); - if ($i !== $last) $output .= ','; + if (is_array($value)) { + $output .= json_encode($value); + } else { + $output .= _val($value); + } + if ($i !== $last) { + $output .= ','; + } ++$i; } $output .= '}'; @@ -109,9 +122,9 @@ function _val($val) $strlen_var = strlen($val); /* - * Iterate over every character in the string, - * escaping with a slash or encoding to UTF-8 where necessary - */ + * Iterate over every character in the string, + * escaping with a slash or encoding to UTF-8 where necessary + */ for ($c = 0; $c < $strlen_var; ++$c) { $ord_var_c = ord($val[$c]); @@ -192,14 +205,18 @@ function _val($val) } return '"'.$ascii.'"'; - } elseif (is_int($val)) return sprintf('%d', $val); - elseif (is_float($val)) return sprintf('%F', $val); - elseif (is_bool($val)) return ($val ? 'true' : 'false'); - else return 'null'; + } elseif (is_int($val)) { + return sprintf('%d', $val); + } elseif (is_float($val)) { + return sprintf('%F', $val); + } elseif (is_bool($val)) { + return ($val ? 'true' : 'false'); + } else { + return 'null'; + } } -if (!function_exists('json_decode')) -{ +if (!function_exists('json_decode')) { /** * Implement json_decode for PHP that does not support it * @@ -230,16 +247,23 @@ function dol_json_decode($json, $assoc = false) $out = ''; $strLength = strlen($json); // Must stay strlen and not dol_strlen because we want technical length, not visible length - for ($i = 0; $i < $strLength; $i++) - { - if (!$comment) - { - if (($json[$i] == '{') || ($json[$i] == '[')) $out .= 'array('; - elseif (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')'; - elseif ($json[$i] == ':') $out .= ' => '; - else $out .= $json[$i]; - } else $out .= $json[$i]; - if ($json[$i] == '"' && $json[($i - 1)] != "\\") $comment = !$comment; + for ($i = 0; $i < $strLength; $i++) { + if (!$comment) { + if (($json[$i] == '{') || ($json[$i] == '[')) { + $out .= 'array('; + } elseif (($json[$i] == '}') || ($json[$i] == ']')) { + $out .= ')'; + } elseif ($json[$i] == ':') { + $out .= ' => '; + } else { + $out .= $json[$i]; + } + } else { + $out .= $json[$i]; + } + if ($json[$i] == '"' && $json[($i - 1)] != "\\") { + $comment = !$comment; + } } $out = _unval($out); @@ -256,17 +280,16 @@ function dol_json_decode($json, $assoc = false) } // Return an object - if (!$assoc) - { - if (!empty($array)) - { + if (!$assoc) { + if (!empty($array)) { $object = false; if (count($array) > 0) { $object = (object) array(); } - foreach ($array as $key => $value) - { - if ($key) $object->{$key} = $value; + foreach ($array as $key => $value) { + if ($key) { + $object->{$key} = $value; + } } return $object; @@ -287,8 +310,7 @@ function dol_json_decode($json, $assoc = false) function _unval($val) { $reg = array(); - while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg)) - { + while (preg_match('/\\\u([0-9A-F]{2})([0-9A-F]{2})/i', $val, $reg)) { // single, escaped unicode character $utf16 = chr(hexdec($reg[1])).chr(hexdec($reg[2])); $utf8 = utf162utf8($utf16); @@ -320,18 +342,18 @@ function utf162utf8($utf16) case ((0x7F & $bytes) == $bytes): // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr($bytes); + return chr($bytes); case (0x07FF & $bytes) == $bytes: // return a 2-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xC0 | (($bytes >> 6) & 0x1F)) + return chr(0xC0 | (($bytes >> 6) & 0x1F)) . chr(0x80 | ($bytes & 0x3F)); case (0xFFFF & $bytes) == $bytes: // return a 3-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 - return chr(0xE0 | (($bytes >> 12) & 0x0F)) + return chr(0xE0 | (($bytes >> 12) & 0x0F)) . chr(0x80 | (($bytes >> 6) & 0x3F)) . chr(0x80 | ($bytes & 0x3F)); } diff --git a/htdocs/core/lib/ldap.lib.php b/htdocs/core/lib/ldap.lib.php index 640152d5999..9d6e0193108 100644 --- a/htdocs/core/lib/ldap.lib.php +++ b/htdocs/core/lib/ldap.lib.php @@ -43,40 +43,35 @@ function ldap_prepare_head() $head[$h][2] = 'ldap'; $h++; - if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) - { + if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_users.php"; $head[$h][1] = $langs->trans("LDAPUsersSynchro"); $head[$h][2] = 'users'; $h++; } - if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) - { + if (!empty($conf->global->LDAP_SYNCHRO_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_groups.php"; $head[$h][1] = $langs->trans("LDAPGroupsSynchro"); $head[$h][2] = 'groups'; $h++; } - if (!empty($conf->societe->enabled) && !empty($conf->global->LDAP_CONTACT_ACTIVE)) - { + if (!empty($conf->societe->enabled) && !empty($conf->global->LDAP_CONTACT_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_contacts.php"; $head[$h][1] = $langs->trans("LDAPContactsSynchro"); $head[$h][2] = 'contacts'; $h++; } - if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE)) - { + if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_members.php"; $head[$h][1] = $langs->trans("LDAPMembersSynchro"); $head[$h][2] = 'members'; $h++; } - if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE)) - { + if (!empty($conf->adherent->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE)) { $head[$h][0] = DOL_URL_ROOT."/admin/ldap_members_types.php"; $head[$h][1] = $langs->trans("LDAPMembersTypesSynchro"); $head[$h][2] = 'memberstypes'; @@ -111,14 +106,11 @@ function show_ldap_test_button($butlabel, $testlabel, $key, $dn, $objectclass) //print 'key='.$key.' dn='.$dn.' objectclass='.$objectclass; print '
    '; - if (!function_exists("ldap_connect")) - { + if (!function_exists("ldap_connect")) { print ''.$butlabel.''; - } elseif (empty($conf->global->LDAP_SERVER_HOST)) - { + } elseif (empty($conf->global->LDAP_SERVER_HOST)) { print ''.$butlabel.''; - } elseif (empty($key) || empty($dn) || empty($objectclass)) - { + } elseif (empty($key) || empty($dn) || empty($objectclass)) { $langs->load("errors"); print ''.$butlabel.''; } else { @@ -144,39 +136,54 @@ function show_ldap_content($result, $level, $count, $var, $hide = 0, $subcount = global $bc, $conf; $count--; - if ($count == 0) return -1; // To stop loop - if (!is_array($result)) return -1; + if ($count == 0) { + return -1; // To stop loop + } + if (!is_array($result)) { + return -1; + } - foreach ($result as $key => $val) - { - if ("$key" == "objectclass") continue; - if ("$key" == "count") continue; - if ("$key" == "dn") continue; - if ("$val" == "objectclass") continue; + foreach ($result as $key => $val) { + if ("$key" == "objectclass") { + continue; + } + if ("$key" == "count") { + continue; + } + if ("$key" == "dn") { + continue; + } + if ("$val" == "objectclass") { + continue; + } $lastkey[$level] = $key; - if (is_array($val)) - { + if (is_array($val)) { $hide = 0; - if (!is_numeric($key)) - { + if (!is_numeric($key)) { print ''; print ''; print $key; print ''; - if (strtolower($key) == 'userpassword') $hide = 1; + if (strtolower($key) == 'userpassword') { + $hide = 1; + } } show_ldap_content($val, $level + 1, $count, $var, $hide, $val["count"]); - } elseif ($subcount) - { + } elseif ($subcount) { $subcount--; $newstring = dol_htmlentitiesbr($val); - if ($hide) print preg_replace('/./i', '*', $newstring); - else print $newstring; + if ($hide) { + print preg_replace('/./i', '*', $newstring); + } else { + print $newstring; + } print '
    '; } - if ("$val" != $lastkey[$level] && !$subcount) print ''; + if ("$val" != $lastkey[$level] && !$subcount) { + print ''; + } } return 1; } diff --git a/htdocs/core/lib/loan.lib.php b/htdocs/core/lib/loan.lib.php index 3a34d3e57c4..c86d0ecce13 100644 --- a/htdocs/core/lib/loan.lib.php +++ b/htdocs/core/lib/loan.lib.php @@ -60,7 +60,9 @@ function loan_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$tab][0] = DOL_URL_ROOT.'/loan/document.php?id='.$object->id; $head[$tab][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$tab][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$tab][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$tab][2] = 'documents'; $tab++; @@ -68,7 +70,9 @@ function loan_prepare_head($object) $nbNote = (empty($object->note_private) ? 0 : 1) + (empty($object->note_public) ? 0 : 1); $head[$tab][0] = DOL_URL_ROOT."/loan/note.php?id=".$object->id; $head[$tab][1] = $langs->trans("Notes"); - if ($nbNote > 0) $head[$tab][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$tab][1] .= ''.$nbNote.''; + } $head[$tab][2] = 'note'; $tab++; } diff --git a/htdocs/core/lib/member.lib.php b/htdocs/core/lib/member.lib.php index 50330686805..93378d77390 100644 --- a/htdocs/core/lib/member.lib.php +++ b/htdocs/core/lib/member.lib.php @@ -43,8 +43,7 @@ function member_prepare_head(Adherent $object) $h++; if ((!empty($conf->ldap->enabled) && !empty($conf->global->LDAP_MEMBER_ACTIVE)) - && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) - { + && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) { $langs->load("ldap"); $head[$h][0] = DOL_URL_ROOT.'/adherents/ldap.php?id='.$object->id; @@ -53,13 +52,14 @@ function member_prepare_head(Adherent $object) $h++; } - if (!empty($user->rights->adherent->cotisation->lire)) - { + if (!empty($user->rights->adherent->cotisation->lire)) { $nbSubscription = is_array($object->subscriptions) ?count($object->subscriptions) : 0; $head[$h][0] = DOL_URL_ROOT.'/adherents/subscription.php?rowid='.$object->id; $head[$h][1] = $langs->trans("Subscriptions"); $head[$h][2] = 'subscription'; - if ($nbSubscription > 0) $head[$h][1] .= ''.$nbSubscription.''; + if ($nbSubscription > 0) { + $head[$h][1] .= ''.$nbSubscription.''; + } $h++; } @@ -70,13 +70,21 @@ function member_prepare_head(Adherent $object) complete_head_from_modules($conf, $langs, $object, $head, $h, 'member'); $nbNote = 0; - if (!empty($object->note)) $nbNote++; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note)) { + $nbNote++; + } + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/adherents/note.php?id='.$object->id; $head[$h][1] = $langs->trans("Note"); $head[$h][2] = 'note'; - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $h++; // Attachments @@ -87,17 +95,17 @@ function member_prepare_head(Adherent $object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/adherents/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'document'; $h++; // Show agenda tab - if (!empty($conf->agenda->enabled)) - { + if (!empty($conf->agenda->enabled)) { $head[$h][0] = DOL_URL_ROOT."/adherents/agenda.php?id=".$object->id; $head[$h][1] = $langs->trans("Events"); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } @@ -129,8 +137,7 @@ function member_type_prepare_head(AdherentType $object) $h++; // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { $head[$h][0] = DOL_URL_ROOT."/adherents/type_translation.php?rowid=".$object->id; $head[$h][1] = $langs->trans("Translation"); $head[$h][2] = 'translation'; @@ -138,8 +145,7 @@ function member_type_prepare_head(AdherentType $object) } if ((!empty($conf->ldap->enabled) && !empty($conf->global->LDAP_MEMBER_TYPE_ACTIVE)) - && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) - { + && (empty($conf->global->MAIN_DISABLE_LDAP_TAB) || !empty($user->admin))) { $langs->load("ldap"); $head[$h][0] = DOL_URL_ROOT.'/adherents/type_ldap.php?rowid='.$object->id; diff --git a/htdocs/core/lib/memory.lib.php b/htdocs/core/lib/memory.lib.php index 484b3933e42..ce603415009 100644 --- a/htdocs/core/lib/memory.lib.php +++ b/htdocs/core/lib/memory.lib.php @@ -71,7 +71,9 @@ function dol_setcache($memoryid, $data, $expire = 0) $result = 0; if (strpos($memoryid, 'count_') === 0) { // The memoryid key start with 'count_...' - if (empty($conf->global->MAIN_CACHE_COUNT)) return 0; + if (empty($conf->global->MAIN_CACHE_COUNT)) { + return 0; + } } if (!empty($conf->memcached->enabled) && class_exists('Memcached')) { @@ -81,7 +83,9 @@ function dol_setcache($memoryid, $data, $expire = 0) $dolmemcache = new Memcached(); $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); $result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); - if (!$result) return -1; + if (!$result) { + return -1; + } } $memoryid = session_name() . '_' . $memoryid; @@ -100,7 +104,9 @@ function dol_setcache($memoryid, $data, $expire = 0) $dolmemcache = new Memcache(); $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); $result = $dolmemcache->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); - if (!$result) return -1; + if (!$result) { + return -1; + } } $memoryid = session_name() . '_' . $memoryid; @@ -131,7 +137,9 @@ function dol_getcache($memoryid) global $conf; if (strpos($memoryid, 'count_') === 0) { // The memoryid key start with 'count_...' - if (empty($conf->global->MAIN_CACHE_COUNT)) return null; + if (empty($conf->global->MAIN_CACHE_COUNT)) { + return null; + } } // Using a memcached server @@ -141,7 +149,9 @@ function dol_getcache($memoryid) $m = new Memcached(); $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); $result = $m->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); - if (!$result) return -1; + if (!$result) { + return -1; + } } $memoryid = session_name() . '_' . $memoryid; @@ -164,7 +174,9 @@ function dol_getcache($memoryid) $m = new Memcache(); $tmparray = explode(':', $conf->global->MEMCACHED_SERVER); $result = $m->addServer($tmparray[0], $tmparray[1] ? $tmparray[1] : 11211); - if (!$result) return -1; + if (!$result) { + return -1; + } } $memoryid = session_name() . '_' . $memoryid; @@ -235,9 +247,13 @@ function dol_setshmop($memoryid, $data, $expire) global $shmkeys, $shmoffset; //print 'dol_setshmop memoryid='.$memoryid."
    \n"; - if (empty($shmkeys[$memoryid]) || !function_exists("shmop_write")) return 0; + if (empty($shmkeys[$memoryid]) || !function_exists("shmop_write")) { + return 0; + } $shmkey = dol_getshmopaddress($memoryid); - if (empty($shmkey)) return 0; // No key reserved for this memoryid, we can't cache this memoryid + if (empty($shmkey)) { + return 0; // No key reserved for this memoryid, we can't cache this memoryid + } $newdata = serialize($data); $size = strlen($newdata); @@ -273,14 +289,19 @@ function dol_getshmop($memoryid) return null; } $shmkey = dol_getshmopaddress($memoryid); - if (empty($shmkey)) return null; // No key reserved for this memoryid, we can't cache this memoryid + if (empty($shmkey)) { + return null; // No key reserved for this memoryid, we can't cache this memoryid + } //print 'dol_getshmop memoryid='.$memoryid." shmkey=".$shmkey."
    \n"; $handle = @shmop_open($shmkey, 'a', 0, 0); if ($handle) { $size = trim(shmop_read($handle, 0, 6)); - if ($size) $data = unserialize(shmop_read($handle, 6, $size)); - else return -1; + if ($size) { + $data = unserialize(shmop_read($handle, 6, $size)); + } else { + return -1; + } shmop_close($handle); } else { return null; // Can't open existing block, so we suppose it was not created, so nothing were cached yet for the memoryid diff --git a/htdocs/core/lib/modulebuilder.lib.php b/htdocs/core/lib/modulebuilder.lib.php index ff14ec56e18..0c6029ebb00 100644 --- a/htdocs/core/lib/modulebuilder.lib.php +++ b/htdocs/core/lib/modulebuilder.lib.php @@ -41,31 +41,30 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = { global $db, $langs; - if (empty($objectname)) return -1; - if (empty($readdir)) $readdir = $destdir; + if (empty($objectname)) { + return -1; + } + if (empty($readdir)) { + $readdir = $destdir; + } - if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) - { + if (!empty($addfieldentry['arrayofkeyval']) && !is_array($addfieldentry['arrayofkeyval'])) { dol_print_error('', 'Bad parameter addfieldentry with a property arrayofkeyval defined but that is not an array.'); return -1; } // Check parameters - if (count($addfieldentry) > 0) - { - if (empty($addfieldentry['name'])) - { + if (count($addfieldentry) > 0) { + if (empty($addfieldentry['name'])) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Name")), null, 'errors'); return -2; } - if (empty($addfieldentry['label'])) - { + if (empty($addfieldentry['label'])) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Label")), null, 'errors'); return -2; } if (!preg_match('/^(integer|price|sellist|varchar|double|text|html|duration)/', $addfieldentry['type']) - && !preg_match('/^(boolean|real|date|datetime|timestamp)$/', $addfieldentry['type'])) - { + && !preg_match('/^(boolean|real|date|datetime|timestamp)$/', $addfieldentry['type'])) { setEventMessages($langs->trans('BadValueForType', $objectname), null, 'errors'); return -2; } @@ -73,8 +72,7 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = $pathoffiletoeditsrc = $readdir.'/class/'.strtolower($objectname).'.class.php'; $pathoffiletoedittarget = $destdir.'/class/'.strtolower($objectname).'.class.php'.($readdir != $destdir ? '.new' : ''); - if (!dol_is_file($pathoffiletoeditsrc)) - { + if (!dol_is_file($pathoffiletoeditsrc)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors'); return -3; @@ -85,8 +83,11 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = try { include_once $pathoffiletoeditsrc; - if (class_exists($objectname)) $object = new $objectname($db); - else return -4; + if (class_exists($objectname)) { + $object = new $objectname($db); + } else { + return -4; + } // Backup old file dol_copy($pathoffiletoedittarget, $pathoffiletoedittarget.'.back', $newmask, 1); @@ -95,17 +96,14 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = $contentclass = file_get_contents(dol_osencode($pathoffiletoeditsrc), 'r'); // Update ->fields (add or remove entries) - if (count($object->fields)) - { - if (is_array($addfieldentry) && count($addfieldentry)) - { + if (count($object->fields)) { + if (is_array($addfieldentry) && count($addfieldentry)) { $name = $addfieldentry['name']; unset($addfieldentry['name']); $object->fields[$name] = $addfieldentry; } - if (!empty($delfieldentry)) - { + if (!empty($delfieldentry)) { $name = $delfieldentry; unset($object->fields[$name]); } @@ -120,40 +118,62 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = $texttoinsert .= "\t".' */'."\n"; $texttoinsert .= "\t".'public $fields=array('."\n"; - if (count($object->fields)) - { - foreach ($object->fields as $key => $val) - { + if (count($object->fields)) { + foreach ($object->fields as $key => $val) { $i++; $texttoinsert .= "\t\t'".$key."' => array('type'=>'".$val['type']."', 'label'=>'".$val['label']."',"; $texttoinsert .= " 'enabled'=>'".($val['enabled'] !== '' ? $val['enabled'] : 1)."',"; $texttoinsert .= " 'position'=>".($val['position'] !== '' ? $val['position'] : 50).","; $texttoinsert .= " 'notnull'=>".(empty($val['notnull']) ? 0 : $val['notnull']).","; $texttoinsert .= " 'visible'=>".($val['visible'] !== '' ? $val['visible'] : -1).","; - if ($val['noteditable']) $texttoinsert .= " 'noteditable'=>'".$val['noteditable']."',"; - if ($val['default'] || $val['default'] === '0') $texttoinsert .= " 'default'=>'".$val['default']."',"; - if ($val['index']) $texttoinsert .= " 'index'=>".$val['index'].","; - if ($val['foreignkey']) $texttoinsert .= " 'foreignkey'=>'".$val['foreignkey']."',"; - if ($val['searchall']) $texttoinsert .= " 'searchall'=>".$val['searchall'].","; - if ($val['isameasure']) $texttoinsert .= " 'isameasure'=>'".$val['isameasure']."',"; - if ($val['css']) $texttoinsert .= " 'css'=>'".$val['css']."',"; - if ($val['help']) $texttoinsert .= " 'help'=>\"".preg_replace('/"/', '', $val['help'])."\","; - if ($val['showoncombobox']) $texttoinsert .= " 'showoncombobox'=>'".$val['showoncombobox']."',"; - if ($val['disabled']) $texttoinsert .= " 'disabled'=>'".$val['disabled']."',"; - if ($val['autofocusoncreate']) $texttoinsert .= " 'autofocusoncreate'=>'".$val['autofocusoncreate']."',"; - if ($val['arrayofkeyval']) - { + if ($val['noteditable']) { + $texttoinsert .= " 'noteditable'=>'".$val['noteditable']."',"; + } + if ($val['default'] || $val['default'] === '0') { + $texttoinsert .= " 'default'=>'".$val['default']."',"; + } + if ($val['index']) { + $texttoinsert .= " 'index'=>".$val['index'].","; + } + if ($val['foreignkey']) { + $texttoinsert .= " 'foreignkey'=>'".$val['foreignkey']."',"; + } + if ($val['searchall']) { + $texttoinsert .= " 'searchall'=>".$val['searchall'].","; + } + if ($val['isameasure']) { + $texttoinsert .= " 'isameasure'=>'".$val['isameasure']."',"; + } + if ($val['css']) { + $texttoinsert .= " 'css'=>'".$val['css']."',"; + } + if ($val['help']) { + $texttoinsert .= " 'help'=>\"".preg_replace('/"/', '', $val['help'])."\","; + } + if ($val['showoncombobox']) { + $texttoinsert .= " 'showoncombobox'=>'".$val['showoncombobox']."',"; + } + if ($val['disabled']) { + $texttoinsert .= " 'disabled'=>'".$val['disabled']."',"; + } + if ($val['autofocusoncreate']) { + $texttoinsert .= " 'autofocusoncreate'=>'".$val['autofocusoncreate']."',"; + } + if ($val['arrayofkeyval']) { $texttoinsert .= " 'arrayofkeyval'=>array("; $i = 0; - foreach ($val['arrayofkeyval'] as $key2 => $val2) - { - if ($i) $texttoinsert .= ", "; + foreach ($val['arrayofkeyval'] as $key2 => $val2) { + if ($i) { + $texttoinsert .= ", "; + } $texttoinsert .= "'".$key2."'=>'".$val2."'"; $i++; } $texttoinsert .= "),"; } - if ($val['comment']) $texttoinsert .= " 'comment'=>\"".preg_replace('/"/', '', $val['comment'])."\""; + if ($val['comment']) { + $texttoinsert .= " 'comment'=>\"".preg_replace('/"/', '', $val['comment'])."\""; + } $texttoinsert .= "),\n"; } @@ -162,12 +182,10 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = $texttoinsert .= "\t".');'."\n"; //print ($texttoinsert);exit; - if (count($object->fields)) - { + if (count($object->fields)) { //$typetotypephp=array('integer'=>'integer', 'duration'=>'integer', 'varchar'=>'string'); - foreach ($object->fields as $key => $val) - { + foreach ($object->fields as $key => $val) { $i++; //$typephp=$typetotypephp[$val['type']]; $texttoinsert .= "\t".'public $'.$key.";"; @@ -192,8 +210,7 @@ function rebuildObjectClass($destdir, $module, $objectname, $newmask, $readdir = @chmod($pathoffiletoedittarget, octdec($newmask)); return $object; - } catch (Exception $e) - { + } catch (Exception $e) { print $e->getMessage(); return -5; } @@ -218,8 +235,12 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $error = 0; - if (empty($objectname)) return -1; - if (empty($readdir)) $readdir = $destdir; + if (empty($objectname)) { + return -1; + } + if (empty($readdir)) { + $readdir = $destdir; + } $pathoffiletoclasssrc = $readdir.'/class/'.strtolower($objectname).'.class.php'; @@ -232,8 +253,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $pathoffiletoedittarget = $destdir.'/sql/llx_'.strtolower($module).'_'.strtolower($objectname).'.sql'.($readdir != $destdir ? '.new' : ''); } - if (!dol_is_file($pathoffiletoeditsrc)) - { + if (!dol_is_file($pathoffiletoeditsrc)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFileNotFound", $pathoffiletoeditsrc), null, 'errors'); return -1; @@ -241,14 +261,15 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' // Load object from myobject.class.php try { - if (!is_object($object)) - { + if (!is_object($object)) { include_once $pathoffiletoclasssrc; - if (class_exists($objectname)) $object = new $objectname($db); - else return -1; + if (class_exists($objectname)) { + $object = new $objectname($db); + } else { + return -1; + } } - } catch (Exception $e) - { + } catch (Exception $e) { print $e->getMessage(); } @@ -259,31 +280,41 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $i = 0; $texttoinsert = '-- BEGIN MODULEBUILDER FIELDS'."\n"; - if (count($object->fields)) - { - foreach ($object->fields as $key => $val) - { + if (count($object->fields)) { + foreach ($object->fields as $key => $val) { $i++; $type = $val['type']; $type = preg_replace('/:.*$/', '', $type); // For case type = 'integer:Societe:societe/class/societe.class.php' - if ($type == 'html') $type = 'text'; // html modulebuilder type is a text type in database - elseif ($type == 'price') $type = 'double'; // html modulebuilder type is a text type in database - elseif (in_array($type, array('link', 'sellist', 'duration'))) $type = 'integer'; + if ($type == 'html') { + $type = 'text'; // html modulebuilder type is a text type in database + } elseif ($type == 'price') { + $type = 'double'; // html modulebuilder type is a text type in database + } elseif (in_array($type, array('link', 'sellist', 'duration'))) { + $type = 'integer'; + } $texttoinsert .= "\t".$key." ".$type; - if ($key == 'rowid') $texttoinsert .= ' AUTO_INCREMENT PRIMARY KEY'; - if ($key == 'entity') $texttoinsert .= ' DEFAULT 1'; - else { - if ($val['default'] != '') - { - if (preg_match('/^null$/i', $val['default'])) $texttoinsert .= " DEFAULT NULL"; - elseif (preg_match('/varchar/', $type)) $texttoinsert .= " DEFAULT '".$db->escape($val['default'])."'"; - else $texttoinsert .= (($val['default'] > 0) ? ' DEFAULT '.$val['default'] : ''); + if ($key == 'rowid') { + $texttoinsert .= ' AUTO_INCREMENT PRIMARY KEY'; + } + if ($key == 'entity') { + $texttoinsert .= ' DEFAULT 1'; + } else { + if ($val['default'] != '') { + if (preg_match('/^null$/i', $val['default'])) { + $texttoinsert .= " DEFAULT NULL"; + } elseif (preg_match('/varchar/', $type)) { + $texttoinsert .= " DEFAULT '".$db->escape($val['default'])."'"; + } else { + $texttoinsert .= (($val['default'] > 0) ? ' DEFAULT '.$val['default'] : ''); + } } } $texttoinsert .= (($val['notnull'] > 0) ? ' NOT NULL' : ''); - if ($i < count($object->fields)) $texttoinsert .= ", "; + if ($i < count($object->fields)) { + $texttoinsert .= ", "; + } $texttoinsert .= "\n"; } } @@ -292,8 +323,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $contentsql = preg_replace('/-- BEGIN MODULEBUILDER FIELDS.*END MODULEBUILDER FIELDS/ims', $texttoinsert, $contentsql); $result = file_put_contents($pathoffiletoedittarget, $contentsql); - if ($result) - { + if ($result) { @chmod($pathoffiletoedittarget, octdec($newmask)); } else { $error++; @@ -312,21 +342,16 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' $i = 0; $texttoinsert = '-- BEGIN MODULEBUILDER INDEXES'."\n"; - if (count($object->fields)) - { - foreach ($object->fields as $key => $val) - { + if (count($object->fields)) { + foreach ($object->fields as $key => $val) { $i++; - if (!empty($val['index'])) - { + if (!empty($val['index'])) { $texttoinsert .= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD INDEX idx_".strtolower($module).'_'.strtolower($objectname)."_".$key." (".$key.");"; $texttoinsert .= "\n"; } - if (!empty($val['foreignkey'])) - { + if (!empty($val['foreignkey'])) { $tmp = explode('.', $val['foreignkey']); - if (!empty($tmp[0]) && !empty($tmp[1])) - { + if (!empty($tmp[0]) && !empty($tmp[1])) { $texttoinsert .= "ALTER TABLE llx_".strtolower($module).'_'.strtolower($objectname)." ADD CONSTRAINT llx_".strtolower($module).'_'.strtolower($objectname)."_".$key." FOREIGN KEY (".$key.") REFERENCES llx_".preg_replace('/^llx_/', '', $tmp[0])."(".$tmp[1].");"; $texttoinsert .= "\n"; } @@ -340,8 +365,7 @@ function rebuildObjectSql($destdir, $module, $objectname, $newmask, $readdir = ' dol_mkdir(dirname($pathoffiletoedittarget)); $result2 = file_put_contents($pathoffiletoedittarget, $contentsql); - if ($result) - { + if ($result) { @chmod($pathoffiletoedittarget, octdec($newmask)); } else { $error++; diff --git a/htdocs/core/lib/multicurrency.lib.php b/htdocs/core/lib/multicurrency.lib.php index a3f7d56ec90..e77a9ee8081 100644 --- a/htdocs/core/lib/multicurrency.lib.php +++ b/htdocs/core/lib/multicurrency.lib.php @@ -65,8 +65,7 @@ function multicurrencyLimitPrepareHead($aCurrencies) $i = 0; $head = array(); - foreach ($aCurrencies as $currency) - { + foreach ($aCurrencies as $currency) { $head[$i][0] = $_SERVER['PHP_SELF'].'?currencycode='.$currency; $head[$i][1] = $langs->trans("Currency".$currency).' ('.$langs->getCurrencySymbol($currency).')'; $head[$i][2] = $currency; diff --git a/htdocs/core/lib/oauth.lib.php b/htdocs/core/lib/oauth.lib.php index a006aad8964..48356868143 100644 --- a/htdocs/core/lib/oauth.lib.php +++ b/htdocs/core/lib/oauth.lib.php @@ -27,8 +27,7 @@ $supportedoauth2array = array( 'OAUTH_GOOGLE_NAME'=>'google', ); -if ($conf->global->MAIN_FEATURES_LEVEL >= 2) -{ +if ($conf->global->MAIN_FEATURES_LEVEL >= 2) { $supportedoauth2array['OAUTH_STRIPE_TEST_NAME'] = 'stripetest'; $supportedoauth2array['OAUTH_STRIPE_LIVE_NAME'] = 'stripelive'; } diff --git a/htdocs/core/lib/order.lib.php b/htdocs/core/lib/order.lib.php index 9bd92a2c79b..9e7d4f8d55a 100644 --- a/htdocs/core/lib/order.lib.php +++ b/htdocs/core/lib/order.lib.php @@ -34,43 +34,58 @@ function commande_prepare_head(Commande $object) { global $db, $langs, $conf, $user; - if (!empty($conf->expedition->enabled)) $langs->load("sendings"); + if (!empty($conf->expedition->enabled)) { + $langs->load("sendings"); + } $langs->load("orders"); $h = 0; $head = array(); - if (!empty($conf->commande->enabled) && $user->rights->commande->lire) - { + if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { $head[$h][0] = DOL_URL_ROOT.'/commande/card.php?id='.$object->id; $head[$h][1] = $langs->trans("CustomerOrder"); $head[$h][2] = 'order'; $h++; } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/commande/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } if (($conf->expedition_bon->enabled && $user->rights->expedition->lire) - || ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire)) - { + || ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire)) { $nbShipments = $object->getNbOfShipments(); $nbReceiption = 0; $head[$h][0] = DOL_URL_ROOT.'/expedition/shipment.php?id='.$object->id; $text = ''; - if ($conf->expedition_bon->enabled) $text .= $langs->trans("Shipments"); - if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled) $text .= ' - '; - if ($conf->delivery_note->enabled) $text .= $langs->trans("Receivings"); - if ($nbShipments > 0 || $nbReceiption > 0) $text .= ''.($nbShipments ? $nbShipments : 0); - if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) $text .= ' - '; - if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) $text .= ($nbReceiption ? $nbReceiption : 0); - if ($nbShipments > 0 || $nbReceiption > 0) $text .= ''; + if ($conf->expedition_bon->enabled) { + $text .= $langs->trans("Shipments"); + } + if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled) { + $text .= ' - '; + } + if ($conf->delivery_note->enabled) { + $text .= $langs->trans("Receivings"); + } + if ($nbShipments > 0 || $nbReceiption > 0) { + $text .= ''.($nbShipments ? $nbShipments : 0); + } + if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) { + $text .= ' - '; + } + if ($conf->expedition_bon->enabled && $conf->delivery_note->enabled && ($nbShipments > 0 || $nbReceiption > 0)) { + $text .= ($nbReceiption ? $nbReceiption : 0); + } + if ($nbShipments > 0 || $nbReceiption > 0) { + $text .= ''; + } $head[$h][1] = $text; $head[$h][2] = 'shipping'; $h++; @@ -82,14 +97,19 @@ function commande_prepare_head(Commande $object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'order'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/commande/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -101,7 +121,9 @@ function commande_prepare_head(Commande $object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/commande/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; diff --git a/htdocs/core/lib/parsemd.lib.php b/htdocs/core/lib/parsemd.lib.php index ef0de8c1298..72903dd9e76 100644 --- a/htdocs/core/lib/parsemd.lib.php +++ b/htdocs/core/lib/parsemd.lib.php @@ -31,17 +31,14 @@ */ function dolMd2Html($content, $parser = 'parsedown', $replaceimagepath = null) { - if (is_array($replaceimagepath)) - { - foreach ($replaceimagepath as $key => $val) - { + if (is_array($replaceimagepath)) { + foreach ($replaceimagepath as $key => $val) { $keytoreplace = ']('.$key; $valafter = ']('.$val; $content = preg_replace('/'.preg_quote($keytoreplace, '/').'/m', $valafter, $content); } } - if ($parser == 'parsedown') - { + if ($parser == 'parsedown') { include_once DOL_DOCUMENT_ROOT.'/includes/parsedown/Parsedown.php'; $Parsedown = new Parsedown(); $content = $Parsedown->text($content); @@ -63,10 +60,8 @@ function dolMd2Html($content, $parser = 'parsedown', $replaceimagepath = null) */ function dolMd2Asciidoc($content, $parser = 'dolibarr', $replaceimagepath = null) { - if (is_array($replaceimagepath)) - { - foreach ($replaceimagepath as $key => $val) - { + if (is_array($replaceimagepath)) { + foreach ($replaceimagepath as $key => $val) { $keytoreplace = ']('.$key; $valafter = ']('.$val; $content = preg_replace('/'.preg_quote($keytoreplace, '/').'/m', $valafter, $content); diff --git a/htdocs/core/lib/payments.lib.php b/htdocs/core/lib/payments.lib.php index 601dad3275d..835986f5f83 100644 --- a/htdocs/core/lib/payments.lib.php +++ b/htdocs/core/lib/payments.lib.php @@ -137,18 +137,15 @@ function getValidOnlinePaymentMethods($paymentmethod = '') $validpaymentmethod = array(); - if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) - { + if ((empty($paymentmethod) || $paymentmethod == 'paypal') && !empty($conf->paypal->enabled)) { $langs->load("paypal"); $validpaymentmethod['paypal'] = 'valid'; } - if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) - { + if ((empty($paymentmethod) || $paymentmethod == 'paybox') && !empty($conf->paybox->enabled)) { $langs->load("paybox"); $validpaymentmethod['paybox'] = 'valid'; } - if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) - { + if ((empty($paymentmethod) || $paymentmethod == 'stripe') && !empty($conf->stripe->enabled)) { $langs->load("stripe"); $validpaymentmethod['stripe'] = 'valid'; } @@ -205,102 +202,142 @@ function getOnlinePaymentUrl($mode, $type, $ref = '', $amount = '9.99', $freetag //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current $urltouse = DOL_MAIN_URL_ROOT; - if ($localorexternal) $urltouse = $urlwithroot; + if ($localorexternal) { + $urltouse = $urlwithroot; + } - if ($type == 'free') - { + if ($type == 'free') { $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; - else $out .= '&securekey='.dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { + $out .= '&securekey='.dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + } } //if ($mode) $out.='&noidempotency=1'; - } elseif ($type == 'order') - { + } elseif ($type == 'order') { $out = $urltouse.'/public/payment/newpayment.php?source=order&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'order_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'order_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + order_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + order_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } - } elseif ($type == 'invoice') - { + } elseif ($type == 'invoice') { $out = $urltouse.'/public/payment/newpayment.php?source=invoice&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'invoice_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'invoice_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + invoice_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + invoice_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } - } elseif ($type == 'contractline') - { + } elseif ($type == 'contractline') { $out = $urltouse.'/public/payment/newpayment.php?source=contractline&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'contractline_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'contractline_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + contractline_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + contractline_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } - } elseif ($type == 'member' || $type == 'membersubscription') - { + } elseif ($type == 'member' || $type == 'membersubscription') { $out = $urltouse.'/public/payment/newpayment.php?source=membersubscription&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'member_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'member_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + member_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + member_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } } - if ($type == 'donation') - { + if ($type == 'donation') { $out = $urltouse.'/public/payment/newpayment.php?source=donation&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'donation_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'donation_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) - { - if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; - else { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN)) { + if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { + $out .= '&securekey='.$conf->global->PAYMENT_SECURITY_TOKEN; + } else { $out .= '&securekey='.($mode ? '' : ''); - if ($mode == 1) $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + donation_ref)"; - if ($mode == 0) $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + if ($mode == 1) { + $out .= "hash('".$conf->global->PAYMENT_SECURITY_TOKEN."' + '".$type."' + donation_ref)"; + } + if ($mode == 0) { + $out .= dol_hash($conf->global->PAYMENT_SECURITY_TOKEN.$type.$ref, 2); + } $out .= ($mode ? '' : ''); } } } // For multicompany - if (!empty($out) && !empty($conf->multicompany->enabled)) $out .= "&entity=".$conf->entity; // Check the entity because we may have the same reference in several entities + if (!empty($out) && !empty($conf->multicompany->enabled)) { + $out .= "&entity=".$conf->entity; // Check the entity because we may have the same reference in several entities + } return $out; } @@ -323,78 +360,86 @@ function htmlPrintOnlinePaymentFooter($fromcompany, $langs, $addformmessage = 0, // Juridical status $line1 = ""; - if ($fromcompany->forme_juridique_code) - { + if ($fromcompany->forme_juridique_code) { $line1 .= ($line1 ? " - " : "").getFormeJuridiqueLabel($fromcompany->forme_juridique_code); } // Capital - if ($fromcompany->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)) - { + 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]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line1 .= ($line1 ? " - " : "").$field.": ".$fromcompany->idprof1; } // Prof Id 2 - if ($fromcompany->idprof2) - { + if ($fromcompany->idprof2) { $field = $langs->transcountrynoentities("ProfId2", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + 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) - { + if ($fromcompany->idprof3) { $field = $langs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof3; } // Prof Id 4 - if ($fromcompany->idprof4) - { + if ($fromcompany->idprof4) { $field = $langs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line2 .= ($line2 ? " - " : "").$field.": ".$fromcompany->idprof4; } // IntraCommunautary VAT - if ($fromcompany->tva_intra != '') - { + if ($fromcompany->tva_intra != '') { $line2 .= ($line2 ? " - " : "").$langs->transnoentities("VATIntraShort").": ".$fromcompany->tva_intra; } print '
    '; print '
    '."\n"; - if ($addformmessage) - { + 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); + 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) - { + 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); + 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 ' - '; + 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 613a68b56d8..08559c3ebd6 100644 --- a/htdocs/core/lib/pdf.lib.php +++ b/htdocs/core/lib/pdf.lib.php @@ -51,8 +51,7 @@ function pdf_getFormat(Translate $outputlangs = null, $mode = 'setup') // Default value if setup was not done and/or entry into c_paper_format not defined $width = 210; $height = 297; $unit = 'mm'; - if ($mode == 'auto' || empty($conf->global->MAIN_PDF_FORMAT) || $conf->global->MAIN_PDF_FORMAT == 'auto') - { + if ($mode == 'auto' || empty($conf->global->MAIN_PDF_FORMAT) || $conf->global->MAIN_PDF_FORMAT == 'auto') { include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $pdfformat = dol_getDefaultFormat($outputlangs); } else { @@ -62,11 +61,9 @@ function pdf_getFormat(Translate $outputlangs = null, $mode = 'setup') $sql = "SELECT code, label, width, height, unit FROM ".MAIN_DB_PREFIX."c_paper_format"; $sql .= " WHERE code = '".$db->escape($pdfformat)."'"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $width = (int) $obj->width; $height = (int) $obj->height; $unit = $obj->unit; @@ -90,8 +87,7 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P') global $conf; // Define constant for TCPDF - if (!defined('K_TCPDF_EXTERNAL_CONFIG')) - { + if (!defined('K_TCPDF_EXTERNAL_CONFIG')) { define('K_TCPDF_EXTERNAL_CONFIG', 1); // this avoid using tcpdf_config file define('K_PATH_CACHE', DOL_DATA_ROOT.'/admin/temp/'); define('K_PATH_URL_CACHE', DOL_DATA_ROOT.'/admin/temp/'); @@ -133,21 +129,27 @@ function pdf_getInstance($format = '', $metric = 'mm', $pagetype = 'P') require_once TCPDF_PATH.'tcpdf.php'; // We need to instantiate tcpdi object (instead of tcpdf) to use merging features. But we can disable it (this will break all merge features). - if (empty($conf->global->MAIN_DISABLE_TCPDI)) require_once TCPDI_PATH.'tcpdi.php'; + if (empty($conf->global->MAIN_DISABLE_TCPDI)) { + require_once TCPDI_PATH.'tcpdi.php'; + } //$arrayformat=pdf_getFormat(); //$format=array($arrayformat['width'],$arrayformat['height']); //$metric=$arrayformat['unit']; $pdfa = false; // PDF-1.3 - if (!empty($conf->global->PDF_USE_1A)) $pdfa = true; // PDF1/A + if (!empty($conf->global->PDF_USE_1A)) { + $pdfa = true; // PDF1/A + } - if (class_exists('TCPDI')) $pdf = new TCPDI($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa); - else $pdf = new TCPDF($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa); + if (class_exists('TCPDI')) { + $pdf = new TCPDI($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa); + } else { + $pdf = new TCPDF($pagetype, $metric, $format, true, 'UTF-8', false, $pdfa); + } // Protection and encryption of pdf - if (!empty($conf->global->PDF_SECURITY_ENCRYPTION)) - { + if (!empty($conf->global->PDF_SECURITY_ENCRYPTION)) { /* Permission supported by TCPDF - print : Print the document; - modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble'; @@ -223,13 +225,13 @@ function pdf_getPDFFont($outputlangs) { global $conf; - if (!empty($conf->global->MAIN_PDF_FORCE_FONT)) return $conf->global->MAIN_PDF_FORCE_FONT; + if (!empty($conf->global->MAIN_PDF_FORCE_FONT)) { + return $conf->global->MAIN_PDF_FORCE_FONT; + } $font = 'Helvetica'; // By default, for FPDI, or ISO language on TCPDF - if (class_exists('TCPDF')) // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower) - { - if ($outputlangs->trans('FONTFORPDF') != 'FONTFORPDF') - { + if (class_exists('TCPDF')) { // If TCPDF on, we can use an UTF8 one like DejaVuSans if required (slower) + if ($outputlangs->trans('FONTFORPDF') != 'FONTFORPDF') { $font = $outputlangs->trans('FONTFORPDF'); } } @@ -247,14 +249,14 @@ function pdf_getPDFFontSize($outputlangs) global $conf; $size = 10; // By default, for FPDI or ISO language on TCPDF - if (class_exists('TCPDF')) // If TCPDF on, we can use an UTF8 font like DejaVuSans if required (slower) - { - if ($outputlangs->trans('FONTSIZEFORPDF') != 'FONTSIZEFORPDF') - { + if (class_exists('TCPDF')) { // If TCPDF on, we can use an UTF8 font like DejaVuSans if required (slower) + if ($outputlangs->trans('FONTSIZEFORPDF') != 'FONTSIZEFORPDF') { $size = (int) $outputlangs->trans('FONTSIZEFORPDF'); } } - if (!empty($conf->global->MAIN_PDF_FORCE_FONT_SIZE)) $size = $conf->global->MAIN_PDF_FORCE_FONT_SIZE; + if (!empty($conf->global->MAIN_PDF_FORCE_FONT_SIZE)) { + $size = $conf->global->MAIN_PDF_FORCE_FONT_SIZE; + } return $size; } @@ -274,10 +276,11 @@ function pdf_getHeightForLogo($logo, $url = false) $maxwidth = 130; include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; $tmp = dol_getImageSize($logo, $url); - if ($tmp['height']) - { + if ($tmp['height']) { $width = round($height * $tmp['width'] / $tmp['height']); - if ($width > $maxwidth) $height = $height * $maxwidth / $width; + if ($width > $maxwidth) { + $height = $height * $maxwidth / $width; + } } //print $tmp['width'].' '.$tmp['height'].' '.$width; exit; return $height; @@ -377,82 +380,103 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t { global $conf, $hookmanager; - if ($mode == 'source' && !is_object($sourcecompany)) return -1; - if ($mode == 'target' && !is_object($targetcompany)) return -1; + if ($mode == 'source' && !is_object($sourcecompany)) { + return -1; + } + if ($mode == 'target' && !is_object($targetcompany)) { + return -1; + } - if (!empty($sourcecompany->state_id) && empty($sourcecompany->state)) $sourcecompany->state = getState($sourcecompany->state_id); - if (!empty($targetcompany->state_id) && empty($targetcompany->state)) $targetcompany->state = getState($targetcompany->state_id); + if (!empty($sourcecompany->state_id) && empty($sourcecompany->state)) { + $sourcecompany->state = getState($sourcecompany->state_id); + } + if (!empty($targetcompany->state_id) && empty($targetcompany->state)) { + $targetcompany->state = getState($targetcompany->state_id); + } $reshook = 0; $stringaddress = ''; - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('sourcecompany' => &$sourcecompany, 'targetcompany' => &$targetcompany, 'targetcontact' => &$targetcontact, 'outputlangs' => $outputlangs, 'mode' => $mode, 'usecontact' => $usecontact); $action = ''; $reshook = $hookmanager->executeHooks('pdf_build_address', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $stringaddress .= $hookmanager->resPrint; } - if (empty($reshook)) - { - if ($mode == 'source') - { + if (empty($reshook)) { + if ($mode == 'source') { $withCountry = 0; - if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) $withCountry = 1; + if (!empty($sourcecompany->country_code) && ($targetcompany->country_code != $sourcecompany->country_code)) { + $withCountry = 1; + } $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($sourcecompany, $withCountry, "\n", $outputlangs))."\n"; - if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS)) - { + if (empty($conf->global->MAIN_PDF_DISABLESOURCEDETAILS)) { // Phone - if ($sourcecompany->phone) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone); + if ($sourcecompany->phone) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("PhoneShort").": ".$outputlangs->convToOutputCharset($sourcecompany->phone); + } // Fax - if ($sourcecompany->fax) $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax); + if ($sourcecompany->fax) { + $stringaddress .= ($stringaddress ? ($sourcecompany->phone ? " - " : "\n") : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($sourcecompany->fax); + } // EMail - if ($sourcecompany->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email); + if ($sourcecompany->email) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($sourcecompany->email); + } // Web - if ($sourcecompany->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url); + if ($sourcecompany->url) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($sourcecompany->url); + } } // Intra VAT - if (!empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS)) - { - if ($sourcecompany->tva_intra) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra); + if (!empty($conf->global->MAIN_TVAINTRA_IN_SOURCE_ADDRESS)) { + if ($sourcecompany->tva_intra) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($sourcecompany->tva_intra); + } } // Professionnal Ids $reg = array(); - if (!empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof1)) - { + if (!empty($conf->global->MAIN_PROFID1_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof1)) { $tmp = $outputlangs->transcountrynoentities("ProfId1", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof1); } - if (!empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof2)) - { + if (!empty($conf->global->MAIN_PROFID2_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof2)) { $tmp = $outputlangs->transcountrynoentities("ProfId2", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof2); } - if (!empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof3)) - { + if (!empty($conf->global->MAIN_PROFID3_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof3)) { $tmp = $outputlangs->transcountrynoentities("ProfId3", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof3); } - if (!empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof4)) - { + if (!empty($conf->global->MAIN_PROFID4_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof4)) { $tmp = $outputlangs->transcountrynoentities("ProfId4", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof4); } - if (!empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof5)) - { + if (!empty($conf->global->MAIN_PROFID5_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof5)) { $tmp = $outputlangs->transcountrynoentities("ProfId5", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof5); } - if (!empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof6)) - { + if (!empty($conf->global->MAIN_PROFID6_IN_SOURCE_ADDRESS) && !empty($sourcecompany->idprof6)) { $tmp = $outputlangs->transcountrynoentities("ProfId6", $sourcecompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($sourcecompany->idprof6); } if (!empty($conf->global->PDF_ADD_MORE_AFTER_SOURCE_ADDRESS)) { @@ -460,10 +484,8 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t } } - if ($mode == 'target' || preg_match('/targetwithdetails/', $mode)) - { - if ($usecontact) - { + if ($mode == 'target' || preg_match('/targetwithdetails/', $mode)) { + if ($usecontact) { $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($targetcontact->getFullName($outputlangs, 1)); if (!empty($targetcontact->address)) { @@ -472,8 +494,7 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t $companytouseforaddress = $targetcompany; // Contact on a thirdparty that is a different thirdparty than the thirdparty of object - if ($targetcontact->socid > 0 && $targetcontact->socid != $targetcompany->id) - { + if ($targetcontact->socid > 0 && $targetcontact->socid != $targetcompany->id) { $targetcontact->fetch_thirdparty(); $companytouseforaddress = $targetcontact->thirdparty; } @@ -487,118 +508,142 @@ function pdf_build_address($outputlangs, $sourcecompany, $targetcompany = '', $t $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code)); } - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) - { + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) { // Phone - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) - { - if (!empty($targetcontact->phone_pro) || !empty($targetcontact->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": "; - if (!empty($targetcontact->phone_pro)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro); - if (!empty($targetcontact->phone_pro) && !empty($targetcontact->phone_mobile)) $stringaddress .= " / "; - if (!empty($targetcontact->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) { + if (!empty($targetcontact->phone_pro) || !empty($targetcontact->phone_mobile)) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": "; + } + if (!empty($targetcontact->phone_pro)) { + $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_pro); + } + if (!empty($targetcontact->phone_pro) && !empty($targetcontact->phone_mobile)) { + $stringaddress .= " / "; + } + if (!empty($targetcontact->phone_mobile)) { + $stringaddress .= $outputlangs->convToOutputCharset($targetcontact->phone_mobile); + } } // Fax - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) - { - if ($targetcontact->fax) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) { + if ($targetcontact->fax) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcontact->fax); + } } // EMail - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) - { - if ($targetcontact->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) { + if ($targetcontact->email) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcontact->email); + } } // Web - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) - { - if ($targetcontact->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) { + if ($targetcontact->url) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcontact->url); + } } } } else { $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset(dol_format_address($targetcompany)); // Country - if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code)); + if (!empty($targetcompany->country_code) && $targetcompany->country_code != $sourcecompany->country_code) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->convToOutputCharset($outputlangs->transnoentitiesnoconv("Country".$targetcompany->country_code)); + } - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) - { + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || preg_match('/targetwithdetails/', $mode)) { // Phone - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) - { - if (!empty($targetcompany->phone) || !empty($targetcompany->phone_mobile)) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": "; - if (!empty($targetcompany->phone)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone); - if (!empty($targetcompany->phone) && !empty($targetcompany->phone_mobile)) $stringaddress .= " / "; - if (!empty($targetcompany->phone_mobile)) $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_phone/', $mode)) { + if (!empty($targetcompany->phone) || !empty($targetcompany->phone_mobile)) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Phone").": "; + } + if (!empty($targetcompany->phone)) { + $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone); + } + if (!empty($targetcompany->phone) && !empty($targetcompany->phone_mobile)) { + $stringaddress .= " / "; + } + if (!empty($targetcompany->phone_mobile)) { + $stringaddress .= $outputlangs->convToOutputCharset($targetcompany->phone_mobile); + } } // Fax - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) - { - if ($targetcompany->fax) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_fax/', $mode)) { + if ($targetcompany->fax) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Fax").": ".$outputlangs->convToOutputCharset($targetcompany->fax); + } } // EMail - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) - { - if ($targetcompany->email) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_email/', $mode)) { + if ($targetcompany->email) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Email").": ".$outputlangs->convToOutputCharset($targetcompany->email); + } } // Web - if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) - { - if ($targetcompany->url) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url); + if (!empty($conf->global->MAIN_PDF_ADDALSOTARGETDETAILS) || $mode == 'targetwithdetails' || preg_match('/targetwithdetails_url/', $mode)) { + if ($targetcompany->url) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("Web").": ".$outputlangs->convToOutputCharset($targetcompany->url); + } } } } // Intra VAT - if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS)) - { - if ($targetcompany->tva_intra) $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra); + if (empty($conf->global->MAIN_TVAINTRA_NOT_IN_ADDRESS)) { + if ($targetcompany->tva_intra) { + $stringaddress .= ($stringaddress ? "\n" : '').$outputlangs->transnoentities("VATIntraShort").': '.$outputlangs->convToOutputCharset($targetcompany->tva_intra); + } } // Professionnal Ids - if (!empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && !empty($targetcompany->idprof1)) - { + if (!empty($conf->global->MAIN_PROFID1_IN_ADDRESS) && !empty($targetcompany->idprof1)) { $tmp = $outputlangs->transcountrynoentities("ProfId1", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof1); } - if (!empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && !empty($targetcompany->idprof2)) - { + if (!empty($conf->global->MAIN_PROFID2_IN_ADDRESS) && !empty($targetcompany->idprof2)) { $tmp = $outputlangs->transcountrynoentities("ProfId2", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof2); } - if (!empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && !empty($targetcompany->idprof3)) - { + if (!empty($conf->global->MAIN_PROFID3_IN_ADDRESS) && !empty($targetcompany->idprof3)) { $tmp = $outputlangs->transcountrynoentities("ProfId3", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof3); } - if (!empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && !empty($targetcompany->idprof4)) - { + if (!empty($conf->global->MAIN_PROFID4_IN_ADDRESS) && !empty($targetcompany->idprof4)) { $tmp = $outputlangs->transcountrynoentities("ProfId4", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof4); } - if (!empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && !empty($targetcompany->idprof5)) - { + if (!empty($conf->global->MAIN_PROFID5_IN_ADDRESS) && !empty($targetcompany->idprof5)) { $tmp = $outputlangs->transcountrynoentities("ProfId5", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof5); } - if (!empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && !empty($targetcompany->idprof6)) - { + if (!empty($conf->global->MAIN_PROFID6_IN_ADDRESS) && !empty($targetcompany->idprof6)) { $tmp = $outputlangs->transcountrynoentities("ProfId6", $targetcompany->country_code); - if (preg_match('/\((.+)\)/', $tmp, $reg)) $tmp = $reg[1]; + if (preg_match('/\((.+)\)/', $tmp, $reg)) { + $tmp = $reg[1]; + } $stringaddress .= ($stringaddress ? "\n" : '').$tmp.': '.$outputlangs->convToOutputCharset($targetcompany->idprof6); } // Public note - if (!empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS)) - { - if ($mode == 'source' && !empty($sourcecompany->note_public)) - { + if (!empty($conf->global->MAIN_PUBLIC_NOTE_IN_ADDRESS)) { + if ($mode == 'source' && !empty($sourcecompany->note_public)) { $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($sourcecompany->note_public); } - if (($mode == 'target' || preg_match('/targetwithdetails/', $mode)) && !empty($targetcompany->note_public)) - { + if (($mode == 'target' || preg_match('/targetwithdetails/', $mode)) && !empty($targetcompany->note_public)) { $stringaddress .= ($stringaddress ? "\n" : '').dol_string_nohtmltag($targetcompany->note_public); } } @@ -622,8 +667,7 @@ function pdf_pagehead(&$pdf, $outputlangs, $page_height) global $conf; // Add a background image on document - if (!empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF)) // Warning, this option make TCPDF generation being crazy and some content disappeared behind the image - { + if (!empty($conf->global->MAIN_USE_BACKGROUND_ON_PDF)) { // Warning, this option make TCPDF generation being crazy and some content disappeared behind the image $pdf->SetAutoPageBreak(0, 0); // Disable auto pagebreak before adding image $pdf->Image($conf->mycompany->dir_output.'/logos/'.$conf->global->MAIN_USE_BACKGROUND_ON_PDF, (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_X) ? $conf->global->MAIN_USE_BACKGROUND_ON_PDF_X : 0), (isset($conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y) ? $conf->global->MAIN_USE_BACKGROUND_ON_PDF_Y : 0), 0, $page_height); $pdf->SetAutoPageBreak(1, 0); // Restore pagebreak @@ -665,10 +709,15 @@ function pdf_watermark(&$pdf, $outputlangs, $h, $w, $unit, $text) global $langs, $mysoc, $user; // Print Draft Watermark - if ($unit == 'pt') $k = 1; - elseif ($unit == 'mm') $k = 72 / 25.4; - elseif ($unit == 'cm') $k = 72 / 2.54; - elseif ($unit == 'in') $k = 72; + if ($unit == 'pt') { + $k = 1; + } elseif ($unit == 'mm') { + $k = 72 / 25.4; + } elseif ($unit == 'cm') { + $k = 72 / 2.54; + } elseif ($unit == 'in') { + $k = 72; + } // Make substitution $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, null); @@ -719,8 +768,7 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, $diffsizecontent = (empty($conf->global->PDF_DIFFSIZE_CONTENT) ? 4 : $conf->global->PDF_DIFFSIZE_CONTENT); $pdf->SetXY($curx, $cury); - if (empty($onlynumber)) - { + if (empty($onlynumber)) { $pdf->SetFont('', 'B', $default_font_size - $diffsizetitle); $pdf->MultiCell(100, 3, $outputlangs->transnoentities('PaymentByTransferOnThisBankAccount').':', 0, 'L', 0); $cury += 4; @@ -730,36 +778,36 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, // Use correct name of bank id according to country $bickey = "BICNumber"; - if ($account->getCountryCode() == 'IN') $bickey = "SWIFT"; + if ($account->getCountryCode() == 'IN') { + $bickey = "SWIFT"; + } // Get format of bank account according to its country $usedetailedbban = $account->useDetailedBBAN(); //$onlynumber=0; $usedetailedbban=1; // For tests - if ($usedetailedbban) - { + if ($usedetailedbban) { $savcurx = $curx; - if (empty($onlynumber)) - { + if (empty($onlynumber)) { $pdf->SetFont('', '', $default_font_size - $diffsizecontent); $pdf->SetXY($curx, $cury); $pdf->MultiCell(100, 3, $outputlangs->transnoentities("Bank").': '.$outputlangs->convToOutputCharset($account->bank), 0, 'L', 0); $cury += 3; } - if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN)) // Note that some countries still need bank number, BIC/IBAN not enougth for them - { + if (empty($conf->global->PDF_BANK_HIDE_NUMBER_SHOW_ONLY_BICIBAN)) { // Note that some countries still need bank number, BIC/IBAN not enougth for them // Note: // bank = code_banque (FR), sort code (GB, IR. Example: 12-34-56) // desk = code guichet (FR), used only when $usedetailedbban = 1 // number = account number // key = check control key used only when $usedetailedbban = 1 - if (empty($onlynumber)) $pdf->line($curx + 1, $cury + 1, $curx + 1, $cury + 6); + if (empty($onlynumber)) { + $pdf->line($curx + 1, $cury + 1, $curx + 1, $cury + 6); + } - foreach ($account->getFieldsToShow() as $val) - { + foreach ($account->getFieldsToShow() as $val) { $pdf->SetXY($curx, $cury + 4); $pdf->SetFont('', '', $default_font_size - 3); @@ -812,7 +860,9 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, $pdf->MultiCell(100, 3, $outputlangs->transnoentities("BankAccountNumber").': '.$outputlangs->convToOutputCharset($account->number), 0, 'L', 0); $cury += 3; - if ($diffsizecontent <= 2) $cury += 1; + if ($diffsizecontent <= 2) { + $cury += 1; + } } $pdf->SetFont('', '', $default_font_size - $diffsizecontent); @@ -840,17 +890,17 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, // Use correct name of bank id according to country $ibankey = FormBank::getIBANLabel($account); - if (!empty($account->iban)) - { + if (!empty($account->iban)) { //Remove whitespaces to ensure we are dealing with the format we expect $ibanDisplay_temp = str_replace(' ', '', $outputlangs->convToOutputCharset($account->iban)); $ibanDisplay = ""; $nbIbanDisplay_temp = dol_strlen($ibanDisplay_temp); - for ($i = 0; $i < $nbIbanDisplay_temp; $i++) - { + for ($i = 0; $i < $nbIbanDisplay_temp; $i++) { $ibanDisplay .= $ibanDisplay_temp[$i]; - if ($i % 4 == 3 && $i > 0) $ibanDisplay .= " "; + if ($i % 4 == 3 && $i > 0) { + $ibanDisplay .= " "; + } } $pdf->SetFont('', 'B', $default_font_size - 3); @@ -859,8 +909,7 @@ function pdf_bank(&$pdf, $outputlangs, $curx, $cury, $account, $onlynumber = 0, $cury += 3; } - if (!empty($account->bic)) - { + if (!empty($account->bic)) { $pdf->SetFont('', 'B', $default_font_size - 3); $pdf->SetXY($curx, $cury); $pdf->MultiCell(100, 3, $outputlangs->transnoentities($bickey).': '.$outputlangs->convToOutputCharset($account->bic), 0, 'L', 0); @@ -894,8 +943,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $dims = $pdf->getPageDimensions(); // Line of free text - if (empty($hidefreetext) && !empty($conf->global->$paramfreetext)) - { + if (empty($hidefreetext) && !empty($conf->global->$paramfreetext)) { $substitutionarray = pdf_getSubstitutionArray($outputlangs, null, $object); // More substitution keys $substitutionarray['__FROM_NAME__'] = $fromcompany->name; @@ -915,124 +963,118 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ // First line of company infos $line1 = ""; $line2 = ""; $line3 = ""; $line4 = ""; - if ($showdetails == 1 || $showdetails == 3) - { + if ($showdetails == 1 || $showdetails == 3) { // Company name - if ($fromcompany->name) - { + if ($fromcompany->name) { $line1 .= ($line1 ? " - " : "").$outputlangs->transnoentities("RegisteredOffice").": ".$fromcompany->name; } // Address - if ($fromcompany->address) - { + if ($fromcompany->address) { $line1 .= ($line1 ? " - " : "").str_replace("\n", ", ", $fromcompany->address); } // Zip code - if ($fromcompany->zip) - { + if ($fromcompany->zip) { $line1 .= ($line1 ? " - " : "").$fromcompany->zip; } // Town - if ($fromcompany->town) - { + if ($fromcompany->town) { $line1 .= ($line1 ? " " : "").$fromcompany->town; } // Country - if ($fromcompany->country) - { + if ($fromcompany->country) { $line1 .= ($line1 ? ", " : "").$fromcompany->country; } // Phone - if ($fromcompany->phone) - { + if ($fromcompany->phone) { $line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Phone").": ".$fromcompany->phone; } // Fax - if ($fromcompany->fax) - { + if ($fromcompany->fax) { $line2 .= ($line2 ? " - " : "").$outputlangs->transnoentities("Fax").": ".$fromcompany->fax; } // URL - if ($fromcompany->url) - { + if ($fromcompany->url) { $line2 .= ($line2 ? " - " : "").$fromcompany->url; } // Email - if ($fromcompany->email) - { + if ($fromcompany->email) { $line2 .= ($line2 ? " - " : "").$fromcompany->email; } } - if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE')) - { + if ($showdetails == 2 || $showdetails == 3 || ($fromcompany->country_code == 'DE')) { // Managers - if ($fromcompany->managers) - { + if ($fromcompany->managers) { $line2 .= ($line2 ? " - " : "").$fromcompany->managers; } } // Line 3 of company infos // Juridical status - if ($fromcompany->forme_juridique_code) - { + if ($fromcompany->forme_juridique_code) { $line3 .= ($line3 ? " - " : "").$outputlangs->convToOutputCharset(getFormeJuridiqueLabel($fromcompany->forme_juridique_code)); } // Capital - if ($fromcompany->capital) - { + if ($fromcompany->capital) { $tmpamounttoshow = price2num($fromcompany->capital); // This field is a free string - if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency)); - else $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", $tmpamounttoshow, $outputlangs); + if (is_numeric($tmpamounttoshow) && $tmpamounttoshow > 0) { + $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", price($tmpamounttoshow, 0, $outputlangs, 0, 0, 0, $conf->currency)); + } else { + $line3 .= ($line3 ? " - " : "").$outputlangs->transnoentities("CapitalOf", $tmpamounttoshow, $outputlangs); + } } // Prof Id 1 - if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) - { + if ($fromcompany->idprof1 && ($fromcompany->country_code != 'FR' || !$fromcompany->idprof2)) { $field = $outputlangs->transcountrynoentities("ProfId1", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line3 .= ($line3 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof1); } // Prof Id 2 - if ($fromcompany->idprof2) - { + if ($fromcompany->idprof2) { $field = $outputlangs->transcountrynoentities("ProfId2", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line3 .= ($line3 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof2); } // Line 4 of company infos // Prof Id 3 - if ($fromcompany->idprof3) - { + if ($fromcompany->idprof3) { $field = $outputlangs->transcountrynoentities("ProfId3", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof3); } // Prof Id 4 - if ($fromcompany->idprof4) - { + if ($fromcompany->idprof4) { $field = $outputlangs->transcountrynoentities("ProfId4", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof4); } // Prof Id 5 - if ($fromcompany->idprof5) - { + if ($fromcompany->idprof5) { $field = $outputlangs->transcountrynoentities("ProfId5", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof5); } // Prof Id 6 - if ($fromcompany->idprof6) - { + if ($fromcompany->idprof6) { $field = $outputlangs->transcountrynoentities("ProfId6", $fromcompany->country_code); - if (preg_match('/\((.*)\)/i', $field, $reg)) $field = $reg[1]; + if (preg_match('/\((.*)\)/i', $field, $reg)) { + $field = $reg[1]; + } $line4 .= ($line4 ? " - " : "").$field.": ".$outputlangs->convToOutputCharset($fromcompany->idprof6); } // IntraCommunautary VAT - if ($fromcompany->tva_intra != '') - { + if ($fromcompany->tva_intra != '') { $line4 .= ($line4 ? " - " : "").$outputlangs->transnoentities("VATIntraShort").": ".$outputlangs->convToOutputCharset($fromcompany->tva_intra); } @@ -1041,11 +1083,9 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ // The start of the bottom of this page footer is positioned according to # of lines $freetextheight = 0; - if ($line) // Free text - { + if ($line) { // Free text //$line="sample text
    \nfdsfsdf
    \nghfghg
    "; - if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) - { + if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { $width = 20000; $align = 'L'; // By default, ask a manual break: We use a large value 20000, to not have automatic wrap. This make user understand, he need to add CR on its text. if (!empty($conf->global->MAIN_USE_AUTOWRAP_ON_FREETEXT)) { $width = 200; $align = 'C'; @@ -1060,11 +1100,9 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $marginwithfooter = $marge_basse + $freetextheight + (!empty($line1) ? 3 : 0) + (!empty($line2) ? 3 : 0) + (!empty($line3) ? 3 : 0) + (!empty($line4) ? 3 : 0); $posy = $marginwithfooter + 0; - if ($line) // Free text - { + if ($line) { // Free text $pdf->SetXY($dims['lm'], -$posy); - if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) // by default - { + if (empty($conf->global->PDF_ALLOW_HTML_FOR_FREE_TEXT)) { // by default $pdf->MultiCell(0, 3, $line, 0, $align, 0); } else { $pdf->writeHTMLCell($pdf->page_largeur - $pdf->margin_left - $pdf->margin_right, $freetextheight, $dims['lm'], $dims['hk'] - $marginwithfooter, dol_htmlentitiesbr($line, 1, 'UTF-8', 0)); @@ -1076,8 +1114,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $pdf->line($dims['lm'], $dims['hk'] - $posy, $dims['wk'] - $dims['rm'], $dims['hk'] - $posy); $posy--; - if (!empty($line1)) - { + if (!empty($line1)) { $pdf->SetFont('', 'B', 7); $pdf->SetXY($dims['lm'], -$posy); $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line1, 0, 'C', 0); @@ -1085,8 +1122,7 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $pdf->SetFont('', '', 7); } - if (!empty($line2)) - { + if (!empty($line2)) { $pdf->SetFont('', 'B', 7); $pdf->SetXY($dims['lm'], -$posy); $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line2, 0, 'C', 0); @@ -1094,22 +1130,19 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ $pdf->SetFont('', '', 7); } - if (!empty($line3)) - { + if (!empty($line3)) { $pdf->SetXY($dims['lm'], -$posy); $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line3, 0, 'C', 0); } - if (!empty($line4)) - { + if (!empty($line4)) { $posy -= 3; $pdf->SetXY($dims['lm'], -$posy); $pdf->MultiCell($dims['wk'] - $dims['rm'] - $dims['lm'], 2, $line4, 0, 'C', 0); } // Show page nb only on iso languages (so default Helvetica font) - if (strtolower(pdf_getPDFFont($outputlangs)) == 'helvetica') - { + if (strtolower(pdf_getPDFFont($outputlangs)) == 'helvetica') { $pdf->SetXY($dims['wk'] - $dims['rm'] - 15, -$posy); //print 'xxx'.$pdf->PageNo().'-'.$pdf->getAliasNbPages().'-'.$pdf->getAliasNumPage();exit; $pdf->MultiCell(15, 2, $pdf->PageNo().'/'.$pdf->getAliasNbPages(), 0, 'R', 0); @@ -1135,13 +1168,10 @@ function pdf_pagefoot(&$pdf, $outputlangs, $paramfreetext, $fromcompany, $marge_ function pdf_writeLinkedObjects(&$pdf, $object, $outputlangs, $posx, $posy, $w, $h, $align, $default_font_size) { $linkedobjects = pdf_getLinkedObjects($object, $outputlangs); - if (!empty($linkedobjects)) - { - foreach ($linkedobjects as $linkedobject) - { + if (!empty($linkedobjects)) { + foreach ($linkedobjects as $linkedobject) { $reftoshow = $linkedobject["ref_title"].' : '.$linkedobject["ref_value"]; - if (!empty($linkedobject["date_value"])) - { + if (!empty($linkedobject["date_value"])) { $reftoshow .= ' / '.$linkedobject["date_value"]; } @@ -1178,18 +1208,20 @@ function pdf_writelinedesc(&$pdf, $object, $i, $outputlangs, $w, $h, $posx, $pos $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = empty($object->lines[$i]->special_code) ? '' : $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('pdf'=>$pdf, 'i'=>$i, 'outputlangs'=>$outputlangs, 'w'=>$w, 'h'=>$h, 'posx'=>$posx, 'posy'=>$posy, 'hideref'=>$hideref, 'hidedesc'=>$hidedesc, 'issupplierline'=>$issupplierline, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_writelinedesc', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { + if (empty($reshook)) { $labelproductservice = pdf_getlinedesc($object, $i, $outputlangs, $hideref, $hidedesc, $issupplierline); //var_dump($labelproductservice);exit; @@ -1229,8 +1261,7 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $note = (!empty($object->lines[$i]->note) ? $object->lines[$i]->note : ''); $dbatch = (!empty($object->lines[$i]->detail_batch) ? $object->lines[$i]->detail_batch : false); - if ($issupplierline) - { + if ($issupplierline) { include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $prodser = new ProductFournisseur($db); } else { @@ -1238,16 +1269,14 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $prodser = new Product($db); if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { - include_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; + include_once DOL_DOCUMENT_ROOT . '/product/class/productcustomerprice.class.php'; } } - if ($idprod) - { + if ($idprod) { $prodser->fetch($idprod); // If a predefined product and multilang and on other lang, we renamed label with label translated - if (!empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && ($outputlangs->defaultlang != $langs->defaultlang)) { $translatealsoifmodified = (!empty($conf->global->MAIN_MULTILANG_TRANSLATE_EVEN_IF_MODIFIED)); // By default if value was modified manually, we keep it (no translation because we don't have it) // TODO Instead of making a compare to see if param was modified, check that content contains reference translation. If yes, add the added part to the new translation @@ -1269,11 +1298,15 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, } else { $textwasmodified = ($desc == $prodser->description); } - if (!empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified)) $desc = $prodser->multilangs[$outputlangs->defaultlang]["description"]; + if (!empty($prodser->multilangs[$outputlangs->defaultlang]["description"]) && ($textwasmodified || $translatealsoifmodified)) { + $desc = $prodser->multilangs[$outputlangs->defaultlang]["description"]; + } // Set note $textwasmodified = ($note == $prodser->note); - if (!empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified)) $note = $prodser->multilangs[$outputlangs->defaultlang]["note"]; + if (!empty($prodser->multilangs[$outputlangs->defaultlang]["note"]) && ($textwasmodified || $translatealsoifmodified)) { + $note = $prodser->multilangs[$outputlangs->defaultlang]["note"]; + } } } elseif ($object->element == 'facture' || $object->element == 'facturefourn') { if ($object->type == $object::TYPE_DEPOSIT) { @@ -1299,34 +1332,30 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, } // Description long of product line - if (!empty($desc) && ($desc != $label)) - { - if ($libelleproduitservice && empty($hidedesc)) - { + if (!empty($desc) && ($desc != $label)) { + if ($libelleproduitservice && empty($hidedesc)) { $libelleproduitservice .= '__N__'; } - if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except) - { + if ($desc == '(CREDIT_NOTE)' && $object->lines[$i]->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $sourceref = !empty($discount->discount_type) ? $discount->ref_invoive_supplier_source : $discount->ref_facture_source; $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromCreditNote", $sourceref); - } elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except) - { + } elseif ($desc == '(DEPOSIT)' && $object->lines[$i]->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $sourceref = !empty($discount->discount_type) ? $discount->ref_invoive_supplier_source : $discount->ref_facture_source; $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromDeposit", $sourceref); // Add date of deposit - if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) $libelleproduitservice .= ' ('.dol_print_date($discount->datec, 'day', '', $outputlangs).')'; - } elseif ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except) - { + if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) { + $libelleproduitservice .= ' ('.dol_print_date($discount->datec, 'day', '', $outputlangs).')'; + } + } elseif ($desc == '(EXCESS RECEIVED)' && $object->lines[$i]->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessReceived", $discount->ref_facture_source); - } elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except) - { + } elseif ($desc == '(EXCESS PAID)' && $object->lines[$i]->fk_remise_except) { $discount = new DiscountAbsolute($db); $discount->fetch($object->lines[$i]->fk_remise_except); $libelleproduitservice = $outputlangs->transnoentitiesnoconv("DiscountFromExcessPaid", $discount->ref_invoice_supplier_source); @@ -1371,7 +1400,9 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, if ($issupplierline) { if (empty($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES)) { // Common case $ref_prodserv = $prodser->ref; // Show local ref - if ($ref_supplier) $ref_prodserv .= ($prodser->ref ? ' (' : '').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref ? ')' : ''); + if ($ref_supplier) { + $ref_prodserv .= ($prodser->ref ? ' (' : '').$outputlangs->transnoentitiesnoconv("SupplierRef").' '.$ref_supplier.($prodser->ref ? ')' : ''); + } } elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 1) { $ref_prodserv = $ref_supplier; } elseif ($conf->global->PDF_HIDE_PRODUCT_REF_IN_SUPPLIER_LINES == 2) { @@ -1381,69 +1412,68 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, $ref_prodserv = $prodser->ref; // Show local ref only if (! empty($conf->global->PRODUIT_CUSTOMER_PRICES)) { - $productCustomerPriceStatic = new Productcustomerprice($db); - $filter = array('fk_product' => $idprod, 'fk_soc' => $object->socid); + $productCustomerPriceStatic = new Productcustomerprice($db); + $filter = array('fk_product' => $idprod, 'fk_soc' => $object->socid); - $nbCustomerPrices = $productCustomerPriceStatic->fetch_all('', '', 1, 0, $filter); + $nbCustomerPrices = $productCustomerPriceStatic->fetch_all('', '', 1, 0, $filter); - if ($nbCustomerPrices > 0) { - $productCustomerPrice = $productCustomerPriceStatic->lines[0]; + if ($nbCustomerPrices > 0) { + $productCustomerPrice = $productCustomerPriceStatic->lines[0]; - if (! empty($productCustomerPrice->ref_customer)) { - switch ($conf->global->PRODUIT_CUSTOMER_PRICES_PDF_REF_MODE) { - case 1: - $ref_prodserv = $productCustomerPrice->ref_customer; - break; + if (! empty($productCustomerPrice->ref_customer)) { + switch ($conf->global->PRODUIT_CUSTOMER_PRICES_PDF_REF_MODE) { + case 1: + $ref_prodserv = $productCustomerPrice->ref_customer; + break; - case 2: - $ref_prodserv = $productCustomerPrice->ref_customer . ' (' . $outputlangs->transnoentitiesnoconv('InternalRef') . ' ' . $ref_prodserv . ')'; - break; + case 2: + $ref_prodserv = $productCustomerPrice->ref_customer . ' (' . $outputlangs->transnoentitiesnoconv('InternalRef') . ' ' . $ref_prodserv . ')'; + break; - default: - $ref_prodserv = $ref_prodserv . ' (' . $outputlangs->transnoentitiesnoconv('RefCustomer') . ' ' . $productCustomerPrice->ref_customer . ')'; - } - } - } + default: + $ref_prodserv = $ref_prodserv . ' (' . $outputlangs->transnoentitiesnoconv('RefCustomer') . ' ' . $productCustomerPrice->ref_customer . ')'; + } + } + } } } - if (!empty($libelleproduitservice) && !empty($ref_prodserv)) $ref_prodserv .= " - "; + if (!empty($libelleproduitservice) && !empty($ref_prodserv)) { + $ref_prodserv .= " - "; + } } - if (!empty($ref_prodserv) && !empty($conf->global->PDF_BOLD_PRODUCT_REF_AND_PERIOD)) { $ref_prodserv = ''.$ref_prodserv.''; } + if (!empty($ref_prodserv) && !empty($conf->global->PDF_BOLD_PRODUCT_REF_AND_PERIOD)) { + $ref_prodserv = ''.$ref_prodserv.''; + } $libelleproduitservice = $prefix_prodserv.$ref_prodserv.$libelleproduitservice; // Add an additional description for the category products - if (!empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && !empty($conf->categorie->enabled)) - { + if (!empty($conf->global->CATEGORY_ADD_DESC_INTO_DOC) && $idprod && !empty($conf->categorie->enabled)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $categstatic = new Categorie($db); // recovering the list of all the categories linked to product $tblcateg = $categstatic->containing($idprod, Categorie::TYPE_PRODUCT); - foreach ($tblcateg as $cate) - { + foreach ($tblcateg as $cate) { // Adding the descriptions if they are filled $desccateg = $cate->description; - if ($desccateg) + if ($desccateg) { $libelleproduitservice .= '__N__'.$desccateg; + } } } - if (!empty($object->lines[$i]->date_start) || !empty($object->lines[$i]->date_end)) - { + if (!empty($object->lines[$i]->date_start) || !empty($object->lines[$i]->date_end)) { $format = 'day'; $period = ''; // Show duration if exists - if ($object->lines[$i]->date_start && $object->lines[$i]->date_end) - { + if ($object->lines[$i]->date_start && $object->lines[$i]->date_end) { $period = '('.$outputlangs->transnoentitiesnoconv('DateFromTo', dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs), dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')'; } - if ($object->lines[$i]->date_start && !$object->lines[$i]->date_end) - { + if ($object->lines[$i]->date_start && !$object->lines[$i]->date_end) { $period = '('.$outputlangs->transnoentitiesnoconv('DateFrom', dol_print_date($object->lines[$i]->date_start, $format, false, $outputlangs)).')'; } - if (!$object->lines[$i]->date_start && $object->lines[$i]->date_end) - { + if (!$object->lines[$i]->date_start && $object->lines[$i]->date_end) { $period = '('.$outputlangs->transnoentitiesnoconv('DateUntil', dol_print_date($object->lines[$i]->date_end, $format, false, $outputlangs)).')'; } //print '>'.$outputlangs->charset_output.','.$period; @@ -1455,23 +1485,30 @@ function pdf_getlinedesc($object, $i, $outputlangs, $hideref = 0, $hidedesc = 0, //print $libelleproduitservice; } - if ($dbatch) - { + if ($dbatch) { $format = 'day'; - foreach ($dbatch as $detail) - { + foreach ($dbatch as $detail) { $dte = array(); - if ($detail->eatby) $dte[] = $outputlangs->transnoentitiesnoconv('printEatby', dol_print_date($detail->eatby, $format, false, $outputlangs)); - if ($detail->sellby) $dte[] = $outputlangs->transnoentitiesnoconv('printSellby', dol_print_date($detail->sellby, $format, false, $outputlangs)); - if ($detail->batch) $dte[] = $outputlangs->transnoentitiesnoconv('printBatch', $detail->batch); + if ($detail->eatby) { + $dte[] = $outputlangs->transnoentitiesnoconv('printEatby', dol_print_date($detail->eatby, $format, false, $outputlangs)); + } + if ($detail->sellby) { + $dte[] = $outputlangs->transnoentitiesnoconv('printSellby', dol_print_date($detail->sellby, $format, false, $outputlangs)); + } + if ($detail->batch) { + $dte[] = $outputlangs->transnoentitiesnoconv('printBatch', $detail->batch); + } $dte[] = $outputlangs->transnoentitiesnoconv('printQty', $detail->qty); $libelleproduitservice .= "__N__ ".implode(" - ", $dte); } } // Now we convert \n into br - if (dol_textishtml($libelleproduitservice)) $libelleproduitservice = preg_replace('/__N__/', '
    ', $libelleproduitservice); - else $libelleproduitservice = preg_replace('/__N__/', "\n", $libelleproduitservice); + if (dol_textishtml($libelleproduitservice)) { + $libelleproduitservice = preg_replace('/__N__/', '
    ', $libelleproduitservice); + } else { + $libelleproduitservice = preg_replace('/__N__/', "\n", $libelleproduitservice); + } $libelleproduitservice = dol_htmlentitiesbr($libelleproduitservice, 1); return $libelleproduitservice; @@ -1493,17 +1530,17 @@ function pdf_getlinenum($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlinenum', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $result .= $hookmanager->resPrint; } - if (empty($reshook)) - { + if (empty($reshook)) { $result .= dol_htmlentitiesbr($object->lines[$i]->num); } return $result; @@ -1526,17 +1563,17 @@ function pdf_getlineref($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineref', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $result .= $hookmanager->resPrint; } - if (empty($reshook)) - { + if (empty($reshook)) { $result .= dol_htmlentitiesbr($object->lines[$i]->product_ref); } return $result; @@ -1558,17 +1595,17 @@ function pdf_getlineref_supplier($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineref_supplier', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $result .= $hookmanager->resPrint; } - if (empty($reshook)) - { + if (empty($reshook)) { $result .= dol_htmlentitiesbr($object->lines[$i]->ref_supplier); } return $result; @@ -1590,38 +1627,41 @@ function pdf_getlinevatrate($object, $i, $outputlangs, $hidedetails = 0) $result = ''; $reshook = 0; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduce this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlinevatrate', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if (empty($hidedetails) || $hidedetails > 1) - { + if (empty($reshook)) { + if (empty($hidedetails) || $hidedetails > 1) { $tmpresult = ''; $tmpresult .= vatrate($object->lines[$i]->tva_tx, 0, $object->lines[$i]->info_bits, -1); - if (empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX)) - { - if ($object->lines[$i]->total_localtax1 != 0) - { - if (preg_replace('/[\s0%]/', '', $tmpresult)) $tmpresult .= '/'; - else $tmpresult = ''; + if (empty($conf->global->MAIN_PDF_MAIN_HIDE_SECOND_TAX)) { + if ($object->lines[$i]->total_localtax1 != 0) { + if (preg_replace('/[\s0%]/', '', $tmpresult)) { + $tmpresult .= '/'; + } else { + $tmpresult = ''; + } $tmpresult .= vatrate(abs($object->lines[$i]->localtax1_tx), 0); } } - if (empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX)) - { - if ($object->lines[$i]->total_localtax2 != 0) - { - if (preg_replace('/[\s0%]/', '', $tmpresult)) $tmpresult .= '/'; - else $tmpresult = ''; + if (empty($conf->global->MAIN_PDF_MAIN_HIDE_THIRD_TAX)) { + if ($object->lines[$i]->total_localtax2 != 0) { + if (preg_replace('/[\s0%]/', '', $tmpresult)) { + $tmpresult .= '/'; + } else { + $tmpresult = ''; + } $tmpresult .= vatrate(abs($object->lines[$i]->localtax2_tx), 0); } } @@ -1647,25 +1687,28 @@ function pdf_getlineupexcltax($object, $i, $outputlangs, $hidedetails = 0) global $conf, $hookmanager; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } $result = ''; $reshook = 0; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineupexcltax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if (empty($hidedetails) || $hidedetails > 1) - { + if (empty($reshook)) { + if (empty($hidedetails) || $hidedetails > 1) { $subprice = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_subprice : $object->lines[$i]->subprice); $result .= price($sign * $subprice, 0, $outputlangs); } @@ -1687,24 +1730,30 @@ function pdf_getlineupwithtax($object, $i, $outputlangs, $hidedetails = 0) global $hookmanager, $conf; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } $result = ''; $reshook = 0; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineupwithtax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if (empty($hidedetails) || $hidedetails > 1) $result .= price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice) * ($object->lines[$i]->tva_tx) / 100), 0, $outputlangs); + if (empty($reshook)) { + if (empty($hidedetails) || $hidedetails > 1) { + $result .= price($sign * (($object->lines[$i]->subprice) + ($object->lines[$i]->subprice) * ($object->lines[$i]->tva_tx) / 100), 0, $outputlangs); + } } return $result; } @@ -1725,20 +1774,26 @@ function pdf_getlineqty($object, $i, $outputlangs, $hidedetails = 0) $result = ''; $reshook = 0; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineqty', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result = $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result = $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty; + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= $object->lines[$i]->qty; + } } return $result; } @@ -1759,20 +1814,26 @@ function pdf_getlineqty_asked($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineqty_asked', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_asked; + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= $object->lines[$i]->qty_asked; + } } return $result; } @@ -1793,20 +1854,26 @@ function pdf_getlineqty_shipped($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineqty_shipped', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= $object->lines[$i]->qty_shipped; + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= $object->lines[$i]->qty_shipped; + } } return $result; } @@ -1827,20 +1894,26 @@ function pdf_getlineqty_keeptoship($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineqty_keeptoship', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= ($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped); + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= ($object->lines[$i]->qty_asked - $object->lines[$i]->qty_shipped); + } } return $result; } @@ -1862,8 +1935,7 @@ function pdf_getlineunit($object, $i, $outputlangs, $hidedetails = 0, $hookmanag $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; if (!empty($object->lines[$i]->fk_parent_line)) { $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); @@ -1877,11 +1949,14 @@ function pdf_getlineunit($object, $i, $outputlangs, $hidedetails = 0, $hookmanag $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineunit', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if (empty($hidedetails) || $hidedetails > 1) $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short')); + if (empty($reshook)) { + if (empty($hidedetails) || $hidedetails > 1) { + $result .= $langs->transnoentitiesnoconv($object->lines[$i]->getLabelOfUnit('short')); + } } return $result; } @@ -1905,20 +1980,26 @@ function pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails = 0) $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineremisepercent', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) $result .= dol_print_reduction($object->lines[$i]->remise_percent, $outputlangs); + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + $result .= dol_print_reduction($object->lines[$i]->remise_percent, $outputlangs); + } } return $result; } @@ -1935,37 +2016,42 @@ function pdf_getlineremisepercent($object, $i, $outputlangs, $hidedetails = 0) */ function pdf_getlineprogress($object, $i, $outputlangs, $hidedetails = 0, $hookmanager = null) { - if (empty($hookmanager)) global $hookmanager; + if (empty($hookmanager)) { + global $hookmanager; + } global $conf; $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i' => $i, 'outputlangs' => $outputlangs, 'hidedetails' => $hidedetails, 'special_code' => $special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlineprogress', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) return $hookmanager->resPrint; + if (!empty($hookmanager->resPrint)) { + return $hookmanager->resPrint; + } } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) return ''; - if (empty($hidedetails) || $hidedetails > 1) - { - if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF) - { + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + return ''; + } + if (empty($hidedetails) || $hidedetails > 1) { + if ($conf->global->SITUATION_DISPLAY_DIFF_ON_PDF) { $prev_progress = 0; - if (method_exists($object, 'get_prev_progress')) - { - $prev_progress = $object->lines[$i]->get_prev_progress($object->id); + if (method_exists($object, 'get_prev_progress')) { + $prev_progress = $object->lines[$i]->get_prev_progress($object->id); } - $result = ($object->lines[$i]->situation_percent - $prev_progress).'%'; - } else $result = $object->lines[$i]->situation_percent.'%'; - } + $result = ($object->lines[$i]->situation_percent - $prev_progress).'%'; + } else { + $result = $object->lines[$i]->situation_percent.'%'; + } + } } return $result; } @@ -1984,37 +2070,36 @@ function pdf_getlinetotalexcltax($object, $i, $outputlangs, $hidedetails = 0) global $conf, $hookmanager; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code, 'sign'=>$sign); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlinetotalexcltax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; - } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) - { - $result .= $outputlangs->transnoentities("Option"); + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; } - elseif (empty($hidedetails) || $hidedetails > 1) - { + } + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + $result .= $outputlangs->transnoentities("Option"); + } elseif (empty($hidedetails) || $hidedetails > 1) { $total_ht = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ht : $object->lines[$i]->total_ht); - if (!empty($object->lines[$i]->situation_percent) && $object->lines[$i]->situation_percent > 0) - { + if (!empty($object->lines[$i]->situation_percent) && $object->lines[$i]->situation_percent > 0) { // TODO Remove this. The total should be saved correctly in database instead of being modified here. $prev_progress = 0; $progress = 1; - if (method_exists($object->lines[$i], 'get_prev_progress')) - { + if (method_exists($object->lines[$i], 'get_prev_progress')) { $prev_progress = $object->lines[$i]->get_prev_progress($object->id); $progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100; } @@ -2041,37 +2126,36 @@ function pdf_getlinetotalwithtax($object, $i, $outputlangs, $hidedetails = 0) global $hookmanager, $conf; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } $reshook = 0; $result = ''; //if (is_object($hookmanager) && ( (isset($object->lines[$i]->product_type) && $object->lines[$i]->product_type == 9 && ! empty($object->lines[$i]->special_code)) || ! empty($object->lines[$i]->fk_parent_line) ) ) - if (is_object($hookmanager)) // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run - { + if (is_object($hookmanager)) { // Old code is commented on preceding line. Reproduct this test in the pdf_xxx function if you don't want your hook to run $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getlinetotalwithtax', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resPrint)) $result .= $hookmanager->resPrint; - } - if (empty($reshook)) - { - if ($object->lines[$i]->special_code == 3) - { - $result .= $outputlangs->transnoentities("Option"); + if (!empty($hookmanager->resPrint)) { + $result .= $hookmanager->resPrint; } - elseif (empty($hidedetails) || $hidedetails > 1) - { + } + if (empty($reshook)) { + if ($object->lines[$i]->special_code == 3) { + $result .= $outputlangs->transnoentities("Option"); + } elseif (empty($hidedetails) || $hidedetails > 1) { $total_ttc = (!empty($conf->multicurrency->enabled) && $object->multicurrency_tx != 1 ? $object->lines[$i]->multicurrency_total_ttc : $object->lines[$i]->total_ttc); - if ($object->lines[$i]->situation_percent > 0) - { + if ($object->lines[$i]->situation_percent > 0) { // TODO Remove this. The total should be saved correctly in database instead of being modified here. $prev_progress = 0; $progress = 1; - if (method_exists($object->lines[$i], 'get_prev_progress')) - { + if (method_exists($object->lines[$i], 'get_prev_progress')) { $prev_progress = $object->lines[$i]->get_prev_progress($object->id); $progress = ($object->lines[$i]->situation_percent - $prev_progress) / 100; } @@ -2101,26 +2185,22 @@ function pdf_getTotalQty($object, $type, $outputlangs) $nblines = count($object->lines); // Loop on each lines - for ($i = 0; $i < $nblines; $i++) - { - if ($object->lines[$i]->special_code != 3) - { - if ($type == 'all') - { + for ($i = 0; $i < $nblines; $i++) { + if ($object->lines[$i]->special_code != 3) { + if ($type == 'all') { $total += $object->lines[$i]->qty; - } elseif ($type == 9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && !empty($object->lines[$i]->special_code)) || !empty($object->lines[$i]->fk_parent_line))) - { + } elseif ($type == 9 && is_object($hookmanager) && (($object->lines[$i]->product_type == 9 && !empty($object->lines[$i]->special_code)) || !empty($object->lines[$i]->fk_parent_line))) { $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array('i'=>$i, 'outputlangs'=>$outputlangs, 'hidedetails'=>$hidedetails, 'special_code'=>$special_code); $action = ''; $reshook = $hookmanager->executeHooks('pdf_getTotalQty', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks return $hookmanager->resPrint; - } elseif ($type == 0 && $object->lines[$i]->product_type == 0) - { + } elseif ($type == 0 && $object->lines[$i]->product_type == 0) { $total += $object->lines[$i]->qty; - } elseif ($type == 1 && $object->lines[$i]->product_type == 1) - { + } elseif ($type == 1 && $object->lines[$i]->product_type == 1) { $total += $object->lines[$i]->qty; } } @@ -2145,81 +2225,73 @@ function pdf_getLinkedObjects($object, $outputlangs) $object->fetchObjectLinked(); - foreach ($object->linkedObjects as $objecttype => $objects) - { - if ($objecttype == 'facture') - { + foreach ($object->linkedObjects as $objecttype => $objects) { + if ($objecttype == 'facture') { // For invoice, we don't want to have a reference line on document. Image we are using recuring invoice, we will have a line longer than document width. - } elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal') - { + } elseif ($objecttype == 'propal' || $objecttype == 'supplier_proposal') { $outputlangs->load('propal'); - foreach ($objects as $elementobject) - { + foreach ($objects as $elementobject) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefProposal"); $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref); $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DatePropal"); $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date, 'day', '', $outputlangs); } - } elseif ($objecttype == 'commande' || $objecttype == 'supplier_order') - { + } elseif ($objecttype == 'commande' || $objecttype == 'supplier_order') { $outputlangs->load('orders'); - foreach ($objects as $elementobject) - { + foreach ($objects as $elementobject) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder"); $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref).($elementobject->ref_client ? ' ('.$elementobject->ref_client.')' : '').($elementobject->ref_supplier ? ' ('.$elementobject->ref_supplier.')' : ''); $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate"); $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date, 'day', '', $outputlangs); } - } elseif ($objecttype == 'contrat') - { + } elseif ($objecttype == 'contrat') { $outputlangs->load('contracts'); - foreach ($objects as $elementobject) - { + foreach ($objects as $elementobject) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefContract"); $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref); $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateContract"); $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->date_contrat, 'day', '', $outputlangs); } - } elseif ($objecttype == 'fichinter') - { + } elseif ($objecttype == 'fichinter') { $outputlangs->load('interventions'); - foreach ($objects as $elementobject) - { + foreach ($objects as $elementobject) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("InterRef"); $linkedobjects[$objecttype]['ref_value'] = $outputlangs->transnoentities($elementobject->ref); $linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("InterDate"); $linkedobjects[$objecttype]['date_value'] = dol_print_date($elementobject->datec, 'day', '', $outputlangs); } - } elseif ($objecttype == 'shipping') - { + } elseif ($objecttype == 'shipping') { $outputlangs->loadLangs(array("orders", "sendings")); - foreach ($objects as $x => $elementobject) - { + foreach ($objects as $x => $elementobject) { $order = null; // We concat this record info into fields xxx_value. title is overwrote. - 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 - { + 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'])) { 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)) - { + if (!is_object($order)) { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefSending"); - if (!empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] .= ' / '; + if (!empty($linkedobjects[$objecttype]['ref_value'])) { + $linkedobjects[$objecttype]['ref_value'] .= ' / '; + } $linkedobjects[$objecttype]['ref_value'] .= $outputlangs->transnoentities($elementobject->ref); //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("DateShipment"); //if (! empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'].=' / '; //$linkedobjects[$objecttype]['date_value'].= dol_print_date($elementobject->date_delivery,'day','',$outputlangs); } else { $linkedobjects[$objecttype]['ref_title'] = $outputlangs->transnoentities("RefOrder").' / '.$outputlangs->transnoentities("RefSending"); - if (empty($linkedobjects[$objecttype]['ref_value'])) $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref).($order->ref_client ? ' ('.$order->ref_client.')' : ''); + if (empty($linkedobjects[$objecttype]['ref_value'])) { + $linkedobjects[$objecttype]['ref_value'] = $outputlangs->convToOutputCharset($order->ref).($order->ref_client ? ' ('.$order->ref_client.')' : ''); + } $linkedobjects[$objecttype]['ref_value'] .= ' / '.$outputlangs->transnoentities($elementobject->ref); //$linkedobjects[$objecttype]['date_title'] = $outputlangs->transnoentities("OrderDate") . ($elementobject->date_delivery ? ' / ' . $outputlangs->transnoentities("DateShipment") : ''); //if (empty($linkedobjects[$objecttype]['date_value'])) $linkedobjects[$objecttype]['date_value'] = dol_print_date($order->date,'day','',$outputlangs); @@ -2230,12 +2302,13 @@ function pdf_getLinkedObjects($object, $outputlangs) } // For add external linked objects - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('linkedobjects' => $linkedobjects, 'outputlangs'=>$outputlangs); $action = ''; $hookmanager->executeHooks('pdf_getLinkedObjects', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks - if (!empty($hookmanager->resArray)) $linkedobjects = $hookmanager->resArray; + if (!empty($hookmanager->resArray)) { + $linkedobjects = $hookmanager->resArray; + } } return $linkedobjects; @@ -2256,11 +2329,9 @@ function pdf_getSizeForImage($realpath) $maxheight = (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT) ? 32 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_HEIGHT); include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; $tmp = dol_getImageSize($realpath); - if ($tmp['height']) - { + if ($tmp['height']) { $width = (int) round($maxheight * $tmp['width'] / $tmp['height']); // I try to use maxheight - if ($width > $maxwidth) // Pb with maxheight, so i use maxwidth - { + if ($width > $maxwidth) { // Pb with maxheight, so i use maxwidth $width = $maxwidth; $height = (int) round($maxwidth * $tmp['height'] / $tmp['width']); } else // No pb with maxheight @@ -2284,15 +2355,17 @@ function pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, $hidedetails = { global $conf, $hookmanager; $sign = 1; - if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) $sign = -1; - if ($object->lines[$i]->special_code == 3) - { + if (isset($object->type) && $object->type == 2 && !empty($conf->global->INVOICE_POSITIVE_CREDIT_NOTE)) { + $sign = -1; + } + if ($object->lines[$i]->special_code == 3) { return $outputlangs->transnoentities("Option"); } else { - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $special_code = $object->lines[$i]->special_code; - if (!empty($object->lines[$i]->fk_parent_line)) $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + if (!empty($object->lines[$i]->fk_parent_line)) { + $special_code = $object->getSpecialCode($object->lines[$i]->fk_parent_line); + } $parameters = array( 'i'=>$i, @@ -2303,13 +2376,14 @@ function pdfGetLineTotalDiscountAmount($object, $i, $outputlangs, $hidedetails = $action = ''; - if ($hookmanager->executeHooks('getlinetotalremise', $parameters, $object, $action) > 0) - { + if ($hookmanager->executeHooks('getlinetotalremise', $parameters, $object, $action) > 0) { return $hookmanager->resPrint; // Note that $action and $object may have been modified by some hooks } } - if (empty($hidedetails) || $hidedetails > 1) return $sign * (($object->lines[$i]->subprice * $object->lines[$i]->qty) - $object->lines[$i]->total_ht); + if (empty($hidedetails) || $hidedetails > 1) { + return $sign * (($object->lines[$i]->subprice * $object->lines[$i]->qty) - $object->lines[$i]->total_ht); + } } return ''; } diff --git a/htdocs/core/lib/prelevement.lib.php b/htdocs/core/lib/prelevement.lib.php index 75bf914b964..bc81ee2bfbd 100644 --- a/htdocs/core/lib/prelevement.lib.php +++ b/htdocs/core/lib/prelevement.lib.php @@ -85,14 +85,22 @@ function prelevement_prepare_head(BonPrelevement $object) function prelevement_check_config($type = 'direct-debit') { global $conf, $db; - if ($type == 'bank-transfer'){ - if (empty($conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT)) return -1; + if ($type == 'bank-transfer') { + if (empty($conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT)) { + return -1; + } //if (empty($conf->global->PRELEVEMENT_ICS)) return -1; - if (empty($conf->global->PAYMENTBYBANKTRANSFER_USER)) return -1; - }else { - if (empty($conf->global->PRELEVEMENT_ID_BANKACCOUNT)) return -1; + if (empty($conf->global->PAYMENTBYBANKTRANSFER_USER)) { + return -1; + } + } else { + if (empty($conf->global->PRELEVEMENT_ID_BANKACCOUNT)) { + return -1; + } //if (empty($conf->global->PRELEVEMENT_ICS)) return -1; - if (empty($conf->global->PRELEVEMENT_USER)) return -1; + if (empty($conf->global->PRELEVEMENT_USER)) { + return -1; + } } return 0; } diff --git a/htdocs/core/lib/price.lib.php b/htdocs/core/lib/price.lib.php index 98311d093cd..3a73f47a6a0 100644 --- a/htdocs/core/lib/price.lib.php +++ b/htdocs/core/lib/price.lib.php @@ -90,13 +90,15 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $result = array(); // Clean parameters - if (empty($info_bits)) $info_bits = 0; - if (empty($txtva)) $txtva = 0; - if (empty($seller) || !is_object($seller)) - { + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($seller) || !is_object($seller)) { dol_syslog("Price.lib::calcul_price_total Warning: function is called with parameter seller that is missing", LOG_WARNING); - if (!is_object($mysoc)) // mysoc may be not defined (during migration process) - { + if (!is_object($mysoc)) { // mysoc may be not defined (during migration process) $mysoc = new Societe($db); $mysoc->setMysoc($conf); } @@ -116,11 +118,19 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $countryid = $seller->country_id; - if (is_numeric($uselocaltax1_rate)) $uselocaltax1_rate = (float) $uselocaltax1_rate; - if (is_numeric($uselocaltax2_rate)) $uselocaltax2_rate = (float) $uselocaltax2_rate; + if (is_numeric($uselocaltax1_rate)) { + $uselocaltax1_rate = (float) $uselocaltax1_rate; + } + if (is_numeric($uselocaltax2_rate)) { + $uselocaltax2_rate = (float) $uselocaltax2_rate; + } - if ($uselocaltax1_rate < 0) $uselocaltax1_rate = $seller->localtax1_assuj; - if ($uselocaltax2_rate < 0) $uselocaltax2_rate = $seller->localtax2_assuj; + if ($uselocaltax1_rate < 0) { + $uselocaltax1_rate = $seller->localtax1_assuj; + } + if ($uselocaltax2_rate < 0) { + $uselocaltax2_rate = $seller->localtax2_assuj; + } //var_dump($uselocaltax1_rate.' - '.$uselocaltax2_rate); dol_syslog('Price.lib::calcul_price_total qty='.$qty.' pu='.$pu.' remise_percent_ligne='.$remise_percent_ligne.' txtva='.$txtva.' uselocaltax1_rate='.$uselocaltax1_rate.' uselocaltax2_rate='.$uselocaltax2_rate.' remise_percent_global='.$remise_percent_global.' price_base_type='.$price_base_type.' type='.$type.' progress='.$progress); @@ -144,33 +154,37 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $sql .= " WHERE cv.taux = ".$txtva; $sql .= " AND cv.fk_pays = ".$countryid; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $localtax1_rate = (float) $obj->localtax1; // Use float to force to get first numeric value when value is x:y:z $localtax2_rate = (float) $obj->localtax2; // Use float to force to get first numeric value when value is -19:-15:-9 $localtax1_type = $obj->localtax1_type; $localtax2_type = $obj->localtax2_type; //var_dump($localtax1_rate.' '.$localtax2_rate.' '.$localtax1_type.' '.$localtax2_type); } - } else dol_print_error($db); + } else { + dol_print_error($db); + } } // pu calculation from pu_devise if pu empty if (empty($pu) && !empty($pu_devise)) { - if (!empty($multicurrency_tx)) $pu = $pu_devise / $multicurrency_tx; - else { + if (!empty($multicurrency_tx)) { + $pu = $pu_devise / $multicurrency_tx; + } else { dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (multicurrency_tx empty when pu_devise not) ', LOG_ERR); return array(); } } - if ($pu === '') $pu = 0; + if ($pu === '') { + $pu = 0; + } // pu_devise calculation from pu if (empty($pu_devise) && !empty($multicurrency_tx)) { - if (is_numeric($pu) && is_numeric($multicurrency_tx)) $pu_devise = $pu * $multicurrency_tx; - else { + if (is_numeric($pu) && is_numeric($multicurrency_tx)) { + $pu_devise = $pu * $multicurrency_tx; + } else { dol_syslog('Price.lib::calcul_price_total function called with bad parameters combination (pu or multicurrency_tx are not numeric)', LOG_ERR); return array(); } @@ -182,13 +196,14 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $tot_avec_remise = $tot_avec_remise_ligne * (1 - ($remise_percent_global / 100)); // initialize result array - for ($i = 0; $i <= 15; $i++) $result[$i] = 0; + for ($i = 0; $i <= 15; $i++) { + $result[$i] = 0; + } // if there's some localtax including vat, we calculate localtaxes (we will add later) // if input unit price is 'HT', we need to have the totals with main VAT for a correct calculation - if ($price_base_type != 'TTC') - { + if ($price_base_type != 'TTC') { $tot_sans_remise_wt = price2num($tot_sans_remise * (1 + ($txtva / 100)), 'MU'); $tot_avec_remise_wt = price2num($tot_avec_remise * (1 + ($txtva / 100)), 'MU'); $pu_wt = price2num($pu * (1 + ($txtva / 100)), 'MU'); @@ -207,22 +222,26 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $apply_tax = true; break; case '4': // localtax on product - if ($type == 0) $apply_tax = true; + if ($type == 0) { + $apply_tax = true; + } break; case '6': // localtax on service - if ($type == 1) $apply_tax = true; + if ($type == 1) { + $apply_tax = true; + } break; } if ($uselocaltax1_rate && $apply_tax) { - $result[14] = price2num(($tot_sans_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT'); - $localtaxes[0] += $result[14]; + $result[14] = price2num(($tot_sans_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_sans_remise_wt, 'MT'); + $localtaxes[0] += $result[14]; - $result[9] = price2num(($tot_avec_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT'); - $localtaxes[1] += $result[9]; + $result[9] = price2num(($tot_avec_remise_wt * (1 + ($localtax1_rate / 100))) - $tot_avec_remise_wt, 'MT'); + $localtaxes[1] += $result[9]; - $result[11] = price2num(($pu_wt * (1 + ($localtax1_rate / 100))) - $pu_wt, 'MU'); - $localtaxes[2] += $result[11]; + $result[11] = price2num(($pu_wt * (1 + ($localtax1_rate / 100))) - $pu_wt, 'MU'); + $localtaxes[2] += $result[11]; } $apply_tax = false; @@ -231,26 +250,29 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $apply_tax = true; break; case '4': // localtax on product - if ($type == 0) $apply_tax = true; + if ($type == 0) { + $apply_tax = true; + } break; case '6': // localtax on service - if ($type == 1) $apply_tax = true; + if ($type == 1) { + $apply_tax = true; + } break; } if ($uselocaltax2_rate && $apply_tax) { - $result[15] = price2num(($tot_sans_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT'); - $localtaxes[0] += $result[15]; + $result[15] = price2num(($tot_sans_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_sans_remise_wt, 'MT'); + $localtaxes[0] += $result[15]; - $result[10] = price2num(($tot_avec_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT'); - $localtaxes[1] += $result[10]; + $result[10] = price2num(($tot_avec_remise_wt * (1 + ($localtax2_rate / 100))) - $tot_avec_remise_wt, 'MT'); + $localtaxes[1] += $result[10]; - $result[12] = price2num(($pu_wt * (1 + ($localtax2_rate / 100))) - $pu_wt, 'MU'); - $localtaxes[2] += $result[12]; + $result[12] = price2num(($pu_wt * (1 + ($localtax2_rate / 100))) - $pu_wt, 'MU'); + $localtaxes[2] += $result[12]; } //dol_syslog("price.lib::calcul_price_total $qty, $pu, $remise_percent_ligne, $txtva, $price_base_type $info_bits"); - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { // We work to define prices using the price without tax $result[6] = price2num($tot_sans_remise, 'MT'); $result[8] = price2num($tot_sans_remise * (1 + ((($info_bits & 1) ? 0 : $txtva) / 100)) + $localtaxes[0], 'MT'); // Selon TVA NPR ou non @@ -287,8 +309,7 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt // if there's some localtax without vat, we calculate localtaxes (we will add them at end) //If input unit price is 'TTC', we need to have the totals without main VAT for a correct calculation - if ($price_base_type == 'TTC') - { + if ($price_base_type == 'TTC') { $tot_sans_remise = price2num($tot_sans_remise / (1 + ($txtva / 100)), 'MU'); $tot_avec_remise = price2num($tot_avec_remise / (1 + ($txtva / 100)), 'MU'); $pu = price2num($pu / (1 + ($txtva / 100)), 'MU'); @@ -300,21 +321,25 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $apply_tax = true; break; case '3': // localtax on product - if ($type == 0) $apply_tax = true; + if ($type == 0) { + $apply_tax = true; + } break; case '5': // localtax on service - if ($type == 1) $apply_tax = true; + if ($type == 1) { + $apply_tax = true; + } break; } if ($uselocaltax1_rate && $apply_tax) { - $result[14] = price2num(($tot_sans_remise * (1 + ($localtax1_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax1 for total_ht_without_discount - $result[8] += $result[14]; // total_ttc_without_discount + tax1 + $result[14] = price2num(($tot_sans_remise * (1 + ($localtax1_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax1 for total_ht_without_discount + $result[8] += $result[14]; // total_ttc_without_discount + tax1 - $result[9] = price2num(($tot_avec_remise * (1 + ($localtax1_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax1 for total_ht - $result[2] += $result[9]; // total_ttc + tax1 + $result[9] = price2num(($tot_avec_remise * (1 + ($localtax1_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax1 for total_ht + $result[2] += $result[9]; // total_ttc + tax1 - $result[11] = price2num(($pu * (1 + ($localtax1_rate / 100))) - $pu, 'MU'); // amount tax1 for pu_ht - $result[5] += $result[11]; // pu_ht + tax1 + $result[11] = price2num(($pu * (1 + ($localtax1_rate / 100))) - $pu, 'MU'); // amount tax1 for pu_ht + $result[5] += $result[11]; // pu_ht + tax1 } $apply_tax = false; @@ -323,28 +348,30 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt $apply_tax = true; break; case '3': // localtax on product - if ($type == 0) $apply_tax = true; + if ($type == 0) { + $apply_tax = true; + } break; case '5': // localtax on service - if ($type == 1) $apply_tax = true; + if ($type == 1) { + $apply_tax = true; + } break; } if ($uselocaltax2_rate && $apply_tax) { - $result[15] = price2num(($tot_sans_remise * (1 + ($localtax2_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax2 for total_ht_without_discount - $result[8] += $result[15]; // total_ttc_without_discount + tax2 + $result[15] = price2num(($tot_sans_remise * (1 + ($localtax2_rate / 100))) - $tot_sans_remise, 'MT'); // amount tax2 for total_ht_without_discount + $result[8] += $result[15]; // total_ttc_without_discount + tax2 - $result[10] = price2num(($tot_avec_remise * (1 + ($localtax2_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax2 for total_ht - $result[2] += $result[10]; // total_ttc + tax2 + $result[10] = price2num(($tot_avec_remise * (1 + ($localtax2_rate / 100))) - $tot_avec_remise, 'MT'); // amount tax2 for total_ht + $result[2] += $result[10]; // total_ttc + tax2 - $result[12] = price2num(($pu * (1 + ($localtax2_rate / 100))) - $pu, 'MU'); // amount tax2 for pu_ht - $result[5] += $result[12]; // pu_ht + tax2 + $result[12] = price2num(($pu * (1 + ($localtax2_rate / 100))) - $pu, 'MU'); // amount tax2 for pu_ht + $result[5] += $result[12]; // pu_ht + tax2 } // If rounding is not using base 10 (rare) - if (!empty($conf->global->MAIN_ROUNDING_RULE_TOT)) - { - if ($price_base_type == 'HT') - { + if (!empty($conf->global->MAIN_ROUNDING_RULE_TOT)) { + if ($price_base_type == 'HT') { $result[0] = round($result[0] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; $result[1] = round($result[1] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; $result[9] = round($result[9] / $conf->global->MAIN_ROUNDING_RULE_TOT, 0) * $conf->global->MAIN_ROUNDING_RULE_TOT; @@ -360,8 +387,7 @@ function calcul_price_total($qty, $pu, $remise_percent_ligne, $txtva, $uselocalt } // Multicurrency - if ($multicurrency_tx != 1) - { + if ($multicurrency_tx != 1) { if ($multicurrency_code) { $savMAIN_MAX_DECIMALS_UNIT = $conf->global->MAIN_MAX_DECIMALS_UNIT; $savMAIN_MAX_DECIMALS_TOT = $conf->global->MAIN_MAX_DECIMALS_TOT; diff --git a/htdocs/core/lib/product.lib.php b/htdocs/core/lib/product.lib.php index 9ce8d84d7e3..52db9f88e24 100644 --- a/htdocs/core/lib/product.lib.php +++ b/htdocs/core/lib/product.lib.php @@ -38,7 +38,9 @@ function product_prepare_head($object) $langs->load("products"); $label = $langs->trans('Product'); - if ($object->isService()) $label = $langs->trans('Service'); + if ($object->isService()) { + $label = $langs->trans('Service'); + } $h = 0; $head = array(); @@ -48,20 +50,17 @@ function product_prepare_head($object) $head[$h][2] = 'card'; $h++; - if (!empty($object->status)) - { + if (!empty($object->status)) { $head[$h][0] = DOL_URL_ROOT."/product/price.php?id=".$object->id; $head[$h][1] = $langs->trans("SellingPrices"); $head[$h][2] = 'price'; $h++; } - if (!empty($object->status_buy) || (!empty($conf->margin->enabled) && !empty($object->status))) // If margin is on and product on sell, we may need the cost price even if product os not on purchase - { + if (!empty($object->status_buy) || (!empty($conf->margin->enabled) && !empty($object->status))) { // If margin is on and product on sell, we may need the cost price even if product os not on purchase if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->lire) || (!empty($conf->margin->enabled) && $user->rights->margin->liretous) - ) - { + ) { $head[$h][0] = DOL_URL_ROOT."/product/fournisseurs.php?id=".$object->id; $head[$h][1] = $langs->trans("BuyingPrices"); $head[$h][2] = 'suppliers'; @@ -70,8 +69,7 @@ function product_prepare_head($object) } // Multilangs - if (!empty($conf->global->MAIN_MULTILANGS)) - { + if (!empty($conf->global->MAIN_MULTILANGS)) { $head[$h][0] = DOL_URL_ROOT."/product/traduction.php?id=".$object->id; $head[$h][1] = $langs->trans("Translation"); $head[$h][2] = 'translation'; @@ -79,13 +77,14 @@ function product_prepare_head($object) } // Sub products - if (!empty($conf->global->PRODUIT_SOUSPRODUITS)) - { + if (!empty($conf->global->PRODUIT_SOUSPRODUITS)) { $head[$h][0] = DOL_URL_ROOT."/product/composition/card.php?id=".$object->id; $head[$h][1] = $langs->trans('AssociatedProducts'); $nbFatherAndChild = $object->hasFatherOrChild(); - if ($nbFatherAndChild > 0) $head[$h][1] .= ''.$nbFatherAndChild.''; + if ($nbFatherAndChild > 0) { + $head[$h][1] .= ''.$nbFatherAndChild.''; + } $head[$h][2] = 'subproduct'; $h++; } @@ -97,22 +96,21 @@ function product_prepare_head($object) $prodcomb = new ProductCombination($db); - if ($prodcomb->fetchByFkProductChild($object->id) <= 0) - { + if ($prodcomb->fetchByFkProductChild($object->id) <= 0) { $head[$h][0] = DOL_URL_ROOT."/variants/combinations.php?id=".$object->id; $head[$h][1] = $langs->trans('ProductCombinations'); $head[$h][2] = 'combinations'; $nbVariant = $prodcomb->countNbOfCombinationForFkProductParent($object->id); - if ($nbVariant > 0) $head[$h][1] .= ''.$nbVariant.''; + if ($nbVariant > 0) { + $head[$h][1] .= ''.$nbVariant.''; + } } $h++; } - if ($object->isProduct() || ($object->isService() && !empty($conf->global->STOCK_SUPPORTS_SERVICES))) // If physical product we can stock (or service with option) - { - if (!empty($conf->stock->enabled) && $user->rights->stock->lire) - { + if ($object->isProduct() || ($object->isService() && !empty($conf->global->STOCK_SUPPORTS_SERVICES))) { // If physical product we can stock (or service with option) + if (!empty($conf->stock->enabled) && $user->rights->stock->lire) { $head[$h][0] = DOL_URL_ROOT."/product/stock/product.php?id=".$object->id; $head[$h][1] = $langs->trans("Stock"); $head[$h][2] = 'stock'; @@ -121,17 +119,14 @@ function product_prepare_head($object) } // Tab to link resources - if (!empty($conf->resource->enabled)) - { - if ($object->isProduct() && !empty($conf->global->RESOURCE_ON_PRODUCTS)) - { + if (!empty($conf->resource->enabled)) { + if ($object->isProduct() && !empty($conf->global->RESOURCE_ON_PRODUCTS)) { $head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=product&ref='.$object->ref; $head[$h][1] = $langs->trans("Resources"); $head[$h][2] = 'resources'; $h++; } - if ($object->isService() && !empty($conf->global->RESOURCE_ON_SERVICES)) - { + if ($object->isService() && !empty($conf->global->RESOURCE_ON_SERVICES)) { $head[$h][0] = DOL_URL_ROOT.'/resource/element_resource.php?element=service&ref='.$object->ref; $head[$h][1] = $langs->trans("Resources"); $head[$h][2] = 'resources'; @@ -156,14 +151,19 @@ function product_prepare_head($object) complete_head_from_modules($conf, $langs, $object, $head, $h, 'product'); // Notes - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/product/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -171,18 +171,28 @@ function product_prepare_head($object) // Attachments require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; - if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); - if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); + if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) { + $upload_dir = $conf->product->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); + } + if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) { + $upload_dir = $conf->service->multidir_output[$object->entity].'/'.dol_sanitizeFileName($object->ref); + } $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) { - if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos'; - if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos'; + if (!empty($conf->product->enabled) && ($object->type == Product::TYPE_PRODUCT)) { + $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos'; + } + if (!empty($conf->service->enabled) && ($object->type == Product::TYPE_SERVICE)) { + $upload_dir = $conf->service->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'product').$object->id.'/photos'; + } $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.'/product/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; @@ -191,8 +201,7 @@ function product_prepare_head($object) // Log $head[$h][0] = DOL_URL_ROOT.'/product/agenda.php?id='.$object->id; $head[$h][1] = $langs->trans("Events"); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } @@ -231,7 +240,9 @@ function productlot_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT."/product/stock/productlot_document.php?id=".$object->id; $head[$h][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; @@ -245,11 +256,11 @@ function productlot_prepare_head($object) // Log /* - $head[$h][0] = DOL_URL_ROOT.'/product/info.php?id='.$object->id; - $head[$h][1] = $langs->trans("Info"); - $head[$h][2] = 'info'; - $h++; - */ + $head[$h][0] = DOL_URL_ROOT.'/product/info.php?id='.$object->id; + $head[$h][1] = $langs->trans("Info"); + $head[$h][2] = 'info'; + $h++; + */ return $head; } @@ -273,8 +284,7 @@ function product_admin_prepare_head() $head[$h][2] = 'general'; $h++; - if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL)) - { + if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($conf->global->PRODUIT_MULTIPRICES_ALLOW_AUTOCALC_PRICELEVEL)) { $head[$h] = array( 0 => DOL_URL_ROOT."/product/admin/price_rules.php", 1 => $langs->trans('MultipriceRules'), @@ -358,11 +368,12 @@ function show_stats_for_company($product, $socid) print ''; // Customer proposals - if (!empty($conf->propal->enabled) && $user->rights->propale->lire) - { + if (!empty($conf->propal->enabled) && $user->rights->propale->lire) { $nblines++; $ret = $product->load_stats_propale($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("propal"); print ''; print ''.img_object('', 'propal').' '.$langs->trans("Proposals").''; @@ -376,11 +387,12 @@ function show_stats_for_company($product, $socid) print ''; } // Supplier proposals - if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) - { + if (!empty($conf->supplier_proposal->enabled) && $user->rights->supplier_proposal->lire) { $nblines++; $ret = $product->load_stats_proposal_supplier($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("propal"); print ''; print ''.img_object('', 'supplier_proposal').' '.$langs->trans("SupplierProposals").''; @@ -394,11 +406,12 @@ function show_stats_for_company($product, $socid) print ''; } // Customer orders - if (!empty($conf->commande->enabled) && $user->rights->commande->lire) - { + if (!empty($conf->commande->enabled) && $user->rights->commande->lire) { $nblines++; $ret = $product->load_stats_commande($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("orders"); print ''; print ''.img_object('', 'order').' '.$langs->trans("CustomersOrders").''; @@ -412,11 +425,12 @@ function show_stats_for_company($product, $socid) print ''; } // Supplier orders - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && $user->rights->fournisseur->commande->lire) { $nblines++; $ret = $product->load_stats_commande_fournisseur($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("orders"); print ''; print ''.img_object('', 'supplier_order').' '.$langs->trans("SuppliersOrders").''; @@ -430,11 +444,12 @@ function show_stats_for_company($product, $socid) print ''; } // Customer invoices - if (!empty($conf->facture->enabled) && $user->rights->facture->lire) - { + if (!empty($conf->facture->enabled) && $user->rights->facture->lire) { $nblines++; $ret = $product->load_stats_facture($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("bills"); print ''; print ''.img_object('', 'bill').' '.$langs->trans("CustomersInvoices").''; @@ -448,11 +463,12 @@ function show_stats_for_company($product, $socid) print ''; } // Supplier invoices - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { $nblines++; $ret = $product->load_stats_facture_fournisseur($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("bills"); print ''; print ''.img_object('', 'supplier_invoice').' '.$langs->trans("SuppliersInvoices").''; @@ -467,11 +483,12 @@ function show_stats_for_company($product, $socid) } // Contracts - if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) - { + if (!empty($conf->contrat->enabled) && $user->rights->contrat->lire) { $nblines++; $ret = $product->load_stats_contrat($socid); - if ($ret < 0) dol_print_error($db); + if ($ret < 0) { + dol_print_error($db); + } $langs->load("contracts"); print ''; print ''.img_object('', 'contract').' '.$langs->trans("Contracts").''; @@ -486,8 +503,7 @@ function show_stats_for_company($product, $socid) } // BOM - if (!empty($conf->bom->enabled) && $user->rights->bom->read) - { + if (!empty($conf->bom->enabled) && $user->rights->bom->read) { $nblines++; $ret = $product->load_stats_bom($socid); if ($ret < 0) { @@ -510,8 +526,7 @@ function show_stats_for_company($product, $socid) } // MO - if (!empty($conf->mrp->enabled) && $user->rights->mrp->read) - { + if (!empty($conf->mrp->enabled) && $user->rights->mrp->read) { $nblines++; $ret = $product->load_stats_mo($socid); if ($ret < 0) { @@ -579,19 +594,16 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho $outputlangs = $langs; } - if (empty($measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label])) - { + if (empty($measuring_unit_cache[$unit.'_'.$measuring_style.'_'.$scale.'_'.$use_short_label])) { require_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php'; $measuringUnits = new CUnits($db); - if ($measuring_style == '' && $scale == '') - { + if ($measuring_style == '' && $scale == '') { $arrayforfilter = array( 't.rowid' => $unit, 't.active' => 1 ); - } elseif ($scale !== '') - { + } elseif ($scale !== '') { $arrayforfilter = array( 't.scale' => $scale, 't.unit_type' => $measuring_style, @@ -610,8 +622,11 @@ function measuringUnitString($unit, $measuring_style = '', $scale = '', $use_sho return -1; } else { if (is_array($measuringUnits->records) && count($measuringUnits->records) > 0) { - if ($use_short_label) $labeltoreturn = $measuringUnits->records[key($measuringUnits->records)]->short_label; - else $labeltoreturn = $outputlangs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label); + if ($use_short_label) { + $labeltoreturn = $measuringUnits->records[key($measuringUnits->records)]->short_label; + } else { + $labeltoreturn = $outputlangs->transnoentitiesnoconv($measuringUnits->records[key($measuringUnits->records)]->label); + } } else { $labeltoreturn = ''; } diff --git a/htdocs/core/lib/project.lib.php b/htdocs/core/lib/project.lib.php index c11cc4a74d6..8f1c457cd15 100644 --- a/htdocs/core/lib/project.lib.php +++ b/htdocs/core/lib/project.lib.php @@ -48,12 +48,13 @@ function project_prepare_head(Project $project) $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.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + 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='.$project->id; $head[$h][1] = $langs->trans("Tasks"); @@ -61,7 +62,9 @@ function project_prepare_head(Project $project) require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php'; $taskstatic = new Task($db); $nbTasks = count($taskstatic->getTasksArray(0, 0, $project->id, 0, 0)); - if ($nbTasks > 0) $head[$h][1] .= ''.($nbTasks).''; + if ($nbTasks > 0) { + $head[$h][1] .= ''.($nbTasks).''; + } $head[$h][2] = 'tasks'; $h++; @@ -73,15 +76,20 @@ function project_prepare_head(Project $project) $sql .= " WHERE t.fk_task = pt.rowid"; $sql .= " AND pt.fk_projet =".$project->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $nbTimeSpent = 1; - } else dol_print_error($db); + if ($obj) { + $nbTimeSpent = 1; + } + } else { + dol_print_error($db); + } $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] .= '...'; + if ($nbTimeSpent > 0) { + $head[$h][1] .= '...'; + } $head[$h][2] = 'timespent'; $h++; } @@ -89,34 +97,75 @@ function project_prepare_head(Project $project) if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) || !empty($conf->propal->enabled) || !empty($conf->commande->enabled) || !empty($conf->facture->enabled) || !empty($conf->contrat->enabled) - || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) - { + || !empty($conf->ficheinter->enabled) || !empty($conf->agenda->enabled) || !empty($conf->deplacement->enabled)) { $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'); + 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.''; + if ($count > 0) { + $head[$h][1] .= ''.$count.''; + } $head[$h][2] = 'element'; $h++; } @@ -127,7 +176,9 @@ function project_prepare_head(Project $project) $nbConfOrBooth = 1; $head[$h][0] = DOL_URL_ROOT . '/projet/event.php?id=' . $project->id; $head[$h][1] = $langs->trans("ConferenceOrBoothTab"); - if ($nbContact > 0) $head[$h][1] .= '' . $nbConfOrBooth . ''; + if ($nbContact > 0) { + $head[$h][1] .= '' . $nbConfOrBooth . ''; + } $head[$h][2] = 'eventorganisation'; $h++; } @@ -139,14 +190,19 @@ function project_prepare_head(Project $project) complete_head_from_modules($conf, $langs, $project, $head, $h, 'project'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($project->note_private)) $nbNote++; - if (!empty($project->note_public)) $nbNote++; + 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.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'notes'; $h++; } @@ -158,25 +214,27 @@ function project_prepare_head(Project $project) $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).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'document'; $h++; // Manage discussion - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) - { + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_PROJECT)) { $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.''; + if ($nbComments > 0) { + $head[$h][1] .= ''.$nbComments.''; + } $head[$h][2] = 'project_comment'; $h++; } $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))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } @@ -209,7 +267,9 @@ function task_prepare_head($object) $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/contact.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); $head[$h][1] = $langs->trans("TaskRessourceLinks"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'task_contact'; $h++; @@ -221,15 +281,20 @@ function task_prepare_head($object) $sql .= " FROM ".MAIN_DB_PREFIX."projet_task_time as t"; $sql .= " WHERE t.fk_task =".$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) $nbTimeSpent = 1; - } else dol_print_error($db); + if ($obj) { + $nbTimeSpent = 1; + } + } else { + dol_print_error($db); + } $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/time.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); $head[$h][1] = $langs->trans("TimeSpent"); - if ($nbTimeSpent > 0) $head[$h][1] .= '...'; + if ($nbTimeSpent > 0) { + $head[$h][1] .= '...'; + } $head[$h][2] = 'task_time'; $h++; @@ -239,14 +304,19 @@ function task_prepare_head($object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'task'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/note.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'task_notes'; $h++; } @@ -258,17 +328,20 @@ function task_prepare_head($object) $nbFiles = count(dol_dir_list($filesdir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'task_document'; $h++; // Manage discussion - if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK)) - { + if (!empty($conf->global->PROJECT_ALLOW_COMMENT_ON_TASK)) { $nbComments = $object->getNbComments(); $head[$h][0] = DOL_URL_ROOT.'/projet/tasks/comment.php?id='.$object->id.(GETPOST('withproject') ? '&withproject=1' : ''); $head[$h][1] = $langs->trans("CommentLink"); - if ($nbComments > 0) $head[$h][1] .= ''.$nbComments.''; + if ($nbComments > 0) { + $head[$h][1] .= ''.$nbComments.''; + } $head[$h][2] = 'task_comment'; $h++; } @@ -295,26 +368,25 @@ function project_timesheet_prepare_head($mode, $fuser = null) $param = ''; $param .= ($mode ? '&mode='.$mode : ''); - if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) $param .= '&search_usertoprocessid='.$fuser->id; + if (is_object($fuser) && $fuser->id > 0 && $fuser->id != $user->id) { + $param .= '&search_usertoprocessid='.$fuser->id; + } - if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERMONTH)) - { + if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERMONTH)) { $head[$h][0] = DOL_URL_ROOT."/projet/activity/permonth.php".($param ? '?'.$param : ''); $head[$h][1] = $langs->trans("InputPerMonth"); $head[$h][2] = 'inputpermonth'; $h++; } - if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK)) - { + if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERWEEK)) { $head[$h][0] = DOL_URL_ROOT."/projet/activity/perweek.php".($param ? '?'.$param : ''); $head[$h][1] = $langs->trans("InputPerWeek"); $head[$h][2] = 'inputperweek'; $h++; } - if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME)) - { + if (empty($conf->global->PROJECT_DISABLE_TIMESHEET_PERTIME)) { $head[$h][0] = DOL_URL_ROOT."/projet/activity/perday.php".($param ? '?'.$param : ''); $head[$h][1] = $langs->trans("InputPerDay"); $head[$h][2] = 'inputperday'; @@ -400,7 +472,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t $projectsArrayId = explode(',', $projectsListId); if ($filterprogresscalc !== '') { - foreach ($lines as $key=>$line) { + foreach ($lines as $key => $line) { if (!empty($line->planned_workload) && !empty($line->duration)) { $filterprogresscalc = str_replace(' = ', ' == ', $filterprogresscalc); if (!eval($filterprogresscalc)) { @@ -415,8 +487,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t // We declare counter as global because we want to edit them into recursive call global $total_projectlinesa_spent, $total_projectlinesa_planned, $total_projectlinesa_spent_if_planned, $total_projectlinesa_declared_if_planned, $total_projectlinesa_tobill, $total_projectlinesa_billed; - if ($level == 0) - { + if ($level == 0) { $total_projectlinesa_spent = 0; $total_projectlinesa_planned = 0; $total_projectlinesa_spent_if_planned = 0; @@ -425,31 +496,28 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t $total_projectlinesa_billed = 0; } - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0 && $level >= 0) $level = 0; // if $level = -1, we dont' use sublevel recursion, we show all lines + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0 && $level >= 0) { + $level = 0; // if $level = -1, we dont' use sublevel recursion, we show all lines + } // Process line // print "i:".$i."-".$lines[$i]->fk_project.'
    '; - if ($lines[$i]->fk_parent == $parent || $level < 0) // if $level = -1, we dont' use sublevel recursion, we show all lines - { + if ($lines[$i]->fk_parent == $parent || $level < 0) { // if $level = -1, we dont' use sublevel recursion, we show all lines // Show task line. $showline = 1; $showlineingray = 0; // If there is filters to use - if (is_array($taskrole)) - { + if (is_array($taskrole)) { // If task not legitimate to show, search if a legitimate task exists later in tree - if (!isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent) - { + if (!isset($taskrole[$lines[$i]->id]) && $lines[$i]->id != $lines[$i]->fk_parent) { // So search if task has a subtask legitimate to show $foundtaskforuserdeeper = 0; searchTaskInChild($foundtaskforuserdeeper, $lines[$i]->id, $lines, $taskrole); //print '$foundtaskforuserpeeper='.$foundtaskforuserdeeper.'
    '; - if ($foundtaskforuserdeeper > 0) - { + if ($foundtaskforuserdeeper > 0) { $showlineingray = 1; // We will show line but in gray } else { $showline = 0; // No reason to show line @@ -458,11 +526,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } else { // Caller did not ask to filter on tasks of a specific user (this probably means he want also tasks of all users, into public project // or into all other projects if user has permission to). - if (empty($user->rights->projet->all->lire)) - { + if (empty($user->rights->projet->all->lire)) { // User is not allowed on this project and project is not public, so we hide line - if (!in_array($lines[$i]->fk_project, $projectsArrayId)) - { + if (!in_array($lines[$i]->fk_project, $projectsArrayId)) { // Note that having a user assigned to a task into a project user has no permission on, should not be possible // because assignement on task can be done only on contact of project. // If assignement was done and after, was removed from contact of project, then we can hide the line. @@ -471,11 +537,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } } - if ($showline) - { + if ($showline) { // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $var = !$var; $lastprojectid = $lines[$i]->fk_project; } @@ -502,13 +566,15 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t $taskstatic->duration_effective = $lines[$i]->duration; - if ($showproject) - { + if ($showproject) { // Project ref print ""; //if ($showlineingray) print ''; - if ($lines[$i]->public || in_array($lines[$i]->fk_project, $projectsArrayId) || !empty($user->rights->projet->all->lire)) print $projectstatic->getNomUrl(1); - else print $projectstatic->getNomUrl(1, 'nolink'); + if ($lines[$i]->public || in_array($lines[$i]->fk_project, $projectsArrayId) || !empty($user->rights->projet->all->lire)) { + print $projectstatic->getNomUrl(1); + } else { + print $projectstatic->getNomUrl(1, 'nolink'); + } //if ($showlineingray) print ''; print ""; @@ -533,8 +599,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t // Title of task if (count($arrayfields) > 0 && !empty($arrayfields['t.label']['checked'])) { print ""; - if ($showlineingray) + if ($showlineingray) { print ''; + } //else print ''; for ($k = 0; $k < $level; $k++) { print '
    '; @@ -543,8 +610,9 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t for ($k = 0; $k < $level; $k++) { print '
    '; } - if ($showlineingray) + if ($showlineingray) { print '
    '; + } //else print ''; print "\n"; } @@ -566,15 +634,20 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) { print ''; print dol_print_date($lines[$i]->date_end, 'dayhour'); - if ($taskstatic->hasDelay()) + if ($taskstatic->hasDelay()) { print img_warning($langs->trans("Late")); + } print ''; } $plannedworkloadoutputformat = 'allhourmin'; $timespentoutputformat = 'allhourmin'; - if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; - if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; + if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) { + $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; + } + if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) { + $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; + } // Planned Workload (in working hours) if (count($arrayfields) > 0 && !empty($arrayfields['t.planned_workload']['checked'])) { @@ -593,15 +666,21 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t // Time spent if (count($arrayfields) > 0 && !empty($arrayfields['t.duration_effective']['checked'])) { print ''; - if ($showlineingray) + if ($showlineingray) { print ''; - else print ''; - if ($lines[$i]->duration) + } else { + print ''; + } + if ($lines[$i]->duration) { print convertSecondToTime($lines[$i]->duration, $timespentoutputformat); - else print '--:--'; - if ($showlineingray) + } else { + print '--:--'; + } + if ($showlineingray) { print ''; - else print ''; + } else { + print ''; + } print ''; } @@ -609,9 +688,11 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if (count($arrayfields) > 0 && !empty($arrayfields['t.progress_calculated']['checked'])) { print ''; if ($lines[$i]->planned_workload || $lines[$i]->duration) { - if ($lines[$i]->planned_workload) + if ($lines[$i]->planned_workload) { print round(100 * $lines[$i]->duration / $lines[$i]->planned_workload, 2).' %'; - else print ''.$langs->trans('WorkloadNotDefined').''; + } else { + print ''.$langs->trans('WorkloadNotDefined').''; + } } print ''; } @@ -634,8 +715,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print ''; } - if ($showbilltime) - { + if ($showbilltime) { // Time not billed if (count($arrayfields) > 0 && !empty($arrayfields['t.tobill']['checked'])) { print ''; @@ -662,18 +742,19 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } // Contacts of task - if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) - { + if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) { print ''; - foreach (array('internal', 'external') as $source) - { + foreach (array('internal', 'external') as $source) { $tab = $lines[$i]->liste_contact(-1, $source); $num = count($tab); if (!empty($num)) { foreach ($tab as $contacttask) { //var_dump($contacttask); - if ($source == 'internal') $c = new User($db); - else $c = new Contact($db); + if ($source == 'internal') { + $c = new User($db); + } else { + $c = new Contact($db); + } $c->fetch($contacttask['id']); print $c->getNomUrl(1).' ('.$contacttask['libelle'].')
    '; } @@ -696,19 +777,26 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print "\n"; - if (!$showlineingray) $inc++; + if (!$showlineingray) { + $inc++; + } - if ($level >= 0) // Call sublevels - { + if ($level >= 0) { // Call sublevels $level++; - if ($lines[$i]->id) projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick, $projectidfortotallink, $filterprogresscalc, $showbilltime, $arrayfields); + if ($lines[$i]->id) { + projectLinesa($inc, $lines[$i]->id, $lines, $level, $var, $showproject, $taskrole, $projectsListId, $addordertick, $projectidfortotallink, $filterprogresscalc, $showbilltime, $arrayfields); + } $level--; } $total_projectlinesa_spent += $lines[$i]->duration; $total_projectlinesa_planned += $lines[$i]->planned_workload; - if ($lines[$i]->planned_workload) $total_projectlinesa_spent_if_planned += $lines[$i]->duration; - if ($lines[$i]->planned_workload) $total_projectlinesa_declared_if_planned += $lines[$i]->planned_workload * $lines[$i]->progress / 100; + if ($lines[$i]->planned_workload) { + $total_projectlinesa_spent_if_planned += $lines[$i]->duration; + } + if ($lines[$i]->planned_workload) { + $total_projectlinesa_declared_if_planned += $lines[$i]->planned_workload * $lines[$i]->progress / 100; + } } } else { //$level--; @@ -716,14 +804,21 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } if (($total_projectlinesa_planned > 0 || $total_projectlinesa_spent > 0 || $total_projectlinesa_tobill > 0 || $total_projectlinesa_billed > 0) - && $level <= 0) - { + && $level <= 0) { print ''; print ''.$langs->trans("Total").''; - if ($showproject) print ''; - if (count($arrayfields) > 0 && !empty($arrayfields['t.label']['checked'])) print ''; - if (count($arrayfields) > 0 && !empty($arrayfields['t.dateo']['checked'])) print ''; - if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) print ''; + if ($showproject) { + print ''; + } + if (count($arrayfields) > 0 && !empty($arrayfields['t.label']['checked'])) { + print ''; + } + if (count($arrayfields) > 0 && !empty($arrayfields['t.dateo']['checked'])) { + print ''; + } + if (count($arrayfields) > 0 && !empty($arrayfields['t.datee']['checked'])) { + print ''; + } if (count($arrayfields) > 0 && !empty($arrayfields['t.planned_workload']['checked'])) { print ''; print convertSecondToTime($total_projectlinesa_planned, 'allhourmin'); @@ -731,11 +826,13 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } if (count($arrayfields) > 0 && !empty($arrayfields['t.duration_effective']['checked'])) { print ''; - if ($projectidfortotallink > 0) + if ($projectidfortotallink > 0) { print ''; + } print convertSecondToTime($total_projectlinesa_spent, 'allhourmin'); - if ($projectidfortotallink > 0) + if ($projectidfortotallink > 0) { print ''; + } print ''; } @@ -764,14 +861,16 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t if (count($arrayfields) > 0 && !empty($arrayfields['t.progress_calculated']['checked'])) { print ''; - if ($total_projectlinesa_planned) + if ($total_projectlinesa_planned) { print $totalCalculatedProgress.' %'; + } print ''; } if (count($arrayfields) > 0 && !empty($arrayfields['t.progress']['checked'])) { print ''; - if ($total_projectlinesa_planned) + if ($total_projectlinesa_planned) { print ''.$totalAverageDeclaredProgress.' %'; + } print ''; } @@ -789,8 +888,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t print ''; } - if ($showbilltime) - { + if ($showbilltime) { if (count($arrayfields) > 0 && !empty($arrayfields['t.tobill']['checked'])) { print ''; print convertSecondToTime($total_projectlinesa_tobill, 'allhourmin'); @@ -803,8 +901,7 @@ function projectLinesa(&$inc, $parent, &$lines, &$level, $var, $showproject, &$t } } // Contacts of task - if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) - { + if (!empty($conf->global->PROJECT_SHOW_CONTACTS_IN_LIST)) { print ''; } print ''; @@ -845,45 +942,40 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec $numlines = count($lines); // Create a smaller array with sublevels only to be used later. This increase dramatically performances. - if ($parent == 0) // Always and only if at first level - { - for ($i = 0; $i < $numlines; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; + if ($parent == 0) { // Always and only if at first level + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_task_parent) { + $lineswithoutlevel0[] = $lines[$i]; + } } } - if (empty($oldprojectforbreak)) - { + if (empty($oldprojectforbreak)) { $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 to start break , -1 no break } //dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0) $level = 0; + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0) { + $level = 0; + } //if ($lines[$i]->fk_task_parent == $parent) //{ // If we want all or we have a role on task, we show it - if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) - { + if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) { //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $lastprojectid = $lines[$i]->fk_project; - if ($preselectedday) - { + if ($preselectedday) { $projectstatic->id = $lines[$i]->fk_project; } } - if (empty($workloadforid[$projectstatic->id])) - { - if ($preselectedday) - { + if (empty($workloadforid[$projectstatic->id])) { + if ($preselectedday) { $projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week $workloadforid[$projectstatic->id] = 1; } @@ -905,13 +997,11 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec $thirdpartystatic->name = $lines[$i]->thirdparty_name; $thirdpartystatic->email = $lines[$i]->thirdparty_email; - if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) - { + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) { print ''."\n"; print ''; print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); - if ($projectstatic->title) - { + if ($projectstatic->title) { print ' - '; print $projectstatic->title; } @@ -919,7 +1009,9 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec print ''; } - if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + if ($oldprojectforbreak != -1) { + $oldprojectforbreak = $projectstatic->id; + } print ''."\n"; @@ -932,8 +1024,7 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec // Project print ""; - if ($oldprojectforbreak == -1) - { + if ($oldprojectforbreak == -1) { print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); print '
    '.$projectstatic->title; } @@ -941,17 +1032,23 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec // Thirdparty print ''; - if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10); + if ($thirdpartystatic->id > 0) { + print $thirdpartystatic->getNomUrl(1, 'project', 10); + } print ''; // Ref print ''; print ''; - for ($k = 0; $k < $level; $k++) print "   "; + for ($k = 0; $k < $level; $k++) { + print "   "; + } print $taskstatic->getNomUrl(1, 'withproject', 'time'); // Label task print '
    '; - for ($k = 0; $k < $level; $k++) print "   "; + for ($k = 0; $k < $level; $k++) { + print "   "; + } print $taskstatic->label; //print "
    "; //for ($k = 0 ; $k < $level ; $k++) print "   "; @@ -968,14 +1065,12 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec //var_dump($lines[$i]); //var_dump($projectsrole[$lines[$i]->fk_project]); // If at least one role for project - if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) - { + if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) { $disabledproject = 0; $disabledtask = 0; } // If $restricteditformytask is on and I have no role on task, i disable edit - if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) - { + if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) { $disabledtask = 1; } @@ -985,9 +1080,13 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec print ''; $cssonholiday = ''; - if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$preselectedday]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; + if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) { + $cssonholiday .= 'onholidayallday '; + } elseif (!$isavailable[$preselectedday]['morning']) { + $cssonholiday .= 'onholidaymorning '; + } elseif (!$isavailable[$preselectedday]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; + } // Duration print ''; @@ -996,7 +1095,9 @@ function projectLinesPerAction(&$inc, $parent, $fuser, $lines, &$level, &$projec $totalforeachline[$preselectedday] += $lines[$i]->timespent_duration; $alreadyspent = ''; - if ($dayWorkLoad > 0) $alreadyspent = convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin'); + if ($dayWorkLoad > 0) { + $alreadyspent = convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin'); + } print convertSecondToTime($lines[$i]->timespent_duration, 'allhourmin'); @@ -1074,54 +1175,47 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $numlines = count($lines); // Create a smaller array with sublevels only to be used later. This increase dramatically performances. - if ($parent == 0) // Always and only if at first level - { - for ($i = 0; $i < $numlines; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; + if ($parent == 0) { // Always and only if at first level + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_task_parent) { + $lineswithoutlevel0[] = $lines[$i]; + } } } - if (empty($oldprojectforbreak)) - { + if (empty($oldprojectforbreak)) { $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 to start break , -1 no break } //dol_syslog('projectLinesPerDay inc='.$inc.' preselectedday='.$preselectedday.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0) $level = 0; + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0) { + $level = 0; + } - if ($lines[$i]->fk_task_parent == $parent) - { + if ($lines[$i]->fk_task_parent == $parent) { $obj = &$lines[$i]; // To display extrafields // If we want all or we have a role on task, we show it - if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) - { + if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) { //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); - if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) // we have no role on task and we request to hide such cases - { + if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) { // we have no role on task and we request to hide such cases continue; } // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $lastprojectid = $lines[$i]->fk_project; - if ($preselectedday) - { + if ($preselectedday) { $projectstatic->id = $lines[$i]->fk_project; } } - if (empty($workloadforid[$projectstatic->id])) - { - if ($preselectedday) - { + if (empty($workloadforid[$projectstatic->id])) { + if ($preselectedday) { $projectstatic->loadTimeSpent($preselectedday, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week - $workloadforid[$projectstatic->id] = 1; + $workloadforid[$projectstatic->id] = 1; } } @@ -1141,91 +1235,98 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $thirdpartystatic->name = $lines[$i]->thirdparty_name; $thirdpartystatic->email = $lines[$i]->thirdparty_email; - if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) - { + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) { $addcolspan = 0; - if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++; - if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++; - foreach ($arrayfields as $key => $val) - { - if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++; + if (!empty($arrayfields['t.planned_workload']['checked'])) { + $addcolspan++; + } + if (!empty($arrayfields['t.progress']['checked'])) { + $addcolspan++; + } + foreach ($arrayfields as $key => $val) { + if ($val['checked'] && substr($key, 0, 5) == 'efpt.') { + $addcolspan++; + } } print ''."\n"; print ''; print $projectstatic->getNomUrl(1, '', 0, ''.$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); - if ($thirdpartystatic->id > 0) print ' - '.$thirdpartystatic->getNomUrl(1); - if ($projectstatic->title) - { + if ($thirdpartystatic->id > 0) { + print ' - '.$thirdpartystatic->getNomUrl(1); + } + if ($projectstatic->title) { print ' - '; print ''.$projectstatic->title.''; } /* - $colspan=5+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2); - print ''; + $colspan=5+(empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)?0:2); + print '
    '; - print ''; + print ''; - // PROJECT fields - if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); + // PROJECT fields + if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); + if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); - $extrafieldsobjectkey='projet'; - $extrafieldsobjectprefix='efp.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; + $extrafieldsobjectkey='projet'; + $extrafieldsobjectprefix='efp.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; - print ''; - print ''; + print ''; + print ''; - // PROJECT fields - if (! empty($arrayfields['p.fk_opp_status']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.opp_amount']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.opp_percent']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.budget_amount']['checked'])) - { - print '\n"; - } - if (! empty($arrayfields['p.usage_bill_time']['checked'])) - { - print '\n"; - } + // PROJECT fields + if (! empty($arrayfields['p.fk_opp_status']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.opp_amount']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.opp_percent']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.budget_amount']['checked'])) + { + print '\n"; + } + if (! empty($arrayfields['p.usage_bill_time']['checked'])) + { + print '\n"; + } - $extrafieldsobjectkey='projet'; - $extrafieldsobjectprefix='efp.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + $extrafieldsobjectkey='projet'; + $extrafieldsobjectprefix='efp.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - print ''; - print '
    '; - $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); - print "'; - print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); - print "'; - print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %'; - print "'; - print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); - print "'; - print yn($lines[$i]->usage_bill_time); - print "'; + $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code'); + if ($code) print $langs->trans("OppStatus".$code); + print "'; + print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); + print "'; + print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %'; + print "'; + print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); + print "'; + print yn($lines[$i]->usage_bill_time); + print "
    '; + print ''; + print ''; */ print ''; print ''; } - if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + if ($oldprojectforbreak != -1) { + $oldprojectforbreak = $projectstatic->id; + } print ''."\n"; @@ -1237,30 +1338,36 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr */ // Project - if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) - { + if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { print ""; - if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + if ($oldprojectforbreak == -1) { + print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + } print ""; } // Thirdparty - if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) - { + if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { print ''; - if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project', 10); + if ($thirdpartystatic->id > 0) { + print $thirdpartystatic->getNomUrl(1, 'project', 10); + } print ''; } // Ref print ''; print ''; - for ($k = 0; $k < $level; $k++) print '
    '; + for ($k = 0; $k < $level; $k++) { + print '
    '; + } print $taskstatic->getNomUrl(1, 'withproject', 'time'); // Label task print '
    '; print ''.$taskstatic->label.''; - for ($k = 0; $k < $level; $k++) print "
    "; + for ($k = 0; $k < $level; $k++) { + print "
    "; + } print "\n"; // TASK extrafields @@ -1269,17 +1376,18 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Planned Workload - if (!empty($arrayfields['t.planned_workload']['checked'])) - { + if (!empty($arrayfields['t.planned_workload']['checked'])) { print ''; - if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); - else print '--:--'; + if ($lines[$i]->planned_workload) { + print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); + } else { + print '--:--'; + } print ''; } // Progress declared % - if (!empty($arrayfields['t.progress']['checked'])) - { + if (!empty($arrayfields['t.progress']['checked'])) { print ''; print $formother->select_percent($lines[$i]->progress, $lines[$i]->id.'progress'); print ''; @@ -1288,19 +1396,23 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr // Time spent by everybody print ''; // $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user - if ($lines[$i]->duration) - { + if ($lines[$i]->duration) { print ''; print convertSecondToTime($lines[$i]->duration, 'allhourmin'); print ''; - } else print '--:--'; + } else { + print '--:--'; + } print "\n"; // Time spent by user print ''; $tmptimespent = $taskstatic->getSummaryOfTimeSpent($fuser->id); - if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); - else print '--:--'; + if ($tmptimespent['total_duration']) { + print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); + } else { + print '--:--'; + } print "\n"; $disabledproject = 1; $disabledtask = 1; @@ -1308,14 +1420,12 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr //var_dump($lines[$i]); //var_dump($projectsrole[$lines[$i]->fk_project]); // If at least one role for project - if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) - { + if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) { $disabledproject = 0; $disabledtask = 0; } // If $restricteditformytask is on and I have no role on task, i disable edit - if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) - { + if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) { $disabledtask = 1; } @@ -1326,9 +1436,13 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr print ''; $cssonholiday = ''; - if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$preselectedday]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$preselectedday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; + if (!$isavailable[$preselectedday]['morning'] && !$isavailable[$preselectedday]['afternoon']) { + $cssonholiday .= 'onholidayallday '; + } elseif (!$isavailable[$preselectedday]['morning']) { + $cssonholiday .= 'onholidaymorning '; + } elseif (!$isavailable[$preselectedday]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; + } global $daytoparse; $tmparray = dol_getdate($daytoparse, true); // detail of current day @@ -1336,8 +1450,7 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $idw = ($tmparray['wday'] - (empty($conf->global->MAIN_START_WEEK) ? 0 : 1)); global $numstartworkingday, $numendworkingday; $cssweekend = ''; - if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. - { + if ((($idw + 1) < $numstartworkingday) || (($idw + 1) > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css. $cssweekend = 'weekend'; } @@ -1347,7 +1460,9 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $totalforeachday[$preselectedday] += $dayWorkLoad; $alreadyspent = ''; - if ($dayWorkLoad > 0) $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin'); + if ($dayWorkLoad > 0) { + $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin'); + } $idw = 0; @@ -1377,14 +1492,16 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr // Warning print ''; - if ((!$lines[$i]->public) && $disabledproject) print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); - elseif ($disabledtask) - { - $titleassigntask = $langs->trans("AssignTaskToMe"); - if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + if ((!$lines[$i]->public) && $disabledproject) { + print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); + } elseif ($disabledtask) { + $titleassigntask = $langs->trans("AssignTaskToMe"); + if ($fuser->id != $user->id) { + $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + } - print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); - } + print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); + } print ''; print "\n"; @@ -1392,15 +1509,13 @@ function projectLinesPerDay(&$inc, $parent, $fuser, $lines, &$level, &$projectsr $inc++; $level++; - if ($lines[$i]->id > 0) - { + if ($lines[$i]->id > 0) { //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level); //var_dump($totalforeachday); $ret = projectLinesPerDay($inc, $lines[$i]->id, $fuser, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $preselectedday, $isavailable, $oldprojectforbreak, $arrayfields, $extrafields); //var_dump('ret with parent='.$lines[$i]->id.' level='.$level); //var_dump($ret); - foreach ($ret as $key => $val) - { + foreach ($ret as $key => $val) { $totalforeachday[$key] += $val; } //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks'); @@ -1448,50 +1563,45 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ $lineswithoutlevel0 = array(); // Create a smaller array with sublevels only to be used later. This increase dramatically performances. - if ($parent == 0) // Always and only if at first level - { - for ($i = 0; $i < $numlines; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; + if ($parent == 0) { // Always and only if at first level + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_task_parent) { + $lineswithoutlevel0[] = $lines[$i]; + } } } //dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); - if (empty($oldprojectforbreak)) - { + if (empty($oldprojectforbreak)) { $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 = start break, -1 = never break } - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0) $level = 0; + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0) { + $level = 0; + } - if ($lines[$i]->fk_task_parent == $parent) - { + if ($lines[$i]->fk_task_parent == $parent) { $obj = &$lines[$i]; // To display extrafields // If we want all or we have a role on task, we show it - if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) - { + if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) { //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); - if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) // we have no role on task and we request to hide such cases - { + if ($restricteditformytask == 2 && empty($tasksrole[$lines[$i]->id])) { // we have no role on task and we request to hide such cases continue; } // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $lastprojectid = $lines[$i]->fk_project; $projectstatic->id = $lines[$i]->fk_project; } //var_dump('--- '.$level.' '.$firstdaytoshow.' '.$fuser->id.' '.$projectstatic->id.' '.$workloadforid[$projectstatic->id]); //var_dump($projectstatic->weekWorkLoadPerTask); - if (empty($workloadforid[$projectstatic->id])) - { + if (empty($workloadforid[$projectstatic->id])) { $projectstatic->loadTimeSpent($firstdaytoshow, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week $workloadforid[$projectstatic->id] = 1; } @@ -1515,22 +1625,27 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ $thirdpartystatic->name = $lines[$i]->thirdparty_name; $thirdpartystatic->email = $lines[$i]->thirdparty_email; - if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) - { + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) { $addcolspan = 0; - if (!empty($arrayfields['t.planned_workload']['checked'])) $addcolspan++; - if (!empty($arrayfields['t.progress']['checked'])) $addcolspan++; - foreach ($arrayfields as $key => $val) - { - if ($val['checked'] && substr($key, 0, 5) == 'efpt.') $addcolspan++; + if (!empty($arrayfields['t.planned_workload']['checked'])) { + $addcolspan++; + } + if (!empty($arrayfields['t.progress']['checked'])) { + $addcolspan++; + } + foreach ($arrayfields as $key => $val) { + if ($val['checked'] && substr($key, 0, 5) == 'efpt.') { + $addcolspan++; + } } print ''."\n"; print ''; print $projectstatic->getNomUrl(1, '', 0, ''.$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); - if ($thirdpartystatic->id > 0) print ' - '.$thirdpartystatic->getNomUrl(1); - if ($projectstatic->title) - { + if ($thirdpartystatic->id > 0) { + print ' - '.$thirdpartystatic->getNomUrl(1); + } + if ($projectstatic->title) { print ' - '; print ''.$projectstatic->title.''; } @@ -1541,65 +1656,67 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ print ''; // PROJECT fields - if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); - if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); - if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.fk_opp_status']['checked'])) print_liste_field_titre($arrayfields['p.fk_opp_status']['label'], $_SERVER["PHP_SELF"], 'p.fk_opp_status', "", $param, '', $sortfield, $sortorder, 'center '); + if (! empty($arrayfields['p.opp_amount']['checked'])) print_liste_field_titre($arrayfields['p.opp_amount']['label'], $_SERVER["PHP_SELF"], 'p.opp_amount', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.opp_percent']['checked'])) print_liste_field_titre($arrayfields['p.opp_percent']['label'], $_SERVER["PHP_SELF"], 'p.opp_percent', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.budget_amount']['checked'])) print_liste_field_titre($arrayfields['p.budget_amount']['label'], $_SERVER["PHP_SELF"], 'p.budget_amount', "", $param, '', $sortfield, $sortorder, 'right '); + if (! empty($arrayfields['p.usage_bill_time']['checked'])) print_liste_field_titre($arrayfields['p.usage_bill_time']['label'], $_SERVER["PHP_SELF"], 'p.usage_bill_time', "", $param, '', $sortfield, $sortorder, 'right '); - $extrafieldsobjectkey='projet'; - $extrafieldsobjectprefix='efp.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; + $extrafieldsobjectkey='projet'; + $extrafieldsobjectprefix='efp.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; - print ''; - print ''; + print ''; + print ''; - // PROJECT fields - if (! empty($arrayfields['p.fk_opp_status']['checked'])) - { - print ''; - $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code'); - if ($code) print $langs->trans("OppStatus".$code); - print "\n"; - } - if (! empty($arrayfields['p.opp_amount']['checked'])) - { - print ''; - print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); - print "\n"; - } - if (! empty($arrayfields['p.opp_percent']['checked'])) - { - print ''; - print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %'; - print "\n"; - } - if (! empty($arrayfields['p.budget_amount']['checked'])) - { - print ''; - print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); - print "\n"; - } - if (! empty($arrayfields['p.usage_bill_time']['checked'])) - { - print ''; - print yn($lines[$i]->usage_bill_time); - print "\n"; - } + // PROJECT fields + if (! empty($arrayfields['p.fk_opp_status']['checked'])) + { + print ''; + $code = dol_getIdFromCode($db, $lines[$i]->fk_opp_status, 'c_lead_status', 'rowid', 'code'); + if ($code) print $langs->trans("OppStatus".$code); + print "\n"; + } + if (! empty($arrayfields['p.opp_amount']['checked'])) + { + print ''; + print price($lines[$i]->opp_amount, 0, $langs, 1, 0, -1, $conf->currency); + print "\n"; + } + if (! empty($arrayfields['p.opp_percent']['checked'])) + { + print ''; + print price($lines[$i]->opp_percent, 0, $langs, 1, 0).' %'; + print "\n"; + } + if (! empty($arrayfields['p.budget_amount']['checked'])) + { + print ''; + print price($lines[$i]->budget_amount, 0, $langs, 1, 0, 0, $conf->currency); + print "\n"; + } + if (! empty($arrayfields['p.usage_bill_time']['checked'])) + { + print ''; + print yn($lines[$i]->usage_bill_time); + print "\n"; + } - $extrafieldsobjectkey='projet'; - $extrafieldsobjectprefix='efp.'; - include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + $extrafieldsobjectkey='projet'; + $extrafieldsobjectprefix='efp.'; + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; - print ''; - print ''; + print ''; + print ''; */ print ''; print ''; } - if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + if ($oldprojectforbreak != -1) { + $oldprojectforbreak = $projectstatic->id; + } print ''."\n"; @@ -1611,30 +1728,36 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ */ // Project - if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) - { + if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { print ''; - if ($oldprojectforbreak == -1) print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + if ($oldprojectforbreak == -1) { + print $projectstatic->getNomUrl(1, '', 0, $langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); + } print ""; } // Thirdparty - if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) - { + if (!empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT)) { print ''; - if ($thirdpartystatic->id > 0) print $thirdpartystatic->getNomUrl(1, 'project'); + if ($thirdpartystatic->id > 0) { + print $thirdpartystatic->getNomUrl(1, 'project'); + } print ''; } // Ref print ''; print ''; - for ($k = 0; $k < $level; $k++) print '
    '; + for ($k = 0; $k < $level; $k++) { + print '
    '; + } print $taskstatic->getNomUrl(1, 'withproject', 'time'); // Label task print '
    '; print ''.$taskstatic->label.''; - for ($k = 0; $k < $level; $k++) print "
    "; + for ($k = 0; $k < $level; $k++) { + print "
    "; + } print "\n"; // TASK extrafields @@ -1643,16 +1766,17 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; // Planned Workload - if (!empty($arrayfields['t.planned_workload']['checked'])) - { + if (!empty($arrayfields['t.planned_workload']['checked'])) { print ''; - if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); - else print '--:--'; + if ($lines[$i]->planned_workload) { + print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); + } else { + print '--:--'; + } print ''; } - if (!empty($arrayfields['t.progress']['checked'])) - { + if (!empty($arrayfields['t.progress']['checked'])) { // Progress declared % print ''; print $formother->select_percent($lines[$i]->progress, $lines[$i]->id.'progress'); @@ -1662,19 +1786,23 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ // Time spent by everybody print ''; // $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user - if ($lines[$i]->duration) - { + if ($lines[$i]->duration) { print ''; print convertSecondToTime($lines[$i]->duration, 'allhourmin'); print ''; - } else print '--:--'; + } else { + print '--:--'; + } print "\n"; // Time spent by user print ''; $tmptimespent = $taskstatic->getSummaryOfTimeSpent($fuser->id); - if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); - else print '--:--'; + if ($tmptimespent['total_duration']) { + print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); + } else { + print '--:--'; + } print "\n"; $disabledproject = 1; $disabledtask = 1; @@ -1682,14 +1810,12 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ //var_dump($lines[$i]); //var_dump($projectsrole[$lines[$i]->fk_project]); // If at least one role for project - if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) - { + if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) { $disabledproject = 0; $disabledtask = 0; } // If $restricteditformytask is on and I have no role on task, i disable edit - if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) - { + if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) { $disabledtask = 1; } @@ -1697,57 +1823,62 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ // Fields to show current time $tableCell = ''; $modeinput = 'hours'; - for ($idw = 0; $idw < 7; $idw++) - { + for ($idw = 0; $idw < 7; $idw++) { $tmpday = dol_time_plus_duree($firstdaytoshow, $idw, 'd'); $cssonholiday = ''; - if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayallday '; - elseif (!$isavailable[$tmpday]['morning']) $cssonholiday .= 'onholidaymorning '; - elseif (!$isavailable[$tmpday]['afternoon']) $cssonholiday .= 'onholidayafternoon '; + if (!$isavailable[$tmpday]['morning'] && !$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayallday '; + } elseif (!$isavailable[$tmpday]['morning']) { + $cssonholiday .= 'onholidaymorning '; + } elseif (!$isavailable[$tmpday]['afternoon']) { + $cssonholiday .= 'onholidayafternoon '; + } $tmparray = dol_getdate($tmpday); $dayWorkLoad = $projectstatic->weekWorkLoadPerTask[$tmpday][$lines[$i]->id]; $totalforeachday[$tmpday] += $dayWorkLoad; $alreadyspent = ''; - if ($dayWorkLoad > 0) $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin'); + if ($dayWorkLoad > 0) { + $alreadyspent = convertSecondToTime($dayWorkLoad, 'allhourmin'); + } $alttitle = $langs->trans("AddHereTimeSpentForDay", $tmparray['day'], $tmparray['mon']); global $numstartworkingday, $numendworkingday; $cssweekend = ''; - if (($idw + 1 < $numstartworkingday) || ($idw + 1 > $numendworkingday)) // This is a day is not inside the setup of working days, so we use a week-end css. - { + if (($idw + 1 < $numstartworkingday) || ($idw + 1 > $numendworkingday)) { // This is a day is not inside the setup of working days, so we use a week-end css. $cssweekend = 'weekend'; } $tableCell = ''; //$tableCell .= 'idw='.$idw.' '.$conf->global->MAIN_START_WEEK.' '.$numstartworkingday.'-'.$numendworkingday; $placeholder = ''; - if ($alreadyspent) - { + if ($alreadyspent) { $tableCell .= ''; //$placeholder=' placeholder="00:00"'; - //$tableCell.='+'; + //$tableCell.='+'; } - $tableCell .= ''; - $tableCell .= ''; + $tableCell .= ' onkeyup="updateTotal('.$idw.',\''.$modeinput.'\')"'; + $tableCell .= ' onblur="regexEvent(this,event,\''.$modeinput.'\'); updateTotal('.$idw.',\''.$modeinput.'\')" />'; + $tableCell .= ''; print $tableCell; } // Warning print ''; - if ((!$lines[$i]->public) && $disabledproject) print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); - elseif ($disabledtask) - { - $titleassigntask = $langs->trans("AssignTaskToMe"); - if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + if ((!$lines[$i]->public) && $disabledproject) { + print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); + } elseif ($disabledtask) { + $titleassigntask = $langs->trans("AssignTaskToMe"); + if ($fuser->id != $user->id) { + $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + } - print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); - } + print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); + } print ''; print "\n"; @@ -1756,15 +1887,13 @@ function projectLinesPerWeek(&$inc, $firstdaytoshow, $fuser, $parent, $lines, &$ // Call to show task with a lower level (task under the current task) $inc++; $level++; - if ($lines[$i]->id > 0) - { + if ($lines[$i]->id > 0) { //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level); //var_dump($totalforeachday); $ret = projectLinesPerWeek($inc, $firstdaytoshow, $fuser, $lines[$i]->id, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable, $oldprojectforbreak, $arrayfields, $extrafields); //var_dump('ret with parent='.$lines[$i]->id.' level='.$level); //var_dump($ret); - foreach ($ret as $key => $val) - { + foreach ($ret as $key => $val) { $totalforeachday[$key] += $val; } //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks'); @@ -1810,43 +1939,39 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & $lineswithoutlevel0 = array(); // Create a smaller array with sublevels only to be used later. This increase dramatically performances. - if ($parent == 0) // Always and only if at first level - { - for ($i = 0; $i < $numlines; $i++) - { - if ($lines[$i]->fk_task_parent) $lineswithoutlevel0[] = $lines[$i]; + if ($parent == 0) { // Always and only if at first level + for ($i = 0; $i < $numlines; $i++) { + if ($lines[$i]->fk_task_parent) { + $lineswithoutlevel0[] = $lines[$i]; + } } } //dol_syslog('projectLinesPerWeek inc='.$inc.' firstdaytoshow='.$firstdaytoshow.' task parent id='.$parent.' level='.$level." count(lines)=".$numlines." count(lineswithoutlevel0)=".count($lineswithoutlevel0)); - if (empty($oldprojectforbreak)) - { + if (empty($oldprojectforbreak)) { $oldprojectforbreak = (empty($conf->global->PROJECT_TIMESHEET_DISABLEBREAK_ON_PROJECT) ? 0 : -1); // 0 = start break, -1 = never break } - for ($i = 0; $i < $numlines; $i++) - { - if ($parent == 0) $level = 0; + for ($i = 0; $i < $numlines; $i++) { + if ($parent == 0) { + $level = 0; + } - if ($lines[$i]->fk_task_parent == $parent) - { + if ($lines[$i]->fk_task_parent == $parent) { // If we want all or we have a role on task, we show it - if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) - { + if (empty($mine) || !empty($tasksrole[$lines[$i]->id])) { //dol_syslog("projectLinesPerWeek Found line ".$i.", a qualified task (i have role or want to show all tasks) with id=".$lines[$i]->id." project id=".$lines[$i]->fk_project); // Break on a new project - if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) - { + if ($parent == 0 && $lines[$i]->fk_project != $lastprojectid) { $lastprojectid = $lines[$i]->fk_project; $projectstatic->id = $lines[$i]->fk_project; } //var_dump('--- '.$level.' '.$firstdaytoshow.' '.$fuser->id.' '.$projectstatic->id.' '.$workloadforid[$projectstatic->id]); //var_dump($projectstatic->weekWorkLoadPerTask); - if (empty($workloadforid[$projectstatic->id])) - { + if (empty($workloadforid[$projectstatic->id])) { $projectstatic->loadTimeSpentMonth($firstdaytoshow, 0, $fuser->id); // Load time spent from table projet_task_time for the project into this->weekWorkLoad and this->weekWorkLoadPerTask for all days of a week $workloadforid[$projectstatic->id] = 1; } @@ -1870,14 +1995,14 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & $thirdpartystatic->name = $lines[$i]->thirdparty_name; $thirdpartystatic->email = $lines[$i]->thirdparty_email; - if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) - { + if (empty($oldprojectforbreak) || ($oldprojectforbreak != -1 && $oldprojectforbreak != $projectstatic->id)) { print ''."\n"; print ''; print $projectstatic->getNomUrl(1, '', 0, ''.$langs->transnoentitiesnoconv("YourRole").': '.$projectsrole[$lines[$i]->fk_project]); - if ($thirdpartystatic->id > 0) print ' - '.$thirdpartystatic->getNomUrl(1); - if ($projectstatic->title) - { + if ($thirdpartystatic->id > 0) { + print ' - '.$thirdpartystatic->getNomUrl(1); + } + if ($projectstatic->title) { print ' - '; print ''.$projectstatic->title.''; } @@ -1885,7 +2010,9 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & print ''; } - if ($oldprojectforbreak != -1) $oldprojectforbreak = $projectstatic->id; + if ($oldprojectforbreak != -1) { + $oldprojectforbreak = $projectstatic->id; + } print ''."\n"; // User @@ -1908,18 +2035,25 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & // Ref print ''; print ''; - for ($k = 0; $k < $level; $k++) print '
    '; + for ($k = 0; $k < $level; $k++) { + print '
    '; + } print $taskstatic->getNomUrl(1, 'withproject', 'time'); // Label task print '
    '; print ''.$taskstatic->label.''; - for ($k = 0; $k < $level; $k++) print "
    "; + for ($k = 0; $k < $level; $k++) { + print "
    "; + } print "\n"; // Planned Workload print ''; - if ($lines[$i]->planned_workload) print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); - else print '--:--'; + if ($lines[$i]->planned_workload) { + print convertSecondToTime($lines[$i]->planned_workload, 'allhourmin'); + } else { + print '--:--'; + } print ''; // Progress declared % @@ -1930,19 +2064,23 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & // Time spent by everybody print ''; // $lines[$i]->duration is a denormalised field = summ of time spent by everybody for task. What we need is time consummed by user - if ($lines[$i]->duration) - { + if ($lines[$i]->duration) { print ''; print convertSecondToTime($lines[$i]->duration, 'allhourmin'); print ''; - } else print '--:--'; + } else { + print '--:--'; + } print "\n"; // Time spent by user print ''; $tmptimespent = $taskstatic->getSummaryOfTimeSpent($fuser->id); - if ($tmptimespent['total_duration']) print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); - else print '--:--'; + if ($tmptimespent['total_duration']) { + print convertSecondToTime($tmptimespent['total_duration'], 'allhourmin'); + } else { + print '--:--'; + } print "\n"; $disabledproject = 1; $disabledtask = 1; @@ -1950,14 +2088,12 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & //var_dump($lines[$i]); //var_dump($projectsrole[$lines[$i]->fk_project]); // If at least one role for project - if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) - { + if ($lines[$i]->public || !empty($projectsrole[$lines[$i]->fk_project]) || $user->rights->projet->all->creer) { $disabledproject = 0; $disabledtask = 0; } // If $restricteditformytask is on and I have no role on task, i disable edit - if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) - { + if ($restricteditformytask && empty($tasksrole[$lines[$i]->id])) { $disabledtask = 1; } @@ -1970,20 +2106,20 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & foreach ($TFirstDay as &$fday) { $fday--; } - foreach ($TWeek as $weekNb) - { + foreach ($TWeek as $weekNb) { $weekWorkLoad = $projectstatic->monthWorkLoadPerTask[$weekNb][$lines[$i]->id]; $totalforeachweek[$weekNb] += $weekWorkLoad; $alreadyspent = ''; - if ($weekWorkLoad > 0) $alreadyspent = convertSecondToTime($weekWorkLoad, 'allhourmin'); + if ($weekWorkLoad > 0) { + $alreadyspent = convertSecondToTime($weekWorkLoad, 'allhourmin'); + } $alttitle = $langs->trans("AddHereTimeSpentForWeek", $weekNb); $tableCell = ''; $placeholder = ''; - if ($alreadyspent) - { + if ($alreadyspent) { $tableCell .= ''; //$placeholder=' placeholder="00:00"'; //$tableCell.='+'; @@ -1999,11 +2135,13 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & // Warning print ''; - if ((!$lines[$i]->public) && $disabledproject) print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); - elseif ($disabledtask) - { + if ((!$lines[$i]->public) && $disabledproject) { + print $form->textwithpicto('', $langs->trans("UserIsNotContactOfProject")); + } elseif ($disabledtask) { $titleassigntask = $langs->trans("AssignTaskToMe"); - if ($fuser->id != $user->id) $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + if ($fuser->id != $user->id) { + $titleassigntask = $langs->trans("AssignTaskToUser", '...'); + } print $form->textwithpicto('', $langs->trans("TaskIsNotAssignedToUser", $titleassigntask)); } @@ -2015,15 +2153,13 @@ function projectLinesPerMonth(&$inc, $firstdaytoshow, $fuser, $parent, $lines, & // Call to show task with a lower level (task under the current task) $inc++; $level++; - if ($lines[$i]->id > 0) - { + if ($lines[$i]->id > 0) { //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level); //var_dump($totalforeachday); $ret = projectLinesPerMonth($inc, $firstdaytoshow, $fuser, $lines[$i]->id, ($parent == 0 ? $lineswithoutlevel0 : $lines), $level, $projectsrole, $tasksrole, $mine, $restricteditformytask, $isavailable, $oldprojectforbreak, $TWeek); //var_dump('ret with parent='.$lines[$i]->id.' level='.$level); //var_dump($ret); - foreach ($ret as $key => $val) - { + foreach ($ret as $key => $val) { $totalforeachweek[$key] += $val; } //var_dump('totalforeachday after taskid='.$lines[$i]->id.' and previous one on level '.$level.' + subtasks'); @@ -2052,14 +2188,11 @@ function searchTaskInChild(&$inc, $parent, &$lines, &$taskrole) { //print 'Search in line with parent id = '.$parent.'
    '; $numlines = count($lines); - for ($i = 0; $i < $numlines; $i++) - { + for ($i = 0; $i < $numlines; $i++) { // Process line $lines[$i] - if ($lines[$i]->fk_parent == $parent && $lines[$i]->id != $lines[$i]->fk_parent) - { + if ($lines[$i]->fk_parent == $parent && $lines[$i]->id != $lines[$i]->fk_parent) { // If task is legitimate to show, no more need to search deeper - if (isset($taskrole[$lines[$i]->id])) - { + if (isset($taskrole[$lines[$i]->id])) { //print 'Found a legitimate task id='.$lines[$i]->id.'
    '; $inc++; return $inc; @@ -2068,7 +2201,9 @@ function searchTaskInChild(&$inc, $parent, &$lines, &$taskrole) searchTaskInChild($inc, $lines[$i]->id, $lines, $taskrole); //print 'Found inc='.$inc.'
    '; - if ($inc > 0) return $inc; + if ($inc > 0) { + return $inc; + } } } @@ -2119,7 +2254,9 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks $project_year_filter = 0; $title = $langs->trans("Projects"); - if (strcmp($status, '') && $status >= 0) $title = $langs->trans("Projects").' '.$langs->trans($projectstatic->statuts_long[$status]); + if (strcmp($status, '') && $status >= 0) { + $title = $langs->trans("Projects").' '.$langs->trans($projectstatic->statuts_long[$status]); + } $arrayidtypeofcontact = array(); @@ -2127,8 +2264,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print ''; $sql = " FROM ".MAIN_DB_PREFIX."projet as p"; - if ($mytasks) - { + if ($mytasks) { $sql .= ", ".MAIN_DB_PREFIX."projet_task as t"; $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as ctc"; @@ -2137,27 +2273,24 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks } $sql .= " WHERE p.entity IN (".getEntity('project').")"; $sql .= " AND p.rowid IN (".$projectsListId.")"; - if ($socid) $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; - if ($mytasks) - { + if ($socid) { + $sql .= " AND (p.fk_soc IS NULL OR p.fk_soc = 0 OR p.fk_soc = ".$socid.")"; + } + if ($mytasks) { $sql .= " AND p.rowid = t.fk_projet"; $sql .= " AND ec.element_id = t.rowid"; $sql .= " AND ec.fk_socpeople = ".$user->id; $sql .= " AND ec.fk_c_type_contact = ctc.rowid"; // Replace the 2 lines with ec.fk_c_type_contact in $arrayidtypeofcontact $sql .= " AND ctc.element = 'project_task'"; } - if ($status >= 0) - { + if ($status >= 0) { $sql .= " AND p.fk_statut = ".(int) $status; } - if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE)) - { + if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE)) { $project_year_filter = GETPOST("project_year_filter"); //Check if empty or invalid year. Wildcard ignores the sql check - if ($project_year_filter != "*") - { - if (empty($project_year_filter) || !ctype_digit($project_year_filter)) - { + if ($project_year_filter != "*") { + if (empty($project_year_filter) || !ctype_digit($project_year_filter)) { $project_year_filter = date("Y"); } $sql .= " AND (p.dateo IS NULL OR p.dateo <= ".$db->idate(dol_get_last_day($project_year_filter, 12, false)).")"; @@ -2170,18 +2303,20 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks $sql1 = "SELECT p.rowid as projectid"; $sql1 .= $sql; $resql = $db->query($sql1); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $arrayidofprojects[$objp->projectid] = $objp->projectid; $i++; } - } else dol_print_error($db); - if (empty($arrayidofprojects)) $arrayidofprojects[0] = -1; + } else { + dol_print_error($db); + } + if (empty($arrayidofprojects)) { + $arrayidofprojects[0] = -1; + } // Get list of project with calculation on tasks $sql2 = "SELECT p.rowid as projectid, p.ref, p.title, p.fk_soc,"; @@ -2201,8 +2336,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks $sql2 .= " ORDER BY p.title, p.ref"; $resql = $db->query($sql2); - if ($resql) - { + if ($resql) { $total_task = 0; $total_opp_amount = 0; $ponderated_opp_amount = 0; @@ -2213,25 +2347,30 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print ''; print_liste_field_titre($title.''.$num.'', $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); print_liste_field_titre("ThirdParty", $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder); - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { - if (!in_array('prospectionstatus', $hiddenfields)) print_liste_field_titre("OpportunityStatus", "", "", "", "", '', $sortfield, $sortorder, 'right '); + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { + if (!in_array('prospectionstatus', $hiddenfields)) { + print_liste_field_titre("OpportunityStatus", "", "", "", "", '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre("OpportunityAmount", "", "", "", "", 'align="right"', $sortfield, $sortorder); //print_liste_field_titre('OpportunityWeightedAmount', '', '', '', '', 'align="right"', $sortfield, $sortorder); } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print_liste_field_titre("Tasks", "", "", "", "", 'align="right"', $sortfield, $sortorder); - if (!in_array('plannedworkload', $hiddenfields)) print_liste_field_titre("PlannedWorkload", "", "", "", "", '', $sortfield, $sortorder, 'right '); - if (!in_array('declaredprogress', $hiddenfields)) print_liste_field_titre("ProgressDeclared", "", "", "", "", '', $sortfield, $sortorder, 'right '); + if (!in_array('plannedworkload', $hiddenfields)) { + print_liste_field_titre("PlannedWorkload", "", "", "", "", '', $sortfield, $sortorder, 'right '); + } + if (!in_array('declaredprogress', $hiddenfields)) { + print_liste_field_titre("ProgressDeclared", "", "", "", "", '', $sortfield, $sortorder, 'right '); + } + } + if (!in_array('projectstatus', $hiddenfields)) { + print_liste_field_titre("Status", "", "", "", "", '', $sortfield, $sortorder, 'right '); } - if (!in_array('projectstatus', $hiddenfields)) print_liste_field_titre("Status", "", "", "", "", '', $sortfield, $sortorder, 'right '); print "\n"; $total_plannedworkload = 0; $total_declaredprogressworkload = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $projectstatic->id = $objp->projectid; @@ -2240,8 +2379,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks // Check is user has read permission on project $userAccess = $projectstatic->restrictedProjectArea($user); - if ($userAccess >= 0) - { + if ($userAccess >= 0) { $projectstatic->ref = $objp->ref; $projectstatic->status = $objp->status; $projectstatic->title = $objp->title; @@ -2252,12 +2390,13 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print ''; print ''; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { if (!in_array('prospectionstatus', $hiddenfields)) { print ''; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print ''; $plannedworkload = $objp->planned_workload; $total_plannedworkload += $plannedworkload; - if (!in_array('plannedworkload', $hiddenfields)) - { + if (!in_array('plannedworkload', $hiddenfields)) { print ''; } - if (!in_array('declaredprogress', $hiddenfields)) - { + if (!in_array('declaredprogress', $hiddenfields)) { $declaredprogressworkload = $objp->declared_progess_workload; $total_declaredprogressworkload += $declaredprogressworkload; print ''; print '"; - if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) - { + if (!empty($conf->global->PROJECT_USE_OPPORTUNITIES)) { if (!in_array('prospectionstatus', $hiddenfields)) { print ''; } @@ -2361,11 +2497,14 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print $form->textwithpicto(price($total_opp_amount, 0, '', 1, -1, 0, $conf->currency), $langs->trans("OpportunityPonderatedAmountDesc").' : '.price($ponderated_opp_amount, 0, '', 1, -1, 0, $conf->currency)); print ''; } - if (empty($conf->global->PROJECT_HIDE_TASKS)) - { + if (empty($conf->global->PROJECT_HIDE_TASKS)) { print ''; - if (!in_array('plannedworkload', $hiddenfields)) print ''; - if (!in_array('declaredprogress', $hiddenfields)) print ''; + if (!in_array('plannedworkload', $hiddenfields)) { + print ''; + } + if (!in_array('declaredprogress', $hiddenfields)) { + print ''; + } } if (!in_array('projectstatus', $hiddenfields)) { print ''; @@ -2380,8 +2519,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print "
    '; print $projectstatic->getNomUrl(1, '', 0, '', '-', 0, -1, 'nowraponall'); - if (!in_array('projectlabel', $hiddenfields)) print '
    '.dol_trunc($objp->title, 24).''; + if (!in_array('projectlabel', $hiddenfields)) { + print '
    '.dol_trunc($objp->title, 24).''; + } print '
    '; - if ($objp->fk_soc > 0) - { + if ($objp->fk_soc > 0) { $thirdpartystatic->id = $objp->socid; $thirdpartystatic->name = $objp->socname; //$thirdpartystatic->name_alias = $objp->name_alias; @@ -2274,8 +2413,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks } print ''; // Because color of prospection status has no meaning yet, it is used if hidden constant is set @@ -2309,22 +2447,21 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks $alttext = $langs->trans("OpportunityWeightedAmount").' '.price($opp_weighted_amount, 0, '', 1, -1, 0, $conf->currency); $ponderated_opp_amount += price2num($opp_weighted_amount); } - if ($objp->opp_amount) print ''.price($objp->opp_amount, 0, '', 1, -1, 0, $conf->currency).''; + if ($objp->opp_amount) { + print ''.price($objp->opp_amount, 0, '', 1, -1, 0, $conf->currency).''; + } print ''.$objp->nb.''.($plannedworkload ?convertSecondToTime($plannedworkload) : '').''; @@ -2351,8 +2488,7 @@ function print_projecttasks_array($db, $form, $socid, $projectsListId, $mytasks print '
    '.$langs->trans("Total")."'.$total_task.''.($total_plannedworkload ?convertSecondToTime($total_plannedworkload) : '').''.($total_plannedworkload ?round(100 * $total_declaredprogressworkload / $total_plannedworkload, 0).'%' : '').''.($total_plannedworkload ?convertSecondToTime($total_plannedworkload) : '').''.($total_plannedworkload ?round(100 * $total_declaredprogressworkload / $total_plannedworkload, 0).'%' : '').'
    "; print '
    '; - if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE)) - { + if (!empty($conf->global->PROJECT_LIMIT_YEAR_RANGE)) { //Add the year filter input print ''; print ''; @@ -2410,8 +2548,12 @@ function getTaskProgressView($task, $label = true, $progressNumber = true, $hide $plannedworkloadoutputformat = 'allhourmin'; $timespentoutputformat = 'allhourmin'; - if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; - if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; + if (!empty($conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT)) { + $plannedworkloadoutputformat = $conf->global->PROJECT_PLANNED_WORKLOAD_FORMAT; + } + if (!empty($conf->global->PROJECT_TIMES_SPENT_FORMAT)) { + $timespentoutputformat = $conf->global->PROJECT_TIME_SPENT_FORMAT; + } if (empty($task->progress) && !empty($hideOnProgressNull)) { return ''; @@ -2450,8 +2592,7 @@ function getTaskProgressView($task, $label = true, $progressNumber = true, $hide $out .= '
    '; - if ($label !== false) - { + if ($label !== false) { $out .= ' '; if ($label !== true) { @@ -2463,21 +2604,25 @@ function getTaskProgressView($task, $label = true, $progressNumber = true, $hide } - if ($progressNumber !== false) - { + if ($progressNumber !== false) { $out .= ' '; if ($progressNumber !== true) { $out .= $progressNumber; // replace label by param } else { - if ($task->hasDelay()) $out .= img_warning($langs->trans("Late")).' '; + if ($task->hasDelay()) { + $out .= img_warning($langs->trans("Late")).' '; + } $url = DOL_URL_ROOT.'/projet/tasks/time.php?id='.$task->id; $out .= !empty($diff) ? $diff.' ' : ''; $out .= ''; $out .= ''; - if ($task->duration_effective) $out .= convertSecondToTime($task->duration_effective, $timespentoutputformat); - else $out .= '--:--'; + if ($task->duration_effective) { + $out .= convertSecondToTime($task->duration_effective, $timespentoutputformat); + } else { + $out .= '--:--'; + } $out .= ''; $out .= ''; @@ -2485,8 +2630,11 @@ function getTaskProgressView($task, $label = true, $progressNumber = true, $hide $out .= ''; $out .= ''; - if ($task->planned_workload) $out .= convertSecondToTime($task->planned_workload, $plannedworkloadoutputformat); - else $out .= '--:--'; + if ($task->planned_workload) { + $out .= convertSecondToTime($task->planned_workload, $plannedworkloadoutputformat); + } else { + $out .= '--:--'; + } $out .= ''; } $out .= ' '; @@ -2529,8 +2677,7 @@ function getTaskProgressBadge($task, $label = '', $tooltip = '') $out = ''; $badgeClass = ''; - if ($task->progress != '') - { + if ($task->progress != '') { // TODO : manage 100% // define color according to time spend vs workload @@ -2548,10 +2695,14 @@ function getTaskProgressBadge($task, $label = '', $tooltip = '') } } elseif (doubleval($progressCalculated) > doubleval($task->progress)) { // warning if close at 10% $badgeClass .= 'badge-warning'; - if (empty($tooltip)) $tooltip = $task->progress.'% < '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; + if (empty($tooltip)) { + $tooltip = $task->progress.'% < '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; + } } else { $badgeClass .= 'badge-success'; - if (empty($tooltip)) $tooltip = $task->progress.'% >= '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; + if (empty($tooltip)) { + $tooltip = $task->progress.'% >= '.$langs->trans("TimeConsumed").' '.$progressCalculated.'%'; + } } } } diff --git a/htdocs/core/lib/propal.lib.php b/htdocs/core/lib/propal.lib.php index bd3a30151da..3ddd3ab1b2b 100644 --- a/htdocs/core/lib/propal.lib.php +++ b/htdocs/core/lib/propal.lib.php @@ -43,24 +43,28 @@ function propal_prepare_head($object) $h++; if ((empty($conf->commande->enabled) && ((!empty($conf->expedition->enabled) && !empty($conf->expedition_bon->enabled) && $user->rights->expedition->lire) - || (!empty($conf->expedition->enabled) && !empty($conf->delivery_note->enabled) && $user->rights->expedition->delivery->lire)))) - { + || (!empty($conf->expedition->enabled) && !empty($conf->delivery_note->enabled) && $user->rights->expedition->delivery->lire)))) { $langs->load("sendings"); $text = ''; $head[$h][0] = DOL_URL_ROOT.'/expedition/propal.php?id='.$object->id; - if ($conf->expedition_bon->enabled) $text = $langs->trans("Shipment"); - if ($conf->delivery_note->enabled) $text .= '/'.$langs->trans("Receivings"); + if ($conf->expedition_bon->enabled) { + $text = $langs->trans("Shipment"); + } + if ($conf->delivery_note->enabled) { + $text .= '/'.$langs->trans("Receivings"); + } $head[$h][1] = $text; $head[$h][2] = 'shipping'; $h++; } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/comm/propal/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -71,14 +75,19 @@ function propal_prepare_head($object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'propal'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/comm/propal/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -90,7 +99,9 @@ function propal_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/comm/propal/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/core/lib/receiptprinter.lib.php b/htdocs/core/lib/receiptprinter.lib.php index e5589f30707..7bbfbc66387 100644 --- a/htdocs/core/lib/receiptprinter.lib.php +++ b/htdocs/core/lib/receiptprinter.lib.php @@ -47,8 +47,7 @@ function receiptprinteradmin_prepare_head($mode) $head[$h][2] = 'template'; $h++; - if ($mode == 'test') - { + if ($mode == 'test') { $head[$h][0] = DOL_URL_ROOT."/admin/receiptprinter.php?mode=test"; $head[$h][1] = $langs->trans("TargetedPrinter"); $head[$h][2] = 'test'; diff --git a/htdocs/core/lib/reception.lib.php b/htdocs/core/lib/reception.lib.php index f36295e31f3..42355497286 100644 --- a/htdocs/core/lib/reception.lib.php +++ b/htdocs/core/lib/reception.lib.php @@ -47,18 +47,18 @@ function reception_prepare_head(Reception $object) $head[$h][2] = 'reception'; $h++; - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $objectsrc = $object; - if ($object->origin == 'commande' && $object->origin_id > 0) - { + if ($object->origin == 'commande' && $object->origin_id > 0) { $objectsrc = new Commande($db); $objectsrc->fetch($object->origin_id); } $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT."/reception/contact.php?id=".$object->id; $head[$h][1] = $langs->trans("ContactsAddresses"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -70,11 +70,17 @@ function reception_prepare_head(Reception $object) complete_head_from_modules($conf, $langs, $object, $head, $h, 'reception'); $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT."/reception/note.php?id=".$object->id; $head[$h][1] = $langs->trans("Notes"); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; @@ -103,16 +109,14 @@ function reception_admin_prepare_head() complete_head_from_modules($conf, $langs, null, $head, $h, 'reception_admin'); - if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) - { + if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) { $head[$h][0] = DOL_URL_ROOT.'/admin/reception_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFields"); $head[$h][2] = 'attributes_reception'; $h++; } - if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) - { + if (!empty($conf->global->MAIN_SUBMODULE_RECEPTION)) { $head[$h][0] = DOL_URL_ROOT.'/admin/commande_fournisseur_dispatch_extrafields.php'; $head[$h][1] = $langs->trans("ExtraFieldsLines"); $head[$h][2] = 'attributeslines_reception'; diff --git a/htdocs/core/lib/report.lib.php b/htdocs/core/lib/report.lib.php index b23acd76a5b..a4279d27a95 100644 --- a/htdocs/core/lib/report.lib.php +++ b/htdocs/core/lib/report.lib.php @@ -44,7 +44,9 @@ function report_header($reportname, $notused, $period, $periodlink, $description print "\n\n\n"; - if (!empty($varlink)) $varlink = '?'.$varlink; + if (!empty($varlink)) { + $varlink = '?'.$varlink; + } $head = array(); @@ -58,8 +60,7 @@ function report_header($reportname, $notused, $period, $periodlink, $description print dol_get_fiche_head($head, 'report'); - foreach ($moreparam as $key => $value) - { + foreach ($moreparam as $key => $value) { print ''."\n"; } @@ -73,17 +74,20 @@ function report_header($reportname, $notused, $period, $periodlink, $description print '
    '; - if ($variante) print ''; + if ($variante) { + print ''; + } print ''."\n"; // Calculation mode - if ($calcmode) - { + if ($calcmode) { print ''; print ''; print ''; + if ($variante) { + print ''; + } print ''; print ''."\n"; } @@ -92,8 +96,12 @@ function report_header($reportname, $notused, $period, $periodlink, $description print ''; print ''; print ''; + if ($period) { + print $period; + } + if ($variante) { + print ''; + } print ''; print ''."\n"; @@ -101,7 +109,9 @@ function report_header($reportname, $notused, $period, $periodlink, $description print ''; print ''; print ''; - if ($variante) print ''; + if ($variante) { + print ''; + } print ''."\n"; // Ligne d'export @@ -110,7 +120,9 @@ function report_header($reportname, $notused, $period, $periodlink, $description print ''; - if ($variante) print ''; + if ($variante) { + print ''; + } print ''."\n"; print '
    '; print $reportname; print '
    '.$langs->trans("CalculationMode").''; print $calcmode; - if ($variante) print '
    '.$langs->trans("ReportPeriod").''; - if ($period) print $period; - if ($variante) print ''.$periodlink.''.$periodlink.'
    '.$langs->trans("ReportDescription").''.$description.'
    '; print dol_print_date($builddate, 'dayhour'); print ''.($exportlink ? $langs->trans("Export").': '.$exportlink : '').''.($exportlink ? $langs->trans("Export").': '.$exportlink : '').'
    '."\n"; diff --git a/htdocs/core/lib/resource.lib.php b/htdocs/core/lib/resource.lib.php index a4ba796078f..29cd8a5b089 100644 --- a/htdocs/core/lib/resource.lib.php +++ b/htdocs/core/lib/resource.lib.php @@ -40,12 +40,13 @@ function resource_prepare_head($object) $head[$h][2] = 'resource'; $h++; - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && (empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_USER) || empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_THIPARTY))) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && (empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_USER) || empty($conf->global->RESOURCE_HIDE_ADD_CONTACT_THIPARTY))) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/resource/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -56,14 +57,19 @@ function resource_prepare_head($object) // $this->tabs = array('entity:-tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'resource'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/resource/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -73,14 +79,15 @@ function resource_prepare_head($object) $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); $head[$h][0] = DOL_URL_ROOT.'/resource/document.php?id='.$object->id; $head[$h][1] = $langs->trans("Documents"); - if ($nbFiles > 0) $head[$h][1] .= ''.$nbFiles.''; + if ($nbFiles > 0) { + $head[$h][1] .= ''.$nbFiles.''; + } $head[$h][2] = 'documents'; $h++; $head[$h][0] = DOL_URL_ROOT.'/resource/agenda.php?id='.$object->id; $head[$h][1] = $langs->trans("Events"); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } diff --git a/htdocs/core/lib/salaries.lib.php b/htdocs/core/lib/salaries.lib.php index f4662f43991..c52246203e2 100644 --- a/htdocs/core/lib/salaries.lib.php +++ b/htdocs/core/lib/salaries.lib.php @@ -50,7 +50,9 @@ function salaries_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/salaries/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; diff --git a/htdocs/core/lib/security.lib.php b/htdocs/core/lib/security.lib.php index 9d18dd1dd85..6b95187e5df 100644 --- a/htdocs/core/lib/security.lib.php +++ b/htdocs/core/lib/security.lib.php @@ -37,21 +37,17 @@ */ function dol_encode($chain, $key = '1') { - if (is_numeric($key) && $key == '1') // rule 1 is offset of 17 for char - { + if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char $output_tab = array(); $strlength = dol_strlen($chain); - for ($i = 0; $i < $strlength; $i++) - { + for ($i = 0; $i < $strlength; $i++) { $output_tab[$i] = chr(ord(substr($chain, $i, 1)) + 17); } $chain = implode("", $output_tab); - } elseif ($key) - { + } elseif ($key) { $result = ''; $strlength = dol_strlen($chain); - for ($i = 0; $i < $strlength; $i++) - { + for ($i = 0; $i < $strlength; $i++) { $keychar = substr($key, ($i % strlen($key)) - 1, 1); $result .= chr(ord(substr($chain, $i, 1)) + (ord($keychar) - 65)); } @@ -74,22 +70,18 @@ function dol_decode($chain, $key = '1') { $chain = base64_decode($chain); - if (is_numeric($key) && $key == '1') // rule 1 is offset of 17 for char - { + if (is_numeric($key) && $key == '1') { // rule 1 is offset of 17 for char $output_tab = array(); $strlength = dol_strlen($chain); - for ($i = 0; $i < $strlength; $i++) - { + for ($i = 0; $i < $strlength; $i++) { $output_tab[$i] = chr(ord(substr($chain, $i, 1)) - 17); } $chain = implode("", $output_tab); - } elseif ($key) - { + } elseif ($key) { $result = ''; $strlength = dol_strlen($chain); - for ($i = 0; $i < $strlength; $i++) - { + for ($i = 0; $i < $strlength; $i++) { $keychar = substr($key, ($i % strlen($key)) - 1, 1); $result .= chr(ord(substr($chain, $i, 1)) - (ord($keychar) - 65)); } @@ -115,21 +107,30 @@ function dol_hash($chain, $type = '0') global $conf; // No need to add salt for password_hash - if (($type == '0' || $type == 'auto') && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash')) - { + if (($type == '0' || $type == 'auto') && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_hash')) { return password_hash($chain, PASSWORD_DEFAULT); } // Salt value - if (!empty($conf->global->MAIN_SECURITY_SALT) && $type != '4' && $type !== 'md5openldap') $chain = $conf->global->MAIN_SECURITY_SALT.$chain; + if (!empty($conf->global->MAIN_SECURITY_SALT) && $type != '4' && $type !== 'md5openldap') { + $chain = $conf->global->MAIN_SECURITY_SALT.$chain; + } - if ($type == '1' || $type == 'sha1') return sha1($chain); - elseif ($type == '2' || $type == 'sha1md5') return sha1(md5($chain)); - elseif ($type == '3' || $type == 'md5') return md5($chain); - elseif ($type == '4' || $type == 'md5openldap') return '{md5}'.base64_encode(mhash(MHASH_MD5, $chain)); // For OpenLdap with md5 (based on an unencrypted password in base) - elseif ($type == '5') return hash('sha256', $chain); - elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') return sha1($chain); - elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') return sha1(md5($chain)); + if ($type == '1' || $type == 'sha1') { + return sha1($chain); + } elseif ($type == '2' || $type == 'sha1md5') { + return sha1(md5($chain)); + } elseif ($type == '3' || $type == 'md5') { + return md5($chain); + } elseif ($type == '4' || $type == 'md5openldap') { + return '{md5}'.base64_encode(mhash(MHASH_MD5, $chain)); // For OpenLdap with md5 (based on an unencrypted password in base) + } elseif ($type == '5') { + return hash('sha256', $chain); + } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1') { + return sha1($chain); + } elseif (!empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'sha1md5') { + return sha1(md5($chain)); + } // No particular encoding defined, use default return md5($chain); @@ -151,9 +152,13 @@ function dol_verifyHash($chain, $hash, $type = '0') global $conf; if ($type == '0' && !empty($conf->global->MAIN_SECURITY_HASH_ALGO) && $conf->global->MAIN_SECURITY_HASH_ALGO == 'password_hash' && function_exists('password_verify')) { - if ($hash[0] == '$') return password_verify($chain, $hash); - elseif (strlen($hash) == 32) return dol_verifyHash($chain, $hash, '3'); // md5 - elseif (strlen($hash) == 40) return dol_verifyHash($chain, $hash, '2'); // sha1md5 + if ($hash[0] == '$') { + return password_verify($chain, $hash); + } elseif (strlen($hash) == 32) { + return dol_verifyHash($chain, $hash, '3'); // md5 + } elseif (strlen($hash) == 40) { + return dol_verifyHash($chain, $hash, '2'); // sha1md5 + } return false; } @@ -192,34 +197,57 @@ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $f // Fix syntax of $features param $originalfeatures = $features; - if ($features == 'facturerec') $features = 'facture'; - if ($features == 'mo') $features = 'mrp'; - if ($features == 'member') $features = 'adherent'; - if ($features == 'subscription') { $features = 'adherent'; $feature2 = 'cotisation'; }; - if ($features == 'websitepage') { $features = 'website'; $tableandshare = 'website_page'; $parentfortableentity = 'fk_website@website'; } - if ($features == 'project') $features = 'projet'; - if ($features == 'product') $features = 'produit'; + if ($features == 'facturerec') { + $features = 'facture'; + } + if ($features == 'mo') { + $features = 'mrp'; + } + if ($features == 'member') { + $features = 'adherent'; + } + if ($features == 'subscription') { + $features = 'adherent'; $feature2 = 'cotisation'; + }; + if ($features == 'websitepage') { + $features = 'website'; $tableandshare = 'website_page'; $parentfortableentity = 'fk_website@website'; + } + if ($features == 'project') { + $features = 'projet'; + } + if ($features == 'product') { + $features = 'produit'; + } // Get more permissions checks from hooks $parameters = array('features'=>$features, 'originalfeatures'=>$originalfeatures, 'objectid'=>$objectid, 'dbt_select'=>$dbt_select, 'idtype'=>$dbt_select, 'isdraft'=>$isdraft); $reshook = $hookmanager->executeHooks('restrictedArea', $parameters); if (isset($hookmanager->resArray['result'])) { - if ($hookmanager->resArray['result'] == 0) accessforbidden(); // Module returns 0, so access forbidden + if ($hookmanager->resArray['result'] == 0) { + accessforbidden(); // Module returns 0, so access forbidden + } } if ($reshook > 0) { // No other test done. return 1; } - if ($dbt_select != 'rowid' && $dbt_select != 'id') $objectid = "'".$objectid."'"; + if ($dbt_select != 'rowid' && $dbt_select != 'id') { + $objectid = "'".$objectid."'"; + } // Features/modules to check $featuresarray = array($features); - if (preg_match('/&/', $features)) $featuresarray = explode("&", $features); - elseif (preg_match('/\|/', $features)) $featuresarray = explode("|", $features); + if (preg_match('/&/', $features)) { + $featuresarray = explode("&", $features); + } elseif (preg_match('/\|/', $features)) { + $featuresarray = explode("|", $features); + } // More subfeatures to check - if (!empty($feature2)) $feature2 = explode("|", $feature2); + if (!empty($feature2)) { + $feature2 = explode("|", $feature2); + } $listofmodules = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); @@ -227,33 +255,59 @@ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $f $readok = 1; $nbko = 0; foreach ($featuresarray as $feature) { // first we check nb of test ko $featureforlistofmodule = $feature; - if ($featureforlistofmodule == 'produit') $featureforlistofmodule = 'product'; + if ($featureforlistofmodule == 'produit') { + $featureforlistofmodule = 'product'; + } if (!empty($user->socid) && !empty($conf->global->MAIN_MODULES_FOR_EXTERNAL) && !in_array($featureforlistofmodule, $listofmodules)) { // If limits on modules for external users, module must be into list of modules for external users $readok = 0; $nbko++; continue; } if ($feature == 'societe') { - if (!$user->rights->societe->lire && !$user->rights->fournisseur->lire) { $readok = 0; $nbko++; } + if (!$user->rights->societe->lire && !$user->rights->fournisseur->lire) { + $readok = 0; $nbko++; + } } elseif ($feature == 'contact') { - if (!$user->rights->societe->contact->lire) { $readok = 0; $nbko++; } + if (!$user->rights->societe->contact->lire) { + $readok = 0; $nbko++; + } } elseif ($feature == 'produit|service') { - if (!$user->rights->produit->lire && !$user->rights->service->lire) { $readok = 0; $nbko++; } + if (!$user->rights->produit->lire && !$user->rights->service->lire) { + $readok = 0; $nbko++; + } } elseif ($feature == 'prelevement') { - if (!$user->rights->prelevement->bons->lire) { $readok = 0; $nbko++; } + if (!$user->rights->prelevement->bons->lire) { + $readok = 0; $nbko++; + } } elseif ($feature == 'cheque') { - if (!$user->rights->banque->cheque) { $readok = 0; $nbko++; } + if (!$user->rights->banque->cheque) { + $readok = 0; $nbko++; + } } elseif ($feature == 'projet') { - if (!$user->rights->projet->lire && !$user->rights->projet->all->lire) { $readok = 0; $nbko++; } + if (!$user->rights->projet->lire && !$user->rights->projet->all->lire) { + $readok = 0; $nbko++; + } } elseif ($feature == 'payment') { - if (!$user->rights->facture->lire) { $readok = 0; $nbko++; } + if (!$user->rights->facture->lire) { + $readok = 0; $nbko++; + } } elseif ($feature == 'payment_supplier') { - if (!$user->rights->fournisseur->facture->lire) { $readok = 0; $nbko++; } + if (!$user->rights->fournisseur->facture->lire) { + $readok = 0; $nbko++; + } } elseif (!empty($feature2)) { // This is for permissions on 2 levels $tmpreadok = 1; foreach ($feature2 as $subfeature) { - if ($subfeature == 'user' && $user->id == $objectid) continue; // A user can always read its own card - if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { $tmpreadok = 0; } elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { $tmpreadok = 0; } else { $tmpreadok = 1; break; } // Break is to bypass second test if the first is ok + if ($subfeature == 'user' && $user->id == $objectid) { + continue; // A user can always read its own card + } + if (!empty($subfeature) && empty($user->rights->$feature->$subfeature->lire) && empty($user->rights->$feature->$subfeature->read)) { + $tmpreadok = 0; + } elseif (empty($subfeature) && empty($user->rights->$feature->lire) && empty($user->rights->$feature->read)) { + $tmpreadok = 0; + } else { + $tmpreadok = 1; break; + } // Break is to bypass second test if the first is ok } if (!$tmpreadok) { // We found a test on feature that is ko $readok = 0; // All tests are ko (we manage here the and, the or will be managed later using $nbko). @@ -262,14 +316,20 @@ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $f } elseif (!empty($feature) && ($feature != 'user' && $feature != 'usergroup')) { // This is permissions on 1 level if (empty($user->rights->$feature->lire) && empty($user->rights->$feature->read) - && empty($user->rights->$feature->run)) { $readok = 0; $nbko++; } + && empty($user->rights->$feature->run)) { + $readok = 0; $nbko++; + } } } // If a or and at least one ok - if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $readok = 1; + if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) { + $readok = 1; + } - if (!$readok) accessforbidden(); + if (!$readok) { + accessforbidden(); + } //print "Read access is ok"; // Check write permission from module (we need to know write permission to create but also to delete drafts record or to upload files) @@ -277,30 +337,48 @@ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $f $wemustcheckpermissionforcreate = (GETPOST('sendit', 'alpha') || GETPOST('linkit', 'alpha') || GETPOST('action', 'aZ09') == 'create' || GETPOST('action', 'aZ09') == 'update'); $wemustcheckpermissionfordeletedraft = ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete'); - if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) - { - foreach ($featuresarray as $feature) - { + if ($wemustcheckpermissionforcreate || $wemustcheckpermissionfordeletedraft) { + foreach ($featuresarray as $feature) { if ($feature == 'contact') { - if (!$user->rights->societe->contact->creer) { $createok = 0; $nbko++; } + if (!$user->rights->societe->contact->creer) { + $createok = 0; $nbko++; + } } elseif ($feature == 'produit|service') { - if (!$user->rights->produit->creer && !$user->rights->service->creer) { $createok = 0; $nbko++; } + if (!$user->rights->produit->creer && !$user->rights->service->creer) { + $createok = 0; $nbko++; + } } elseif ($feature == 'prelevement') { - if (!$user->rights->prelevement->bons->creer) { $createok = 0; $nbko++; } + if (!$user->rights->prelevement->bons->creer) { + $createok = 0; $nbko++; + } } elseif ($feature == 'commande_fournisseur') { - if (!$user->rights->fournisseur->commande->creer) { $createok = 0; $nbko++; } + if (!$user->rights->fournisseur->commande->creer) { + $createok = 0; $nbko++; + } } elseif ($feature == 'banque') { - if (!$user->rights->banque->modifier) { $createok = 0; $nbko++; } + if (!$user->rights->banque->modifier) { + $createok = 0; $nbko++; + } } elseif ($feature == 'cheque') { - if (!$user->rights->banque->cheque) { $createok = 0; $nbko++; } + if (!$user->rights->banque->cheque) { + $createok = 0; $nbko++; + } } elseif ($feature == 'import') { - if (!$user->rights->import->run) { $createok = 0; $nbko++; } + if (!$user->rights->import->run) { + $createok = 0; $nbko++; + } } elseif ($feature == 'ecm') { - if (!$user->rights->ecm->upload) { $createok = 0; $nbko++; } + if (!$user->rights->ecm->upload) { + $createok = 0; $nbko++; + } } elseif (!empty($feature2)) { // This is for permissions on one level foreach ($feature2 as $subfeature) { - if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->creer) continue; // User can edit its own card - if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->password) continue; // User can edit its own password + if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->creer) { + continue; // User can edit its own card + } + if ($subfeature == 'user' && $user->id == $objectid && $user->rights->user->self->password) { + continue; // User can edit its own password + } if (empty($user->rights->$feature->$subfeature->creer) && empty($user->rights->$feature->$subfeature->write) @@ -325,82 +403,101 @@ function restrictedArea($user, $features, $objectid = 0, $tableandshare = '', $f } // If a or and at least one ok - if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $createok = 1; + if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) { + $createok = 1; + } - if ($wemustcheckpermissionforcreate && !$createok) accessforbidden(); + if ($wemustcheckpermissionforcreate && !$createok) { + accessforbidden(); + } //print "Write access is ok"; } // Check create user permission $createuserok = 1; - if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') - { - if (!$user->rights->user->user->creer) $createuserok = 0; + if (GETPOST('action', 'aZ09') == 'confirm_create_user' && GETPOST("confirm", 'aZ09') == 'yes') { + if (!$user->rights->user->user->creer) { + $createuserok = 0; + } - if (!$createuserok) accessforbidden(); + if (!$createuserok) { + accessforbidden(); + } //print "Create user access is ok"; } // Check delete permission from module $deleteok = 1; $nbko = 0; - if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete') - { - foreach ($featuresarray as $feature) - { - if ($feature == 'contact') - { - if (!$user->rights->societe->contact->supprimer) $deleteok = 0; - } elseif ($feature == 'produit|service') - { - if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) $deleteok = 0; - } elseif ($feature == 'commande_fournisseur') - { - if (!$user->rights->fournisseur->commande->supprimer) $deleteok = 0; - } elseif ($feature == 'banque') - { - if (!$user->rights->banque->modifier) $deleteok = 0; - } elseif ($feature == 'cheque') - { - if (!$user->rights->banque->cheque) $deleteok = 0; - } elseif ($feature == 'ecm') - { - if (!$user->rights->ecm->upload) $deleteok = 0; - } elseif ($feature == 'ftp') - { - if (!$user->rights->ftp->write) $deleteok = 0; - } elseif ($feature == 'salaries') - { - if (!$user->rights->salaries->delete) $deleteok = 0; - } elseif ($feature == 'salaries') - { - if (!$user->rights->salaries->delete) $deleteok = 0; - } elseif (!empty($feature2)) // This is for permissions on 2 levels - { - foreach ($feature2 as $subfeature) - { - if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) $deleteok = 0; - else { $deleteok = 1; break; } // For bypass the second test if the first is ok + if ((GETPOST("action", "aZ09") == 'confirm_delete' && GETPOST("confirm", "aZ09") == 'yes') || GETPOST("action", "aZ09") == 'delete') { + foreach ($featuresarray as $feature) { + if ($feature == 'contact') { + if (!$user->rights->societe->contact->supprimer) { + $deleteok = 0; } - } elseif (!empty($feature)) // This is used for permissions on 1 level - { + } elseif ($feature == 'produit|service') { + if (!$user->rights->produit->supprimer && !$user->rights->service->supprimer) { + $deleteok = 0; + } + } elseif ($feature == 'commande_fournisseur') { + if (!$user->rights->fournisseur->commande->supprimer) { + $deleteok = 0; + } + } elseif ($feature == 'banque') { + if (!$user->rights->banque->modifier) { + $deleteok = 0; + } + } elseif ($feature == 'cheque') { + if (!$user->rights->banque->cheque) { + $deleteok = 0; + } + } elseif ($feature == 'ecm') { + if (!$user->rights->ecm->upload) { + $deleteok = 0; + } + } elseif ($feature == 'ftp') { + if (!$user->rights->ftp->write) { + $deleteok = 0; + } + } elseif ($feature == 'salaries') { + if (!$user->rights->salaries->delete) { + $deleteok = 0; + } + } elseif ($feature == 'salaries') { + if (!$user->rights->salaries->delete) { + $deleteok = 0; + } + } elseif (!empty($feature2)) { // This is for permissions on 2 levels + foreach ($feature2 as $subfeature) { + if (empty($user->rights->$feature->$subfeature->supprimer) && empty($user->rights->$feature->$subfeature->delete)) { + $deleteok = 0; + } else { + $deleteok = 1; break; + } // For bypass the second test if the first is ok + } + } elseif (!empty($feature)) { // This is used for permissions on 1 level //print '
    feature='.$feature.' creer='.$user->rights->$feature->supprimer.' write='.$user->rights->$feature->delete; if (empty($user->rights->$feature->supprimer) && empty($user->rights->$feature->delete) - && empty($user->rights->$feature->run)) $deleteok = 0; + && empty($user->rights->$feature->run)) { + $deleteok = 0; + } } } // If a or and at least one ok - if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) $deleteok = 1; + if (preg_match('/\|/', $features) && $nbko < count($featuresarray)) { + $deleteok = 1; + } - if (!$deleteok && !($isdraft && $createok)) accessforbidden(); + if (!$deleteok && !($isdraft && $createok)) { + accessforbidden(); + } //print "Delete access is ok"; } // If we have a particular object to check permissions on, we check this object // is linked to a company allowed to $user. - if (!empty($objectid) && $objectid > 0) - { + if (!empty($objectid) && $objectid > 0) { $ok = checkUserAccessToObject($user, $featuresarray, $objectid, $tableandshare, $feature2, $dbt_keyfield, $dbt_select, $parentfortableentity); $params = array('objectid' => $objectid, 'features' => join(',', $featuresarray), 'features2' => $feature2); return $ok ? 1 : accessforbidden('', 1, 1, 0, $params); @@ -437,14 +534,19 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $dbtablename = (!empty($params[0]) ? $params[0] : ''); $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); - foreach ($featuresarray as $feature) - { + foreach ($featuresarray as $feature) { $sql = ''; // For backward compatibility - if ($feature == 'member') $feature = 'adherent'; - if ($feature == 'project') $feature = 'projet'; - if ($feature == 'task') $feature = 'projet_task'; + if ($feature == 'member') { + $feature = 'adherent'; + } + if ($feature == 'project') { + $feature = 'projet'; + } + if ($feature == 'task') { + $feature = 'projet_task'; + } $check = array('adherent', 'banque', 'bom', 'don', 'mrp', 'user', 'usergroup', 'payment', 'payment_supplier', 'product', 'produit', 'service', 'produit|service', 'categorie', 'resource', 'expensereport', 'holiday', 'website'); // Test on entity only (Objects with no link to company) $checksoc = array('societe'); // Test for societe object @@ -455,15 +557,13 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand //$checkdefault = 'all other not already defined'; // Test on entity + link to third party on field $dbt_keyfield. Not allowed if link is empty (Ex: invoice, orders...). // If dbtablename not defined, we use same name for table than module name - if (empty($dbtablename)) - { + if (empty($dbtablename)) { $dbtablename = $feature; $sharedelement = (!empty($params[1]) ? $params[1] : $dbtablename); // We change dbtablename, so we set sharedelement too. } // Check permission for object on entity only - if (in_array($feature, $check)) - { + if (in_array($feature, $check)) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; if (($feature == 'user' || $feature == 'usergroup') && !empty($conf->multicompany->enabled)) { // Special for multicompany @@ -496,7 +596,9 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand } elseif (in_array($feature, $checksoc)) { // We check feature = checksoc if ($user->socid > 0) { // If external user: Check permission for external users - if ($user->socid <> $objectid) return false; + if ($user->socid <> $objectid) { + return false; + } } elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) { // If internal user: Check permission for internal users that are restricted on their objects $sql = "SELECT COUNT(sc.fk_soc) as nb"; @@ -513,18 +615,15 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $sql .= " WHERE s.rowid IN (".$objectid.")"; $sql .= " AND s.entity IN (".getEntity($sharedelement, 1).")"; } - } elseif (in_array($feature, $checkother)) // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...). - { + } elseif (in_array($feature, $checkother)) { // Test on entity + link to thirdparty. Allowed if link is empty (Ex: contacts...). // If external user: Check permission for external users - if ($user->socid > 0) - { + if ($user->socid > 0) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.fk_soc = ".$user->socid; } // If internal user: Check permission for internal users that are restricted on their objects - elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) - { + elseif (!empty($conf->societe->enabled) && ($user->rights->societe->lire && !$user->rights->societe->client->voir)) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON dbt.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id); @@ -532,15 +631,13 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $sql .= " AND (dbt.fk_soc IS NULL OR sc.fk_soc IS NOT NULL)"; // Contact not linked to a company or to a company of user $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } // If multicompany and internal users with all permissions, check user is in correct entity - elseif (!empty($conf->multicompany->enabled)) - { + elseif (!empty($conf->multicompany->enabled)) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } - if ($feature == 'agenda')// Also check owner or attendee for users without allactions->read - { + if ($feature == 'agenda') {// Also check owner or attendee for users without allactions->read if ($objectid > 0 && empty($user->rights->agenda->allactions->read)) { require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php'; $action = new ActionComm($db); @@ -551,13 +648,14 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand } } } elseif (in_array($feature, $checkproject)) { - if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) - { + if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) { include_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; $projectstatic = new Project($db); $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0); $tmparray = explode(',', $tmps); - if (!in_array($objectid, $tmparray)) return false; + if (!in_array($objectid, $tmparray)) { + return false; + } } else { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; @@ -565,8 +663,7 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $sql .= " AND dbt.entity IN (".getEntity($sharedelement, 1).")"; } } elseif (in_array($feature, $checktask)) { - if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) - { + if (!empty($conf->projet->enabled) && empty($user->rights->projet->all->lire)) { $task = new Task($db); $task->fetch($objectid); @@ -574,7 +671,9 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $projectstatic = new Project($db); $tmps = $projectstatic->getProjectsAuthorizedForUser($user, 0, 1, 0); $tmparray = explode(',', $tmps); - if (!in_array($task->fk_project, $tmparray)) return false; + if (!in_array($task->fk_project, $tmparray)) { + return false; + } } else { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; @@ -584,7 +683,9 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand } elseif (!in_array($feature, $nocheck)) { // By default (case of $checkdefault), we check on object entity + link to third party on field $dbt_keyfield // If external user: Check permission for external users if ($user->socid > 0) { - if (empty($dbt_keyfield)) dol_print_error('', 'Param dbt_keyfield is required but not defined'); + if (empty($dbt_keyfield)) { + dol_print_error('', 'Param dbt_keyfield is required but not defined'); + } $sql = "SELECT COUNT(dbt.".$dbt_keyfield.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.rowid IN (".$objectid.")"; @@ -592,7 +693,9 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand } elseif (!empty($conf->societe->enabled) && !$user->rights->societe->client->voir) { // If internal user: Check permission for internal users that are restricted on their objects if ($feature != 'ticket') { - if (empty($dbt_keyfield)) dol_print_error('', 'Param dbt_keyfield is required but not defined'); + if (empty($dbt_keyfield)) { + dol_print_error('', 'Param dbt_keyfield is required but not defined'); + } $sql = "SELECT COUNT(sc.fk_soc) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; @@ -610,8 +713,7 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand $sql .= " AND (sc.fk_user = ".$user->id." OR sc.fk_user IS NULL)"; } } // If multicompany and internal users with all permissions, check user is in correct entity - elseif (!empty($conf->multicompany->enabled)) - { + elseif (!empty($conf->multicompany->enabled)) { $sql = "SELECT COUNT(dbt.".$dbt_select.") as nb"; $sql .= " FROM ".MAIN_DB_PREFIX.$dbtablename." as dbt"; $sql .= " WHERE dbt.".$dbt_select." IN (".$objectid.")"; @@ -619,13 +721,13 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand } } - if ($sql) - { + if ($sql) { $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if (!$obj || $obj->nb < count(explode(',', $objectid))) return false; + if (!$obj || $obj->nb < count(explode(',', $objectid))) { + return false; + } } else { return false; } @@ -649,8 +751,7 @@ function checkUserAccessToObject($user, $featuresarray, $objectid = 0, $tableand function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $showonlymessage = 0, $params = null) { global $conf, $db, $user, $langs, $hookmanager; - if (!is_object($langs)) - { + if (!is_object($langs)) { include_once DOL_DOCUMENT_ROOT.'/core/class/translate.class.php'; $langs = new Translate('', $conf); $langs->setDefaultLang(); @@ -658,21 +759,24 @@ function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $sho $langs->load("errors"); - if ($printheader) - { - if (function_exists("llxHeader")) llxHeader(''); - elseif (function_exists("llxHeaderVierge")) llxHeaderVierge(''); + if ($printheader) { + if (function_exists("llxHeader")) { + llxHeader(''); + } elseif (function_exists("llxHeaderVierge")) { + llxHeaderVierge(''); + } } print '
    '; - if (!$message) print $langs->trans("ErrorForbidden"); - else print $message; + if (!$message) { + print $langs->trans("ErrorForbidden"); + } else { + print $message; + } print '
    '; print '
    '; - if (empty($showonlymessage)) - { + if (empty($showonlymessage)) { global $action, $object; - if (empty($hookmanager)) - { + if (empty($hookmanager)) { $hookmanager = new HookManager($db); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $hookmanager->initHooks(array('main')); @@ -680,10 +784,8 @@ function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $sho $parameters = array('message'=>$message, 'params'=>$params); $reshook = $hookmanager->executeHooks('getAccessForbiddenMessage', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks print $hookmanager->resPrint; - if (empty($reshook)) - { - if ($user->login) - { + if (empty($reshook)) { + if ($user->login) { print $langs->trans("CurrentLogin").': '.$user->login.'
    '; print $langs->trans("ErrorForbidden2", $langs->transnoentitiesnoconv("Home"), $langs->transnoentitiesnoconv("Users")); } else { @@ -691,6 +793,8 @@ function accessforbidden($message = '', $printheader = 1, $printfooter = 1, $sho } } } - if ($printfooter && function_exists("llxFooter")) llxFooter(); + if ($printfooter && function_exists("llxFooter")) { + llxFooter(); + } exit(0); } diff --git a/htdocs/core/lib/security2.lib.php b/htdocs/core/lib/security2.lib.php index 3527d132cde..9181b3dd07d 100644 --- a/htdocs/core/lib/security2.lib.php +++ b/htdocs/core/lib/security2.lib.php @@ -35,8 +35,12 @@ function dol_getwebuser($mode) { $t = '?'; - if ($mode == 'user') $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty - if ($mode == 'group') $t = getenv('APACHE_RUN_GROUP'); + if ($mode == 'user') { + $t = getenv('APACHE_RUN_USER'); // $_ENV['APACHE_RUN_USER'] is empty + } + if ($mode == 'group') { + $t = getenv('APACHE_RUN_GROUP'); + } return $t; } @@ -56,44 +60,44 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth //global $dolauthmode; // To return authentication finally used // Check parameters - if ($entitytotest == '') $entitytotest = 1; + if ($entitytotest == '') { + $entitytotest = 1; + } dol_syslog("checkLoginPassEntity usertotest=".$usertotest." entitytotest=".$entitytotest." authmode=".join(',', $authmode)); $login = ''; // Validation of login/pass/entity with standard modules - if (empty($login)) - { + if (empty($login)) { $test = true; - foreach ($authmode as $mode) - { - if ($test && $mode && !$login) - { + foreach ($authmode as $mode) { + if ($test && $mode && !$login) { // Validation of login/pass/entity for mode $mode $mode = trim($mode); $authfile = 'functions_'.$mode.'.php'; $fullauthfile = ''; $dirlogin = array_merge(array("/core/login"), (array) $conf->modules_parts['login']); - foreach ($dirlogin as $reldir) - { + foreach ($dirlogin as $reldir) { $dir = dol_buildpath($reldir, 0); $newdir = dol_osencode($dir); // Check if file found (do not use dol_is_file to avoid loading files.lib.php) $tmpnewauthfile = $newdir.(preg_match('/\/$/', $newdir) ? '' : '/').$authfile; - if (is_file($tmpnewauthfile)) $fullauthfile = $tmpnewauthfile; + if (is_file($tmpnewauthfile)) { + $fullauthfile = $tmpnewauthfile; + } } $result = false; - if ($fullauthfile) $result = include_once $fullauthfile; - if ($fullauthfile && $result) - { + if ($fullauthfile) { + $result = include_once $fullauthfile; + } + if ($fullauthfile && $result) { // Call function to check user/password $function = 'check_user_password_'.$mode; $login = call_user_func($function, $usertotest, $passwordtotest, $entitytotest, $context); - if ($login && $login != '--bad-login-validity--') // Login is successfull - { + if ($login && $login != '--bad-login-validity--') { // Login is successfull $test = false; // To stop once at first login success $conf->authmode = $mode; // This properties is defined only when logged to say what mode was successfully used $dol_tz = GETPOST('tz'); @@ -117,8 +121,7 @@ function checkLoginPassEntity($usertotest, $passwordtotest, $entitytotest, $auth } -if (!function_exists('dol_loginfunction')) -{ +if (!function_exists('dol_loginfunction')) { /** * Show Dolibarr default login page. * Part of this code is also duplicated into main.inc.php::top_htmlhead @@ -147,7 +150,9 @@ if (!function_exists('dol_loginfunction')) // Title $appli = constant('DOL_APPLICATION_TITLE'); $title = $appli.' '.constant('DOL_VERSION'); - if (!empty($conf->global->MAIN_APPLICATION_TITLE)) $title = $conf->global->MAIN_APPLICATION_TITLE; + if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { + $title = $conf->global->MAIN_APPLICATION_TITLE; + } $titletruedolibarrversion = constant('DOL_VERSION'); // $title used by login template after the @ to inform of true Dolibarr version // Note: $conf->css looks like '/theme/eldy/style.css.php' @@ -169,13 +174,13 @@ if (!function_exists('dol_loginfunction')) */ // Select templates dir - if (!empty($conf->modules_parts['tpl'])) // Using this feature slow down application - { + if (!empty($conf->modules_parts['tpl'])) { // Using this feature slow down application $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl/')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $tmp = dol_buildpath($reldir.'login.tpl.php'); - if (file_exists($tmp)) { $template_dir = preg_replace('/login\.tpl\.php$/', '', $tmp); break; } + if (file_exists($tmp)) { + $template_dir = preg_replace('/login\.tpl\.php$/', '', $tmp); break; + } } } else { $template_dir = DOL_DOCUMENT_ROOT."/core/tpl/"; @@ -184,18 +189,25 @@ if (!function_exists('dol_loginfunction')) // Set cookie for timeout management $prefix = dol_getprefix(''); $sessiontimeout = 'DOLSESSTIMEOUT_'.$prefix; - if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, (empty($dolibarr_main_force_https) ? false : true), true); + if (!empty($conf->global->MAIN_SESSION_TIMEOUT)) { + setcookie($sessiontimeout, $conf->global->MAIN_SESSION_TIMEOUT, 0, "/", null, (empty($dolibarr_main_force_https) ? false : true), true); + } - if (GETPOST('urlfrom', 'alpha')) $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha'); - else unset($_SESSION["urlfrom"]); + if (GETPOST('urlfrom', 'alpha')) { + $_SESSION["urlfrom"] = GETPOST('urlfrom', 'alpha'); + } else { + unset($_SESSION["urlfrom"]); + } - if (!GETPOST("username", 'alpha')) $focus_element = 'username'; - else $focus_element = 'password'; + if (!GETPOST("username", 'alpha')) { + $focus_element = 'username'; + } else { + $focus_element = 'password'; + } $demologin = ''; $demopassword = ''; - if (!empty($dolibarr_main_demo)) - { + if (!empty($dolibarr_main_demo)) { $tab = explode(',', $dolibarr_main_demo); $demologin = $tab[0]; $demopassword = $tab[1]; @@ -233,8 +245,7 @@ if (!function_exists('dol_loginfunction')) // Security graphical code $captcha = 0; $captcha_refresh = ''; - if (function_exists("imagecreatefrompng") && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) - { + if (function_exists("imagecreatefrompng") && !empty($conf->global->MAIN_SECURITY_ENABLECAPTCHA)) { $captcha = 1; $captcha_refresh = img_picto($langs->trans("Refresh"), 'refresh', 'id="captcha_refresh_img"'); } @@ -242,23 +253,19 @@ if (!function_exists('dol_loginfunction')) // Extra link $forgetpasslink = 0; $helpcenterlink = 0; - if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) - { - if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) - { + if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK) || empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) { + if (empty($conf->global->MAIN_SECURITY_DISABLEFORGETPASSLINK)) { $forgetpasslink = 1; } - if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) - { + if (empty($conf->global->MAIN_HELPCENTER_DISABLELINK)) { $helpcenterlink = 1; } } // Home message $main_home = ''; - if (!empty($conf->global->MAIN_HOME)) - { + if (!empty($conf->global->MAIN_HOME)) { $substitutionarray = getCommonSubstitutionArray($langs); complete_substitutions_array($substitutionarray, $langs); $texttoshow = make_substitutions($conf->global->MAIN_HOME, $substitutionarray, $langs); @@ -273,11 +280,17 @@ if (!function_exists('dol_loginfunction')) $dol_loginmesg = (!empty($_SESSION["dol_loginmesg"]) ? $_SESSION["dol_loginmesg"] : ''); $favicon = DOL_URL_ROOT.'/theme/dolibarr_256x256_color.png'; - if (!empty($mysoc->logo_squarred_mini)) $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); - if (!empty($conf->global->MAIN_FAVICON_URL)) $favicon = $conf->global->MAIN_FAVICON_URL; + if (!empty($mysoc->logo_squarred_mini)) { + $favicon = DOL_URL_ROOT.'/viewimage.php?cache=1&modulepart=mycompany&file='.urlencode('logos/thumbs/'.$mysoc->logo_squarred_mini); + } + if (!empty($conf->global->MAIN_FAVICON_URL)) { + $favicon = $conf->global->MAIN_FAVICON_URL; + } $jquerytheme = 'base'; - if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME; + if (!empty($conf->global->MAIN_USE_JQUERY_THEME)) { + $jquerytheme = $conf->global->MAIN_USE_JQUERY_THEME; + } // Set dol_hide_topmenu, dol_hide_leftmenu, dol_optimize_smallscreen, dol_no_mouse_hover $dol_hide_topmenu = GETPOST('dol_hide_topmenu', 'int'); @@ -307,18 +320,22 @@ if (!function_exists('dol_loginfunction')) function makesalt($type = CRYPT_SALT_LENGTH) { dol_syslog("makesalt type=".$type); - switch ($type) - { + switch ($type) { case 12: // 8 + 4 - $saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; break; + $saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; + break; case 8: // 8 (Pour compatibilite, ne devrait pas etre utilise) - $saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; break; + $saltlen = 8; $saltprefix = '$1$'; $saltsuffix = '$'; + break; case 2: // 2 default: // by default, fall back on Standard DES (should work everywhere) - $saltlen = 2; $saltprefix = ''; $saltsuffix = ''; break; + $saltlen = 2; $saltprefix = ''; $saltsuffix = ''; + break; } $salt = ''; - while (dol_strlen($salt) < $saltlen) $salt .= chr(mt_rand(64, 126)); + while (dol_strlen($salt) < $saltlen) { + $salt .= chr(mt_rand(64, 126)); + } $result = $saltprefix.$salt.$saltsuffix; dol_syslog("makesalt return=".$result); @@ -338,33 +355,27 @@ function encodedecode_dbpassconf($level = 0) $passwd = ''; $passwd_crypted = ''; - if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php', 'r')) - { - while (!feof($fp)) - { + if ($fp = fopen(DOL_DOCUMENT_ROOT.'/conf/conf.php', 'r')) { + while (!feof($fp)) { $buffer = fgets($fp, 4096); $lineofpass = 0; - if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) // Old way to save crypted value - { + if (preg_match('/^[^#]*dolibarr_main_db_encrypted_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) { // Old way to save crypted value $val = trim($reg[1]); // This also remove CR/LF $val = preg_replace('/^["\']/', '', $val); $val = preg_replace('/["\'][\s;]*$/', '', $val); - if (!empty($val)) - { + if (!empty($val)) { $passwd_crypted = $val; $val = dol_decode($val); $passwd = $val; $lineofpass = 1; } - } elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) - { + } elseif (preg_match('/^[^#]*dolibarr_main_db_pass[\s]*=[\s]*(.*)/i', $buffer, $reg)) { $val = trim($reg[1]); // This also remove CR/LF $val = preg_replace('/^["\']/', '', $val); $val = preg_replace('/["\'][\s;]*$/', '', $val); - if (preg_match('/crypted:/i', $buffer)) - { + if (preg_match('/crypted:/i', $buffer)) { $val = preg_replace('/crypted:/i', '', $val); $passwd_crypted = $val; $val = dol_decode($val); @@ -378,15 +389,12 @@ function encodedecode_dbpassconf($level = 0) } // Output line - if ($lineofpass) - { + if ($lineofpass) { // Add value at end of file - if ($level == 0) - { + if ($level == 0) { $config .= '$dolibarr_main_db_pass=\''.$passwd.'\';'."\n"; } - if ($level == 1) - { + if ($level == 1) { $config .= '$dolibarr_main_db_pass=\'crypted:'.$passwd_crypted.'\';'."\n"; } @@ -400,8 +408,7 @@ function encodedecode_dbpassconf($level = 0) // Write new conf file $file = DOL_DOCUMENT_ROOT.'/conf/conf.php'; - if ($fp = @fopen($file, 'w')) - { + if ($fp = @fopen($file, 'w')) { fputs($fp, $config); fflush($fp); fclose($fp); @@ -436,8 +443,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len global $db, $conf, $langs, $user; $generated_password = ''; - if ($generic) - { + if ($generic) { $lowercase = "qwertyuiopasdfghjklzxcvbnm"; $uppercase = "ASDFGHJKLZXCVBNMQWERTYUIOP"; $numbers = "1234567890"; @@ -445,8 +451,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len $nbofchar = round($length / 3); $nbofcharlast = ($length - 2 * $nbofchar); //var_dump($nbofchar.'-'.$nbofcharlast); - if (function_exists('random_int')) // Cryptographic random - { + if (function_exists('random_int')) { // Cryptographic random $max = strlen($lowercase) - 1; for ($x = 0; $x < $nbofchar; $x++) { $tmp = random_int(0, $max); @@ -484,8 +489,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len $generated_password = str_shuffle($randomCode); } - } elseif (!empty($conf->global->USER_PASSWORD_GENERATED)) - { + } elseif (!empty($conf->global->USER_PASSWORD_GENERATED)) { $nomclass = "modGeneratePass".ucfirst($conf->global->USER_PASSWORD_GENERATED); $nomfichier = $nomclass.".class.php"; //print DOL_DOCUMENT_ROOT."/core/modules/security/generate/".$nomclass; @@ -496,8 +500,7 @@ function getRandomPassword($generic = false, $replaceambiguouschars = null, $len } // Do we have to discard some alphabetic characters ? - if (is_array($replaceambiguouschars) && count($replaceambiguouschars) > 0) - { + if (is_array($replaceambiguouschars) && count($replaceambiguouschars) > 0) { $numbers = "ABCDEF"; $max = strlen($numbers) - 1; if (function_exists('random_int')) { // Cryptographic random diff --git a/htdocs/core/lib/sendings.lib.php b/htdocs/core/lib/sendings.lib.php index 0bb0db6afd1..15e7286ab08 100644 --- a/htdocs/core/lib/sendings.lib.php +++ b/htdocs/core/lib/sendings.lib.php @@ -47,12 +47,10 @@ function shipping_prepare_head($object) $head[$h][2] = 'shipping'; $h++; - if ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire) - { + if ($conf->delivery_note->enabled && $user->rights->expedition->delivery->lire) { // delivery link $object->fetchObjectLinked($object->id, $object->element); - if (is_array($object->linkedObjectsIds['delivery']) && count($object->linkedObjectsIds['delivery']) > 0) // If there is a delivery - { + if (is_array($object->linkedObjectsIds['delivery']) && count($object->linkedObjectsIds['delivery']) > 0) { // If there is a delivery // Take first one element of array $tmp = reset($object->linkedObjectsIds['delivery']); @@ -63,18 +61,18 @@ function shipping_prepare_head($object) } } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $objectsrc = $object; - if ($object->origin == 'commande' && $object->origin_id > 0) - { + if ($object->origin == 'commande' && $object->origin_id > 0) { $objectsrc = new Commande($db); $objectsrc->fetch($object->origin_id); } $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT."/expedition/contact.php?id=".$object->id; $head[$h][1] = $langs->trans("ContactsAddresses"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -86,16 +84,24 @@ function shipping_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/expedition/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT."/expedition/note.php?id=".$object->id; $head[$h][1] = $langs->trans("Notes"); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; @@ -127,8 +133,7 @@ function delivery_prepare_head($object) $h = 0; $head = array(); - if ($conf->expedition_bon->enabled && $user->rights->expedition->lire) - { + if ($conf->expedition_bon->enabled && $user->rights->expedition->lire) { $head[$h][0] = DOL_URL_ROOT."/expedition/card.php?id=".$object->origin_id; $head[$h][1] = $langs->trans("SendingCard"); $head[$h][2] = 'shipping'; @@ -157,18 +162,18 @@ function delivery_prepare_head($object) $tmpobject = $object; } - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $objectsrc = $tmpobject; - if ($tmpobject->origin == 'commande' && $tmpobject->origin_id > 0) - { + if ($tmpobject->origin == 'commande' && $tmpobject->origin_id > 0) { $objectsrc = new Commande($db); $objectsrc->fetch($tmpobject->origin_id); } $nbContact = count($objectsrc->liste_contact(-1, 'internal')) + count($objectsrc->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT."/expedition/contact.php?id=".$tmpobject->id; $head[$h][1] = $langs->trans("ContactsAddresses"); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -180,16 +185,24 @@ function delivery_prepare_head($object) $nbLinks = Link::count($db, $tmpobject->element, $tmpobject->id); $head[$h][0] = DOL_URL_ROOT.'/expedition/document.php?id='.$tmpobject->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; $nbNote = 0; - if (!empty($tmpobject->note_private)) $nbNote++; - if (!empty($tmpobject->note_public)) $nbNote++; + if (!empty($tmpobject->note_private)) { + $nbNote++; + } + if (!empty($tmpobject->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT."/expedition/note.php?id=".$tmpobject->id; $head[$h][1] = $langs->trans("Notes"); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; @@ -236,21 +249,24 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') $sql .= " AND obj.fk_".$origin." = ".$origin_id; $sql .= " AND obj.rowid = ed.fk_origin_line"; $sql .= " AND ed.fk_expedition = e.rowid"; - if ($filter) $sql .= $filter; + if ($filter) { + $sql .= $filter; + } $sql .= " ORDER BY obj.fk_product"; dol_syslog("show_list_sending_receive", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { - if ($filter) print load_fiche_titre($langs->trans("OtherSendingsForSameOrder")); - else print load_fiche_titre($langs->trans("SendingsAndReceivingForSameOrder")); + if ($num) { + if ($filter) { + print load_fiche_titre($langs->trans("OtherSendingsForSameOrder")); + } else { + print load_fiche_titre($langs->trans("SendingsAndReceivingForSameOrder")); + } print ''; print ''; @@ -260,26 +276,23 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') print ''; print ''; print ''; - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print ''; } /*TODO Add link to expeditiondet_batch if (! empty($conf->productbatch->enabled)) { - print ''; + print ''; }*/ - if (!empty($conf->delivery_note->enabled)) - { + if (!empty($conf->delivery_note->enabled)) { print ''; //print ''; print ''; } print "\n"; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); print ''; @@ -290,11 +303,9 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') print ''; // Description - if ($objp->fk_product > 0) - { + if ($objp->fk_product > 0) { // Define output language - if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) - { + if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $object = new $origin($db); $object->fetch($origin_id); $object->fetch_thirdparty(); @@ -305,10 +316,13 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && !empty($_REQUEST['lang_id'])) $newlang = $_REQUEST['lang_id']; - if (empty($newlang)) $newlang = $object->thirdparty->default_lang; - if (!empty($newlang)) - { + if (empty($newlang) && !empty($_REQUEST['lang_id'])) { + $newlang = $_REQUEST['lang_id']; + } + if (empty($newlang)) { + $newlang = $object->thirdparty->default_lang; + } + if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); } @@ -334,16 +348,18 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') print_date_range($objp->date_start, $objp->date_end); // Add description in form - if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if (!empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($objp->description) && $objp->description != $objp->product) ? '
    '.dol_htmlentitiesbr($objp->description) : ''; } print ''; } else { print "'; // Warehouse - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { print ''; - } else { - print ''; - } + } + print $form->textwithtooltip(img_picto('', 'object_barcode').' '.$langs->trans("DetailBatchNumber"),$detail); + } + else + { + print $langs->trans("NA"); + } + print ''; + } else { + print ''; + } }*/ // Informations on receipt - if (!empty($conf->delivery_note->enabled)) - { + if (!empty($conf->delivery_note->enabled)) { include_once DOL_DOCUMENT_ROOT.'/delivery/class/delivery.class.php'; $expedition->id = $objp->sendingid; $expedition->fetchObjectLinked($expedition->id, $expedition->element); //var_dump($expedition->linkedObjects); $receiving = ''; - if (!empty($expedition->linkedObjects['delivery'])) $receiving = reset($expedition->linkedObjects['delivery']); // Take first link + if (!empty($expedition->linkedObjects['delivery'])) { + $receiving = reset($expedition->linkedObjects['delivery']); // Take first link + } - if (!empty($receiving)) - { + if (!empty($receiving)) { // $expedition->fk_origin_line = id of det line of order // $receiving->fk_origin_line = id of det line of order // $receiving->origin may be 'shipping' diff --git a/htdocs/core/lib/signature.lib.php b/htdocs/core/lib/signature.lib.php index 14ca70926d3..8b49b01ae35 100644 --- a/htdocs/core/lib/signature.lib.php +++ b/htdocs/core/lib/signature.lib.php @@ -56,18 +56,24 @@ function getOnlineSignatureUrl($mode, $type, $ref = '') $ref = str_replace(' ', '', $ref); $out = ''; - if ($type == 'proposal') - { + if ($type == 'proposal') { $out = DOL_MAIN_URL_ROOT.'/public/onlinesign/newonlinesign.php?source=proposal&ref='.($mode ? '' : ''); - if ($mode == 1) $out .= 'proposal_ref'; - if ($mode == 0) $out .= urlencode($ref); + if ($mode == 1) { + $out .= 'proposal_ref'; + } + if ($mode == 0) { + $out .= urlencode($ref); + } $out .= ($mode ? '' : ''); - if ($mode == 1) $out .= '&hashp=hash_of_file'; - else { + if ($mode == 1) { + $out .= '&hashp=hash_of_file'; + } else { include_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php'; $propaltmp = new Propal($db); $res = $propaltmp->fetch(0, $ref); - if ($res <= 0) return 'FailedToGetProposal'; + if ($res <= 0) { + return 'FailedToGetProposal'; + } include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile = new EcmFiles($db); @@ -75,8 +81,7 @@ function getOnlineSignatureUrl($mode, $type, $ref = '') $ecmfile->fetch(0, '', $propaltmp->last_main_doc); $hashp = $ecmfile->share; - if (empty($hashp)) - { + if (empty($hashp)) { $out = $langs->trans("FeatureOnlineSignDisabled"); return $out; } else { @@ -86,7 +91,9 @@ function getOnlineSignatureUrl($mode, $type, $ref = '') } // For multicompany - if (!empty($out)) $out .= "&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities + if (!empty($out)) { + $out .= "&entity=".$conf->entity; // Check the entity because He may be the same reference in several entities + } return $out; } diff --git a/htdocs/core/lib/stock.lib.php b/htdocs/core/lib/stock.lib.php index 2d6768010fb..2e58e6c8082 100644 --- a/htdocs/core/lib/stock.lib.php +++ b/htdocs/core/lib/stock.lib.php @@ -39,8 +39,7 @@ function stock_prepare_head($object) $head[$h][2] = 'card'; $h++; - if (!empty($user->rights->stock->mouvement->lire)) - { + if (!empty($user->rights->stock->mouvement->lire)) { $head[$h][0] = DOL_URL_ROOT.'/product/stock/movement_list.php?id='.$object->id; $head[$h][1] = $langs->trans("StockMovements"); $head[$h][2] = 'movements'; diff --git a/htdocs/core/lib/supplier_proposal.lib.php b/htdocs/core/lib/supplier_proposal.lib.php index ec782350c9d..a7720bd9ef4 100644 --- a/htdocs/core/lib/supplier_proposal.lib.php +++ b/htdocs/core/lib/supplier_proposal.lib.php @@ -44,12 +44,13 @@ function supplier_proposal_prepare_head($object) $head[$h][2] = 'comm'; $h++; - if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/contact.php?id='.$object->id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -60,14 +61,19 @@ function supplier_proposal_prepare_head($object) // $this->tabs = array('entity:-tabname); to remove a tab complete_head_from_modules($conf, $langs, $object, $head, $h, 'supplier_proposal'); - if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $nbNote = 0; - if (!empty($object->note_private)) $nbNote++; - if (!empty($object->note_public)) $nbNote++; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/note.php?id='.$object->id; $head[$h][1] = $langs->trans('Notes'); - if ($nbNote > 0) $head[$h][1] .= ''.$nbNote.''; + if ($nbNote > 0) { + $head[$h][1] .= ''.$nbNote.''; + } $head[$h][2] = 'note'; $h++; } @@ -79,7 +85,9 @@ function supplier_proposal_prepare_head($object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/supplier_proposal/document.php?id='.$object->id; $head[$h][1] = $langs->trans('Documents'); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'document'; $h++; diff --git a/htdocs/core/lib/takepos.lib.php b/htdocs/core/lib/takepos.lib.php index dfddc95d733..db1623387c1 100644 --- a/htdocs/core/lib/takepos.lib.php +++ b/htdocs/core/lib/takepos.lib.php @@ -54,8 +54,7 @@ function takepos_admin_prepare_head() $h++; $numterminals = max(1, $conf->global->TAKEPOS_NUM_TERMINALS); - for ($i = 1; $i <= $numterminals; $i++) - { + for ($i = 1; $i <= $numterminals; $i++) { $head[$h][0] = DOL_URL_ROOT.'/takepos/admin/terminal.php?terminal='.$i; $head[$h][1] = $langs->trans("Terminal")." ".$i; $head[$h][2] = 'terminal'.$i; diff --git a/htdocs/core/lib/tax.lib.php b/htdocs/core/lib/tax.lib.php index 36ce55f7c85..e2257369865 100644 --- a/htdocs/core/lib/tax.lib.php +++ b/htdocs/core/lib/tax.lib.php @@ -59,7 +59,9 @@ function tax_prepare_head(ChargeSociales $object) $nbLinks = Link::count($db, $object->element, $object->id); $head[$h][0] = DOL_URL_ROOT.'/compta/sociales/document.php?id='.$object->id; $head[$h][1] = $langs->trans("Documents"); - if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } $head[$h][2] = 'documents'; $h++; @@ -93,14 +95,12 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di global $conf; // If we use date_start and date_end, we must not use $y, $m, $q - if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) - { + if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) { dol_print_error('', 'Bad value of input parameter for tax_by_rate'); } $list = array(); - if ($direction == 'sell') - { + if ($direction == 'sell') { $invoicetable = 'facture'; $invoicedettable = 'facturedet'; $fk_facture = 'fk_facture'; @@ -110,8 +110,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $paymenttable = 'paiement'; $paymentfacturetable = 'paiement_facture'; $invoicefieldref = 'ref'; - } elseif ($direction == 'buy') - { + } elseif ($direction == 'buy') { $invoicetable = 'facture_fourn'; $invoicedettable = 'facture_fourn_det'; $fk_facture = 'fk_facture_fourn'; @@ -138,8 +137,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di // Define sql request $sql = ''; if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) - { + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) { // Count on delivery date (use invoice date as delivery is unknown) $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; @@ -153,24 +151,31 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -189,49 +194,64 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; $sql .= " AND pf.".$fk_facture2." = f.rowid"; $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } - if (!$sql) return -1; - if ($sql == 'TODO') return -2; - if ($sql != 'TODO') - { + if (!$sql) { + return -1; + } + if ($sql == 'TODO') { + return -2; + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_thirdparty", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $company_id = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; - if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; - if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; - if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; + while ($assoc = $db->fetch_array($resql)) { + if (!isset($list[$assoc['company_id']]['totalht'])) { + $list[$assoc['company_id']]['totalht'] = 0; + } + if (!isset($list[$assoc['company_id']]['vat'])) { + $list[$assoc['company_id']]['vat'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax1'])) { + $list[$assoc['company_id']]['localtax1'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax2'])) { + $list[$assoc['company_id']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; @@ -280,8 +300,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di // Define sql request $sql = ''; if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) - { + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { // Count on invoice date $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; @@ -295,24 +314,31 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -331,52 +357,64 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; $sql .= " AND pf.".$fk_facture2." = f.rowid"; $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } - if (!$sql) - { + if (!$sql) { dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); return -1; // -1 = Not accountancy module enabled } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { + if ($sql == 'TODO') { + return -2; // -2 = Feature not yet available + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $company_id = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; - if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; - if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; - if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; + while ($assoc = $db->fetch_array($resql)) { + if (!isset($list[$assoc['company_id']]['totalht'])) { + $list[$assoc['company_id']]['totalht'] = 0; + } + if (!isset($list[$assoc['company_id']]['vat'])) { + $list[$assoc['company_id']]['vat'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax1'])) { + $list[$assoc['company_id']]['localtax1'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax2'])) { + $list[$assoc['company_id']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; @@ -422,8 +460,7 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di // CASE OF EXPENSE REPORT - if ($direction == 'buy') // buy only for expense reports - { + if ($direction == 'buy') { // buy only for expense reports // Define sql request $sql = ''; @@ -438,45 +475,54 @@ function tax_by_thirdparty($type, $db, $y, $date_start, $date_end, $modetax, $di $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_expensereport as p ON p.fk_expensereport = e.rowid "; $sql .= " WHERE e.entity = ".$conf->entity; $sql .= " AND e.fk_statut in (6)"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = -1"; $sql .= " OR e.date_debut is NOT null OR e.date_fin IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + } $sql .= " ORDER BY e.rowid"; - if (!$sql) - { + if (!$sql) { dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); return -1; // -1 = Not accountancy module enabled } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { + if ($sql == 'TODO') { + return -2; // -2 = Feature not yet available + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $company_id = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { - if (!isset($list[$assoc['company_id']]['totalht'])) $list[$assoc['company_id']]['totalht'] = 0; - if (!isset($list[$assoc['company_id']]['vat'])) $list[$assoc['company_id']]['vat'] = 0; - if (!isset($list[$assoc['company_id']]['localtax1'])) $list[$assoc['company_id']]['localtax1'] = 0; - if (!isset($list[$assoc['company_id']]['localtax2'])) $list[$assoc['company_id']]['localtax2'] = 0; + while ($assoc = $db->fetch_array($resql)) { + if (!isset($list[$assoc['company_id']]['totalht'])) { + $list[$assoc['company_id']]['totalht'] = 0; + } + if (!isset($list[$assoc['company_id']]['vat'])) { + $list[$assoc['company_id']]['vat'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax1'])) { + $list[$assoc['company_id']]['localtax1'] = 0; + } + if (!isset($list[$assoc['company_id']]['localtax2'])) { + $list[$assoc['company_id']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['company_id']]['totalht'] += $assoc['total_ht']; $list[$assoc['company_id']]['vat'] += $assoc['total_vat']; @@ -545,15 +591,13 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire global $conf; // If we use date_start and date_end, we must not use $y, $m, $q - if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) - { + if (($date_start || $date_end) && (!empty($y) || !empty($m) || !empty($q))) { dol_print_error('', 'Bad value of input parameter for tax_by_rate'); } $list = array(); - if ($direction == 'sell') - { + if ($direction == 'sell') { $invoicetable = 'facture'; $invoicedettable = 'facturedet'; $fk_facture = 'fk_facture'; @@ -590,8 +634,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire // Define sql request $sql = ''; if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_PRODUCT == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) - { + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_PRODUCT == 'invoice')) { // Count on delivery date (use invoice date as delivery is unknown) $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; @@ -605,24 +648,31 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -641,50 +691,65 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; $sql .= " AND pf.".$fk_facture2." = f.rowid"; $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 0"; // Limit to products $sql .= " AND d.date_start is null AND d.date_end IS NULL)"; // enhance detection of products - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } - if (!$sql) return -1; - if ($sql == 'TODO') return -2; - if ($sql != 'TODO') - { + if (!$sql) { + return -1; + } + if ($sql == 'TODO') { + return -2; + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $rate = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { + while ($assoc = $db->fetch_array($resql)) { // Code to avoid warnings when array entry not defined - if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; - if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; - if (!isset($list[$assoc['rate']]['localtax1'])) $list[$assoc['rate']]['localtax1'] = 0; - if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; + if (!isset($list[$assoc['rate']]['totalht'])) { + $list[$assoc['rate']]['totalht'] = 0; + } + if (!isset($list[$assoc['rate']]['vat'])) { + $list[$assoc['rate']]['vat'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax1'])) { + $list[$assoc['rate']]['localtax1'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax2'])) { + $list[$assoc['rate']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; $list[$assoc['rate']]['vat'] += $assoc['total_vat']; @@ -732,8 +797,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire // Define sql request $sql = ''; if (($direction == 'sell' && $conf->global->TAX_MODE_SELL_SERVICE == 'invoice') - || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) - { + || ($direction == 'buy' && $conf->global->TAX_MODE_BUY_SERVICE == 'invoice')) { // Count on invoice date $sql = "SELECT d.rowid, d.product_type as dtype, d.".$fk_facture." as facid, d.$f_rate as rate, d.total_ht as total_ht, d.total_ttc as total_ttc, d.".$total_tva." as total_vat, d.description as descr,"; $sql .= " d.".$total_localtax1." as total_localtax1, d.".$total_localtax2." as total_localtax2, "; @@ -747,24 +811,31 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Validated or paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND f.datef >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND f.datef <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(f.datef,'%m') > ".(($q - 1) * 3)." AND date_format(f.datef,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND f.datef >= '".$db->idate($date_start)."' AND f.datef <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture; } else { // Count on payments date @@ -783,53 +854,65 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p on d.fk_product = p.rowid"; $sql .= " WHERE f.entity IN (".getEntity($invoicetable).")"; $sql .= " AND f.fk_statut in (1,2)"; // Paid (partially or completely) - if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) $sql .= " AND f.type IN (0,1,2,5)"; - else $sql .= " AND f.type IN (0,1,2,3,5)"; + if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) { + $sql .= " AND f.type IN (0,1,2,5)"; + } else { + $sql .= " AND f.type IN (0,1,2,3,5)"; + } $sql .= " AND f.rowid = d.".$fk_facture; $sql .= " AND s.rowid = f.fk_soc"; $sql .= " AND pf.".$fk_facture2." = f.rowid"; $sql .= " AND pa.rowid = pf.".$fk_payment; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND pa.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND pa.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(pa.datep,'%m') > ".(($q - 1) * 3)." AND date_format(pa.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND pa.datep >= '".$db->idate($date_start)."' AND pa.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = 1"; // Limit to services $sql .= " OR d.date_start is NOT null OR d.date_end IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.".$total_tva." <> 0)"; + } $sql .= " ORDER BY d.rowid, d.".$fk_facture.", pf.rowid"; } - if (!$sql) - { + if (!$sql) { dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); return -1; // -1 = Not accountancy module enabled } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { + if ($sql == 'TODO') { + return -2; // -2 = Feature not yet available + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $rate = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { + while ($assoc = $db->fetch_array($resql)) { // Code to avoid warnings when array entry not defined - if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; - if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; - if (!isset($list[$assoc['rate']]['localtax1'])) $list[$assoc['rate']]['localtax1'] = 0; - if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; + if (!isset($list[$assoc['rate']]['totalht'])) { + $list[$assoc['rate']]['totalht'] = 0; + } + if (!isset($list[$assoc['rate']]['vat'])) { + $list[$assoc['rate']]['vat'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax1'])) { + $list[$assoc['rate']]['localtax1'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax2'])) { + $list[$assoc['rate']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; $list[$assoc['rate']]['vat'] += $assoc['total_vat']; @@ -874,8 +957,7 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire // CASE OF EXPENSE REPORT - if ($direction == 'buy') // buy only for expense reports - { + if ($direction == 'buy') { // buy only for expense reports // Define sql request $sql = ''; @@ -890,46 +972,55 @@ function tax_by_rate($type, $db, $y, $q, $date_start, $date_end, $modetax, $dire $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_expensereport as p ON p.fk_expensereport = e.rowid "; $sql .= " WHERE e.entity = ".$conf->entity; $sql .= " AND e.fk_statut in (6)"; - if ($y && $m) - { + if ($y && $m) { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, $m, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, $m, false))."'"; - } elseif ($y) - { + } elseif ($y) { $sql .= " AND p.datep >= '".$db->idate(dol_get_first_day($y, 1, false))."'"; $sql .= " AND p.datep <= '".$db->idate(dol_get_last_day($y, 12, false))."'"; } - if ($q) $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; - if ($date_start && $date_end) $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + if ($q) { + $sql .= " AND (date_format(p.datep,'%m') > ".(($q - 1) * 3)." AND date_format(p.datep,'%m') <= ".($q * 3).")"; + } + if ($date_start && $date_end) { + $sql .= " AND p.datep >= '".$db->idate($date_start)."' AND p.datep <= '".$db->idate($date_end)."'"; + } $sql .= " AND (d.product_type = -1"; $sql .= " OR e.date_debut is NOT null OR e.date_fin IS NOT NULL)"; // enhance detection of service - if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + if (!empty($conf->global->MAIN_NOT_INCLUDE_ZERO_VAT_IN_REPORTS)) { + $sql .= " AND (d.".$f_rate." <> 0 OR d.total_tva <> 0)"; + } $sql .= " ORDER BY e.rowid"; - if (!$sql) - { + if (!$sql) { dol_syslog("Tax.lib.php::tax_by_rate no accountancy module enabled".$sql, LOG_ERR); return -1; // -1 = Not accountancy module enabled } - if ($sql == 'TODO') return -2; // -2 = Feature not yet available - if ($sql != 'TODO') - { + if ($sql == 'TODO') { + return -2; // -2 = Feature not yet available + } + if ($sql != 'TODO') { dol_syslog("Tax.lib.php::tax_by_rate", LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $rate = -1; $oldrowid = ''; - while ($assoc = $db->fetch_array($resql)) - { + while ($assoc = $db->fetch_array($resql)) { // Code to avoid warnings when array entry not defined - if (!isset($list[$assoc['rate']]['totalht'])) $list[$assoc['rate']]['totalht'] = 0; - if (!isset($list[$assoc['rate']]['vat'])) $list[$assoc['rate']]['vat'] = 0; - if (!isset($list[$assoc['rate']]['localtax1'])) $list[$assoc['rate']]['localtax1'] = 0; - if (!isset($list[$assoc['rate']]['localtax2'])) $list[$assoc['rate']]['localtax2'] = 0; + if (!isset($list[$assoc['rate']]['totalht'])) { + $list[$assoc['rate']]['totalht'] = 0; + } + if (!isset($list[$assoc['rate']]['vat'])) { + $list[$assoc['rate']]['vat'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax1'])) { + $list[$assoc['rate']]['localtax1'] = 0; + } + if (!isset($list[$assoc['rate']]['localtax2'])) { + $list[$assoc['rate']]['localtax2'] = 0; + } - if ($assoc['rowid'] != $oldrowid) // Si rupture sur d.rowid - { + if ($assoc['rowid'] != $oldrowid) { // Si rupture sur d.rowid $oldrowid = $assoc['rowid']; $list[$assoc['rate']]['totalht'] += $assoc['total_ht']; $list[$assoc['rate']]['vat'] += $assoc['total_vat']; diff --git a/htdocs/core/lib/ticket.lib.php b/htdocs/core/lib/ticket.lib.php index c90892d603c..c7f3e0612ce 100644 --- a/htdocs/core/lib/ticket.lib.php +++ b/htdocs/core/lib/ticket.lib.php @@ -88,7 +88,9 @@ function ticket_prepare_head($object) $nbContact = count($object->liste_contact(-1, 'internal')) + count($object->liste_contact(-1, 'external')); $head[$h][0] = DOL_URL_ROOT.'/ticket/contact.php?track_id='.$object->track_id; $head[$h][1] = $langs->trans('ContactsAddresses'); - if ($nbContact > 0) $head[$h][1] .= ''.$nbContact.''; + if ($nbContact > 0) { + $head[$h][1] .= ''.$nbContact.''; + } $head[$h][2] = 'contact'; $h++; } @@ -124,8 +126,7 @@ function ticket_prepare_head($object) $head[$h][0] = DOL_URL_ROOT.'/ticket/agenda.php?track_id='.$object->track_id; } $head[$h][1] = $langs->trans('Events'); - if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) - { + if (!empty($conf->agenda->enabled) && (!empty($user->rights->agenda->myactions->read) || !empty($user->rights->agenda->allactions->read))) { $head[$h][1] .= '/'; $head[$h][1] .= $langs->trans("Agenda"); } @@ -150,8 +151,7 @@ function showDirectPublicLink($object) require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php'; $email = CMailFile::getValidAddress($object->origin_email, 2); $url = ''; - if ($email) - { + if ($email) { $url = dol_buildpath('/public/ticket/view.php', 3).'?track_id='.$object->track_id.'&email='.$email; } @@ -278,7 +278,9 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no dol_include_once('/comm/action/class/actioncomm.class.php'); // Check parameters - if (!is_object($filterobj) && !is_object($objcon)) dol_print_error('', 'BadParameter'); + if (!is_object($filterobj) && !is_object($objcon)) { + dol_print_error('', 'BadParameter'); + } $out = ''; $histo = array(); @@ -294,8 +296,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no } $sortfield_new = implode(',', $sortfield_new_list); - if (!empty($conf->agenda->enabled)) - { + if (!empty($conf->agenda->enabled)) { // Recherche histo sur actioncomm if (is_object($objcon) && $objcon->id > 0) { $sql = "SELECT DISTINCT a.id, a.label as label,"; @@ -365,22 +366,34 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $sql .= " AND a.fk_project = ".$filterobj->id; } elseif (is_object($filterobj) && get_class($filterobj) == 'Adherent') { $sql .= " AND a.fk_element = m.rowid AND a.elementtype = 'member'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'CommandeFournisseur') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'order_supplier'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'Product') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'product'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'Ticket') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'ticket'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'BOM') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'bom'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } elseif (is_object($filterobj) && get_class($filterobj) == 'Contrat') { $sql .= " AND a.fk_element = o.rowid AND a.elementtype = 'contract'"; - if ($filterobj->id) $sql .= " AND a.fk_element = ".$filterobj->id; + if ($filterobj->id) { + $sql .= " AND a.fk_element = ".$filterobj->id; + } } } @@ -399,20 +412,28 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no } } } else { - if ($actioncode == 'AC_NON_AUTO') $sql .= " AND c.type != 'systemauto'"; - elseif ($actioncode == 'AC_ALL_AUTO') $sql .= " AND c.type = 'systemauto'"; - else $sql .= " AND c.code = '".$db->escape($actioncode)."'"; + if ($actioncode == 'AC_NON_AUTO') { + $sql .= " AND c.type != 'systemauto'"; + } elseif ($actioncode == 'AC_ALL_AUTO') { + $sql .= " AND c.type = 'systemauto'"; + } else { + $sql .= " AND c.code = '".$db->escape($actioncode)."'"; + } } } - if ($donetodo == 'todo') $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; - elseif ($donetodo == 'done') $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; - if (is_array($filters) && $filters['search_agenda_label']) $sql .= natural_search('a.label', $filters['search_agenda_label']); + if ($donetodo == 'todo') { + $sql .= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; + } elseif ($donetodo == 'done') { + $sql .= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; + } + if (is_array($filters) && $filters['search_agenda_label']) { + $sql .= natural_search('a.label', $filters['search_agenda_label']); + } } // Add also event from emailings. TODO This should be replaced by an automatic event ? May be it's too much for very large emailing. if (!empty($conf->mailing->enabled) && !empty($objcon->email) - && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) - { + && (empty($actioncode) || $actioncode == 'AC_OTH_AUTO' || $actioncode == 'AC_EMAILING')) { $langs->load("mails"); $sql2 = "SELECT m.rowid as id, m.titre as label, mc.date_envoi as dp, mc.date_envoi as dp2, '100' as percent, 'mailing' as type"; @@ -467,7 +488,9 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no //if ($donetodo == 'todo') $sql.= " AND ((a.percent >= 0 AND a.percent < 100) OR (a.percent = -1 AND a.datep > '".$db->idate($now)."'))"; //elseif ($donetodo == 'done') $sql.= " AND (a.percent = 100 OR (a.percent = -1 AND a.datep <= '".$db->idate($now)."'))"; $tododone = ''; - if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) $tododone = 'todo'; + if (($obj->percent >= 0 and $obj->percent < 100) || ($obj->percent == -1 && $obj->datep > $now)) { + $tododone = 'todo'; + } $histo[$numaction] = array( 'type'=>$obj->type, @@ -549,7 +572,9 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no } else { $out .= ''; } - if ($filterobj && get_class($filterobj) == 'Societe') $out .= ''; + if ($filterobj && get_class($filterobj) == 'Societe') { + $out .= ''; + } $out .= "\n"; @@ -591,12 +616,16 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no if ($donetodo) { $tmp = ''; - if (get_class($filterobj) == 'Societe') $tmp .= ''; + if (get_class($filterobj) == 'Societe') { + $tmp .= ''; + } $tmp .= ($donetodo != 'done' ? $langs->trans("ActionsToDoShort") : ''); $tmp .= ($donetodo != 'done' && $donetodo != 'todo' ? ' / ' : ''); $tmp .= ($donetodo != 'todo' ? $langs->trans("ActionsDoneShort") : ''); //$out.=$langs->trans("ActionsToDoShort").' / '.$langs->trans("ActionsDoneShort"); - if (get_class($filterobj) == 'Societe') $tmp .= ''; + if (get_class($filterobj) == 'Societe') { + $tmp .= ''; + } $out .= getTitleFieldOfList($tmp); } @@ -607,8 +636,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $actualCycleDate = false; - foreach ($histo as $key=>$value) - { + foreach ($histo as $key => $value) { $actionstatic->fetch($histo[$key]['id']); // TODO Do we need this, we already have a lot of data of line into $histo $actionstatic->type_picto = $histo[$key]['apicto']; @@ -652,8 +680,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no //} if ($user->rights->agenda->allactions->create || - (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->rights->agenda->myactions->create)) - { + (($actionstatic->authorid == $user->id || $actionstatic->userownerid == $user->id) && $user->rights->agenda->myactions->create)) { $out .= ''; } @@ -671,11 +698,21 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no } } $late = 0; - if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; - if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; - if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) $late = 1; - if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) $late = 1; - if ($late) $out .= img_warning($langs->trans("Late")).' '; + if ($histo[$key]['percent'] == 0 && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) { + $late = 1; + } + if ($histo[$key]['percent'] == 0 && !$histo[$key]['datestart'] && $histo[$key]['dateend'] && $histo[$key]['datestart'] < ($now - $delay_warning)) { + $late = 1; + } + if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && $histo[$key]['dateend'] && $histo[$key]['dateend'] < ($now - $delay_warning)) { + $late = 1; + } + if ($histo[$key]['percent'] > 0 && $histo[$key]['percent'] < 100 && !$histo[$key]['dateend'] && $histo[$key]['datestart'] && $histo[$key]['datestart'] < ($now - $delay_warning)) { + $late = 1; + } + if ($late) { + $out .= img_warning($langs->trans("Late")).' '; + } $out .= "\n"; // Ref @@ -683,8 +720,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no // Author of event $out .= ''; - if ($histo[$key]['userid'] > 0) - { + if ($histo[$key]['userid'] > 0) { if (!isset($userGetNomUrlCache[$histo[$key]['userid']])) { // is in cache ? $userstatic->fetch($histo[$key]['userid']); $userGetNomUrlCache[$histo[$key]['userid']] = $userstatic->getNomUrl(-1, '', 0, 0, 16, 0, 'firstelselast', ''); @@ -723,8 +759,7 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no if (!empty($histo[$key]['message']) && $actionstatic->code != 'AC_TICKET_CREATE' && $actionstatic->code != 'AC_TICKET_MODIFY' - ) - { + ) { $out .= '
    '; $out .= $histo[$key]['message']; $out .= '
    '; @@ -748,8 +783,9 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $contactList .= !empty($contactList) ? ', ' : ''; $contactList .= $contact->getNomUrl(1); if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') { - if (!empty($contact->phone_pro)) + if (!empty($contact->phone_pro)) { $contactList .= '('.dol_print_phone($contact->phone_pro).')'; + } } } } @@ -759,24 +795,24 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $contact = new Contact($db); $result = $contact->fetch($histo[$key]['contact_id']); - if ($result < 0) + if ($result < 0) { dol_print_error($db, $contact->error); + } if ($result > 0) { $footer .= $contact->getNomUrl(1); if (isset($histo[$key]['acode']) && $histo[$key]['acode'] == 'AC_TEL') { - if (!empty($contact->phone_pro)) + if (!empty($contact->phone_pro)) { $footer .= '('.dol_print_phone($contact->phone_pro).')'; + } } } } $documents = getTicketActionCommEcmList($actionstatic); - if (!empty($documents)) - { + if (!empty($documents)) { $footer .= '
    '; - foreach ($documents as $doc) - { + foreach ($documents as $doc) { $footer .= 'id.'" '; $footer .= ' data-path="'.$doc->filepath.'"'; @@ -819,8 +855,11 @@ function show_ticket_messaging($conf, $langs, $db, $filterobj, $objcon = '', $no $out .= "\n"; } - if ($noprint) return $out; - else print $out; + if ($noprint) { + return $out; + } else { + print $out; + } } /** diff --git a/htdocs/core/lib/treeview.lib.php b/htdocs/core/lib/treeview.lib.php index 9df0f8d9ddf..a20170e3a95 100644 --- a/htdocs/core/lib/treeview.lib.php +++ b/htdocs/core/lib/treeview.lib.php @@ -38,8 +38,7 @@ function tree_showpad(&$fulltree, $key, $silent = 0) $pos = 1; // Loop on each pos, because we will output an img for each pos - while ($pos <= $fulltree[$key]['level'] && $fulltree[$key]['level'] > 0) - { + while ($pos <= $fulltree[$key]['level'] && $fulltree[$key]['level'] > 0) { // Process for column $pos $atleastoneofthislevelafter = 0; @@ -47,41 +46,41 @@ function tree_showpad(&$fulltree, $key, $silent = 0) $nbofdocinsub = 0; $found = 0; //print 'x'.$key; - foreach ($fulltree as $key2 => $val2) - { + foreach ($fulltree as $key2 => $val2) { //print "x".$pos." ".$key2." ".$found." ".$fulltree[$key2]['level']; - if ($found == 1) // We are after the entry to show - { - if ($fulltree[$key2]['level'] > $pos) - { + if ($found == 1) { // We are after the entry to show + if ($fulltree[$key2]['level'] > $pos) { $nbofdirinsub++; - if (isset($fulltree[$key2]['cachenbofdoc']) && $fulltree[$key2]['cachenbofdoc'] > 0) $nbofdocinsub += $fulltree[$key2]['cachenbofdoc']; + if (isset($fulltree[$key2]['cachenbofdoc']) && $fulltree[$key2]['cachenbofdoc'] > 0) { + $nbofdocinsub += $fulltree[$key2]['cachenbofdoc']; + } } - if ($fulltree[$key2]['level'] == $pos) - { + if ($fulltree[$key2]['level'] == $pos) { $atleastoneofthislevelafter = 1; } - if ($fulltree[$key2]['level'] <= $pos) - { + if ($fulltree[$key2]['level'] <= $pos) { break; } } - if ($key2 == $key) // We found ourself, so now every lower level will be counted - { + if ($key2 == $key) { // We found ourself, so now every lower level will be counted $found = 1; } } //print $atleastoneofthislevelafter; - if (!$silent) - { - if ($atleastoneofthislevelafter) - { - if ($fulltree[$key]['level'] == $pos) print img_picto_common('', 'treemenu/branch.gif'); - else print img_picto_common('', 'treemenu/line.gif'); + if (!$silent) { + if ($atleastoneofthislevelafter) { + if ($fulltree[$key]['level'] == $pos) { + print img_picto_common('', 'treemenu/branch.gif'); + } else { + print img_picto_common('', 'treemenu/line.gif'); + } } else { - if ($fulltree[$key]['level'] == $pos) print img_picto_common('', 'treemenu/branchbottom.gif'); - else print img_picto_common('', 'treemenu/linebottom.gif'); + if ($fulltree[$key]['level'] == $pos) { + print img_picto_common('', 'treemenu/branchbottom.gif'); + } else { + print img_picto_common('', 'treemenu/linebottom.gif'); + } } } $pos++; @@ -116,10 +115,11 @@ function tree_recur($tab, $pere, $rang, $iddivjstree = 'iddivjstree', $donoreset { global $tree_recur_alreadyadded, $menu_handler_to_search; - if ($rang == 0 && empty($donoresetalreadyloaded)) $tree_recur_alreadyadded = array(); + if ($rang == 0 && empty($donoresetalreadyloaded)) { + $tree_recur_alreadyadded = array(); + } - if ($rang == 0) - { + if ($rang == 0) { // Test also done with jstree and dynatree (not able to have inside label) print ''."\n"; - } elseif ($type == 'organization') - { + } elseif ($type == 'organization') { $companyname = $mysoc->name; $url = $mysoc->url; @@ -603,16 +596,16 @@ function getStructuredData($type, $data = array()) $ret .= '"https://www.'.$key.'.com/'.dol_escape_json($value).'"'; } $i++; - if ($i < count($mysoc->socialnetworks)) $ret .= ', '; + if ($i < count($mysoc->socialnetworks)) { + $ret .= ', '; + } } $ret .= ']'."\n"; } $ret .= '}'."\n"; $ret .= ''."\n"; - } elseif ($type == 'blogpost') - { - if (!empty($websitepage->author_alias)) - { + } elseif ($type == 'blogpost') { + if (!empty($websitepage->author_alias)) { //include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; //$tmpuser = new User($db); //$restmpuser = $tmpuser->fetch($websitepage->fk_user_creat); @@ -664,7 +657,9 @@ function getStructuredData($type, $data = array()) foreach ($arrayofkeywords as $keyword) { $ret .= '"'.dol_escape_json($keyword).'"'; $i++; - if ($i < count($arrayofkeywords)) $ret .= ', '; + if ($i < count($arrayofkeywords)) { + $ret .= ', '; + } } $ret .= '],'."\n"; } @@ -672,8 +667,7 @@ function getStructuredData($type, $data = array()) $ret .= "\n".'}'."\n"; $ret .= ''."\n"; } - } elseif ($type == 'product') - { + } elseif ($type == 'product') { $ret = ''."\n"; $ret .= ''."\n"; - } elseif ($type == 'qa') - { + } elseif ($type == 'qa') { $ret = ''."\n"; $ret .= ' " method="post"> @@ -163,18 +160,18 @@ $listofexamplesforlink = 'Societe:societe/class/societe.class.php
    Contact:con trans("Value"); ?>
    @@ -210,7 +207,7 @@ $listofexamplesforlink = 'Societe:societe/class/societe.class.php
    Contact:con
    multicompany->enabled) { ?> - +
    '.$langs->trans("DateCreation").''.$langs->trans("DateDeliveryPlanned").''.$langs->trans("QtyPreparedOrShipped").''.$langs->trans("Warehouse").''; - print ''; + print ''.$langs->trans("DeliveryOrder").''.$langs->trans("QtyReceived").''.$langs->trans("DeliveryDate").'
    "; - if ($objp->fk_product_type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($objp->fk_product_type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($objp->label)) { $text .= ' '.$objp->label.''; @@ -369,11 +385,9 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') print ''.$objp->qty_shipped.''; - if ($objp->warehouse_id > 0) - { + if ($objp->warehouse_id > 0) { $warehousestatic->fetch($objp->warehouse_id); print $warehousestatic->getNomUrl(1); } @@ -384,47 +398,47 @@ function show_list_sending_receive($origin, $origin_id, $filter = '') /*TODO Add link to expeditiondet_batch if (! empty($conf->productbatch->enabled)) { - var_dump($objp->edrowid); - $lines[$i]->detail_batch - if (isset($lines[$i]->detail_batch)) - { - print ''; - if ($lines[$i]->product_tobatch) - { - $detail = ''; - foreach ($lines[$i]->detail_batch as $dbatch) - { + var_dump($objp->edrowid); + $lines[$i]->detail_batch + if (isset($lines[$i]->detail_batch)) + { + print ''; + if ($lines[$i]->product_tobatch) + { + $detail = ''; + foreach ($lines[$i]->detail_batch as $dbatch) + { $detail.= $langs->trans("Batch").': '.$dbatch->batch; $detail.= ' - '.$langs->trans("SellByDate").': '.dol_print_date($dbatch->sellby,"day"); $detail.= ' - '.$langs->trans("EatByDate").': '.dol_print_date($dbatch->eatby,"day"); $detail.= ' - '.$langs->trans("Qty").': '.$dbatch->qty; $detail.= '
    '; - } - print $form->textwithtooltip(img_picto('', 'object_barcode').' '.$langs->trans("DetailBatchNumber"),$detail); - } - else - { - print $langs->trans("NA"); - } - print '
    - - -
    - - - textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"), 1, 0, '', 0, 2, 'helpvalue1')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"), 1, 0, '', 0, 2, 'helpvalue2')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"), 1, 0, '', 0, 2, 'helpvalue3')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelplink").'

    '.$langs->trans("Examples").':
    '.$listofexamplesforlink, 1, 0, '', 0, 2, 'helpvalue4')?>
    - textwithpicto('', $langs->trans("ExtrafieldParamHelpPassword"), 1, 0, '', 0, 2, 'helpvalue5')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpSeparator"), 1, 0, '', 0, 2, 'helpvalue6')?> -
    + + +
    + + + textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"), 1, 0, '', 0, 2, 'helpvalue1')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"), 1, 0, '', 0, 2, 'helpvalue2')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"), 1, 0, '', 0, 2, 'helpvalue3')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelplink").'

    '.$langs->trans("Examples").':
    '.$listofexamplesforlink, 1, 0, '', 0, 2, 'helpvalue4')?>
    + textwithpicto('', $langs->trans("ExtrafieldParamHelpPassword"), 1, 0, '', 0, 2, 'helpvalue5')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpSeparator"), 1, 0, '', 0, 2, 'helpvalue6')?> +
    textwithpicto($langs->trans("HelpOnTooltip"), $langs->trans("HelpOnTooltipDesc")); ?>
    trans("AllEntities"); ?>>
    trans("AllEntities"); ?>>
    diff --git a/htdocs/core/tpl/admin_extrafields_edit.tpl.php b/htdocs/core/tpl/admin_extrafields_edit.tpl.php index 5239a93fdf7..bba6fd1bb7c 100644 --- a/htdocs/core/tpl/admin_extrafields_edit.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_edit.tpl.php @@ -27,8 +27,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -42,60 +41,58 @@ $listofexamplesforlink = 'Societe:societe/class/societe.class.php
    Contact:con @@ -171,18 +168,14 @@ $entitycurrentorall = $extrafields->attributes[$elementtype]['entityid'][$attrna $printable = $extrafields->attributes[$elementtype]['printable'][$attrname]; $enabled = $extrafields->attributes[$elementtype]['enabled'][$attrname]; -if ((($type == 'select') || ($type == 'checkbox') || ($type == 'radio')) && is_array($param)) -{ +if ((($type == 'select') || ($type == 'checkbox') || ($type == 'radio')) && is_array($param)) { $param_chain = ''; - foreach ($param['options'] as $key => $value) - { - if (strlen($key)) - { + foreach ($param['options'] as $key => $value) { + if (strlen($key)) { $param_chain .= $key.','.$value."\n"; } } -} elseif (($type == 'sellist') || ($type == 'chkbxlst') || ($type == 'link') || ($type == 'password') || ($type == 'separate')) -{ +} elseif (($type == 'sellist') || ($type == 'chkbxlst') || ($type == 'link') || ($type == 'password') || ($type == 'separate')) { $paramlist = array_keys($param['options']); $param_chain = $paramlist[0]; } @@ -215,16 +208,19 @@ if ($size <= 255 && in_array($type, array('text', 'html'))) { $typewecanchangeinto['text'][] = 'varchar'; }*/ -if (in_array($type, array_keys($typewecanchangeinto))) -{ +if (in_array($type, array_keys($typewecanchangeinto))) { $newarray = array(); print ''; print ajax_combobox('type'); @@ -244,18 +240,18 @@ if (in_array($type, array_keys($typewecanchangeinto))) trans("Value"); ?> - - -
    - - - textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"), 1, 0, '', 0, 2, 'helpvalue1')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"), 1, 0, '', 0, 2, 'helpvalue2')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"), 1, 0, '', 0, 2, 'helpvalue3')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelplink").'

    '.$langs->trans("Examples").':
    '.$listofexamplesforlink, 1, 0, '', 0, 2, 'helpvalue4')?>
    - textwithpicto('', $langs->trans("ExtrafieldParamHelpPassword"), 1, 0, '', 0, 2, 'helpvalue5')?> - textwithpicto('', $langs->trans("ExtrafieldParamHelpSeparator"), 1, 0, '', 0, 2, 'helpvalue6')?> -
    + + +
    + + + textwithpicto('', $langs->trans("ExtrafieldParamHelpselect"), 1, 0, '', 0, 2, 'helpvalue1')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpsellist"), 1, 0, '', 0, 2, 'helpvalue2')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpchkbxlst"), 1, 0, '', 0, 2, 'helpvalue3')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelplink").'

    '.$langs->trans("Examples").':
    '.$listofexamplesforlink, 1, 0, '', 0, 2, 'helpvalue4')?>
    + textwithpicto('', $langs->trans("ExtrafieldParamHelpPassword"), 1, 0, '', 0, 2, 'helpvalue5')?> + textwithpicto('', $langs->trans("ExtrafieldParamHelpSeparator"), 1, 0, '', 0, 2, 'helpvalue6')?> +
    @@ -301,7 +297,7 @@ if (in_array($type, array_keys($typewecanchangeinto))) multicompany->enabled) { ?> - trans("AllEntities"); ?>> + trans("AllEntities"); ?>> diff --git a/htdocs/core/tpl/admin_extrafields_view.tpl.php b/htdocs/core/tpl/admin_extrafields_view.tpl.php index c62a95ec12b..829ccaee903 100644 --- a/htdocs/core/tpl/admin_extrafields_view.tpl.php +++ b/htdocs/core/tpl/admin_extrafields_view.tpl.php @@ -25,8 +25,7 @@ */ // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } @@ -72,10 +71,8 @@ if ($conf->multicompany->enabled) { print ' '; print "\n"; -if (is_array($extrafields->attributes[$elementtype]['type']) && count($extrafields->attributes[$elementtype]['type'])) -{ - foreach ($extrafields->attributes[$elementtype]['type'] as $key => $value) - { +if (is_array($extrafields->attributes[$elementtype]['type']) && count($extrafields->attributes[$elementtype]['type'])) { + foreach ($extrafields->attributes[$elementtype]['type'] as $key => $value) { /*if (! dol_eval($extrafields->attributes[$elementtype]['enabled'][$key], 1)) { // TODO Uncomment this to exclude extrafields of modules not enabled. Add a link to "Show extrafields disabled" // continue; @@ -102,12 +99,13 @@ if (is_array($extrafields->attributes[$elementtype]['type']) && count($extrafiel print ''.yn($extrafields->attributes[$elementtype]['totalizable'][$key])."\n"; if (!empty($conf->multicompany->enabled)) { print ''; - if (empty($extrafields->attributes[$elementtype]['entityid'][$key])) - { + if (empty($extrafields->attributes[$elementtype]['entityid'][$key])) { print $langs->trans("All"); } else { global $multicompanylabel_cache; - if (!is_array($multicompanylabel_cache)) $multicompanylabel_cache = array(); + if (!is_array($multicompanylabel_cache)) { + $multicompanylabel_cache = array(); + } if (empty($multicompanylabel_cache[$extrafields->attributes[$elementtype]['entityid'][$key]])) { global $mc; $mc->getInfo($extrafields->attributes[$elementtype]['entityid'][$key]); @@ -123,7 +121,9 @@ if (is_array($extrafields->attributes[$elementtype]['type']) && count($extrafiel } } else { $colspan = 13; - if (!empty($conf->multicompany->enabled)) $colspan++; + if (!empty($conf->multicompany->enabled)) { + $colspan++; + } print ''; print ''; diff --git a/htdocs/core/tpl/advtarget.tpl.php b/htdocs/core/tpl/advtarget.tpl.php index 590a65f1286..86292ec0ff4 100644 --- a/htdocs/core/tpl/advtarget.tpl.php +++ b/htdocs/core/tpl/advtarget.tpl.php @@ -154,7 +154,8 @@ if (!empty($array_query['cust_status'])) { } print ''; print $formadvtargetemaling->advMultiselectarray( - 'cust_status', array( + 'cust_status', + array( '0' => $langs->trans('ActivityCeased'), '1' => $langs->trans('InActivity') ), @@ -473,8 +474,9 @@ if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) { $extrafields->fetch_name_optionals_label($elementype); if (!empty($extrafields->attributes[$elementtype]['type'])) { foreach ($extrafields->attributes[$elementtype]['type'] as $key => &$value) { - if ($value == 'radio') + if ($value == 'radio') { $value = 'select'; + } } } if (!empty($extrafields->attributes[$elementtype]['label'])) { diff --git a/htdocs/core/tpl/ajax/fileupload_main.tpl.php b/htdocs/core/tpl/ajax/fileupload_main.tpl.php index 6b7e21b5261..a4563c7536a 100644 --- a/htdocs/core/tpl/ajax/fileupload_main.tpl.php +++ b/htdocs/core/tpl/ajax/fileupload_main.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -27,20 +26,20 @@ if (empty($conf) || !is_object($conf))
    diff --git a/htdocs/core/tpl/ajax/objectlinked_lineimport.tpl.php b/htdocs/core/tpl/ajax/objectlinked_lineimport.tpl.php index 119e27a705b..3193f3db96d 100644 --- a/htdocs/core/tpl/ajax/objectlinked_lineimport.tpl.php +++ b/htdocs/core/tpl/ajax/objectlinked_lineimport.tpl.php @@ -16,15 +16,13 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } $objectUrl = $object->getNomUrl(0, '', 0, 1); -if ($object->element == 'propal') -{ +if ($object->element == 'propal') { $objectUrl = DOL_URL_ROOT.'/comm/propal/card.php?id='.$object->id; } @@ -36,67 +34,67 @@ if ($object->element == 'propal') $(document).ready(function(){ $('.objectlinked_importbtn').click(function (e) { - e.preventDefault(); - var page = $(this).attr("href"); + e.preventDefault(); + var page = $(this).attr("href"); - var fromelement = $(this).attr("data-element"); - var fromelementid = $(this).attr("data-id"); + var fromelement = $(this).attr("data-element"); + var fromelementid = $(this).attr("data-id"); if( page != undefined && fromelement != undefined && fromelementid != undefined) { - var windowWidth = $(window).width()*0.8; //retrieve current window width - var windowHeight = $(window).height()*0.8; //retrieve current window height + var windowWidth = $(window).width()*0.8; //retrieve current window width + var windowHeight = $(window).height()*0.8; //retrieve current window height var htmlLines; var formId = "ajaxloaded_tablelinesform_" + fromelement + "_" + fromelementid; - $.get(page, function (data) { - htmlLines = $(data).find('#tablelines') ; - }); + $.get(page, function (data) { + htmlLines = $(data).find('#tablelines') ; + }); - var $dialog = $('') - .load( page + " #tablelines", function() { + var $dialog = $('
    ') + .load( page + " #tablelines", function() { - $("#" + formId + " #tablelines").prop("id", "ajaxloaded_tablelines"); // change id attribute + $("#" + formId + " #tablelines").prop("id", "ajaxloaded_tablelines"); // change id attribute - $("#" + formId + " .linecheckbox,#" + formId + " .linecheckboxtoggle").prop("checked", true); // checked by default + $("#" + formId + " .linecheckbox,#" + formId + " .linecheckboxtoggle").prop("checked", true); // checked by default - // reload checkbox toggle function - $("#" + formId + " .linecheckboxtoggle").click(function(){ - var checkBoxes = $("#" + formId + " .linecheckbox"); - checkBoxes.prop("checked", this.checked); - }); + // reload checkbox toggle function + $("#" + formId + " .linecheckboxtoggle").click(function(){ + var checkBoxes = $("#" + formId + " .linecheckbox"); + checkBoxes.prop("checked", this.checked); + }); - }) - .html(htmlLines) - .dialog({ - autoOpen: false, - modal: true, - height: windowHeight, - width: windowWidth, - title: "transnoentities('LinesToImport'); ?>", - buttons: { - "trans('Import'); ?>": function() { - $( this ).dialog( "close" ); - $("#" + formId).append(''); - $("#" + formId).append(''); - $("#" + formId).append(''); - $("#" + formId).submit(); - }, - "trans("Cancel"); ?>": function() { - $( this ).dialog( "close" ); - } - } - }); + }) + .html(htmlLines) + .dialog({ + autoOpen: false, + modal: true, + height: windowHeight, + width: windowWidth, + title: "transnoentities('LinesToImport'); ?>", + buttons: { + "trans('Import'); ?>": function() { + $( this ).dialog( "close" ); + $("#" + formId).append(''); + $("#" + formId).append(''); + $("#" + formId).append(''); + $("#" + formId).submit(); + }, + "trans("Cancel"); ?>": function() { + $( this ).dialog( "close" ); + } + } + }); - $dialog.dialog('open'); + $dialog.dialog('open'); } else { $.jnotify("trans('ErrorNoUrl'); ?>", "error", true); } - }); + }); @@ -106,7 +104,7 @@ $(document).ready(function(){ diff --git a/htdocs/core/tpl/ajaxrow.tpl.php b/htdocs/core/tpl/ajaxrow.tpl.php index 1a797b936c3..6d6df3a5408 100644 --- a/htdocs/core/tpl/ajaxrow.tpl.php +++ b/htdocs/core/tpl/ajaxrow.tpl.php @@ -26,8 +26,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page ".basename(__FILE__)." can't be called with no object defined."; exit; } @@ -50,13 +49,13 @@ if (GETPOST('action', 'aZ09') != 'editline' && $nboflines > 1 && $conf->browser- $(document).ready(function(){ $(".imgupforline").hide(); $(".imgdownforline").hide(); - $(".lineupdown").removeAttr('href'); - $(".tdlineupdown").css("background-image",'url(theme.'/img/grip.png'; ?>)'); - $(".tdlineupdown").css("background-repeat","no-repeat"); - $(".tdlineupdown").css("background-position","center center"); + $(".lineupdown").removeAttr('href'); + $(".tdlineupdown").css("background-image",'url(theme.'/img/grip.png'; ?>)'); + $(".tdlineupdown").css("background-repeat","no-repeat"); + $(".tdlineupdown").css("background-position","center center"); - console.log("Prepare tableDnd for #"); - $("#").tableDnD({ + console.log("Prepare tableDnd for #"); + $("#").tableDnD({ onDrop: function(table, row) { var reloadpage = ""; console.log("tableDND onDrop"); @@ -100,9 +99,9 @@ $(document).ready(function(){ onDragClass: "dragClass", dragHandle: "td.tdlineupdown" }); - $(".tdlineupdown").hover( function() { $(this).addClass('showDragHandle'); }, - function() { $(this).removeClass('showDragHandle'); } - ); + $(".tdlineupdown").hover( function() { $(this).addClass('showDragHandle'); }, + function() { $(this).removeClass('showDragHandle'); } + ); }); @@ -110,7 +109,7 @@ $(document).ready(function(){ $(document).ready(function(){ $(".imgupforline").hide(); $(".imgdownforline").hide(); - $(".lineupdown").removeAttr('href'); + $(".lineupdown").removeAttr('href'); }); diff --git a/htdocs/core/tpl/bloc_comment.tpl.php b/htdocs/core/tpl/bloc_comment.tpl.php index 6dae2c713f2..bf148c2124f 100644 --- a/htdocs/core/tpl/bloc_comment.tpl.php +++ b/htdocs/core/tpl/bloc_comment.tpl.php @@ -1,8 +1,7 @@ '; print ''; print "\n"; -if ($action !== 'editcomment') -{ +if ($action !== 'editcomment') { print ''; // Description @@ -58,21 +56,17 @@ if ($action !== 'editcomment') print ''; // List of comments -if (!empty($object->comments)) -{ +if (!empty($object->comments)) { // Default color for current user $TColors = array($user->id => array('bgcolor'=>'efefef', 'color'=>'555')); $first = true; - foreach ($object->comments as $comment) - { + foreach ($object->comments as $comment) { $fk_user = $comment->fk_user_author; $userstatic->fetch($fk_user); - if (empty($TColors[$fk_user])) - { + if (empty($TColors[$fk_user])) { $bgcolor = randomColor(180, 240); - if (!empty($userstatic->color)) - { + if (!empty($userstatic->color)) { $bgcolor = $userstatic->color; } $color = (colorIsLight($bgcolor)) ? '555' : 'fff'; @@ -85,8 +79,7 @@ if (!empty($object->comments)) print '
    '; print '
    '; - if (!empty($user->photo)) - { + if (!empty($user->photo)) { print Form::showphoto('userphoto', $userstatic, 80, 0, 0, '', 'small', 0, 1).'
    '; } print $langs->trans('User').' : '.$userstatic->getNomUrl().'
    '; @@ -96,8 +89,7 @@ if (!empty($object->comments)) print '
    '; print '
    '; - if ($action === 'editcomment' && $comment->id == $idcomment) - { + if ($action === 'editcomment' && $comment->id == $idcomment) { print '
    '; print ''; print ''; @@ -107,8 +99,7 @@ if (!empty($object->comments)) } print '
    '; - if ($action === 'editcomment' && $comment->id == $idcomment) - { + 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 { @@ -116,15 +107,13 @@ if (!empty($object->comments)) } print '
    '; // End comment-description - if ($action === 'editcomment' && $comment->id == $idcomment) - { + if ($action === 'editcomment' && $comment->id == $idcomment) { print ''; print ''; print '
    '; } else { - if ($fk_user == $user->id || $user->admin == 1) - { + if ($fk_user == $user->id || $user->admin == 1) { print '
    '; print img_picto('', 'edit.png'); print ''; diff --git a/htdocs/core/tpl/bloc_showhide.tpl.php b/htdocs/core/tpl/bloc_showhide.tpl.php index d654f2b97b3..ee67fa6b74a 100644 --- a/htdocs/core/tpl/bloc_showhide.tpl.php +++ b/htdocs/core/tpl/bloc_showhide.tpl.php @@ -18,15 +18,18 @@ */ // Protection to avoid direct call of template -if (empty($blocname)) -{ +if (empty($blocname)) { print "Error, template page can't be called as URL"; exit; } $hide = true; // Hide by default -if (isset($parameters['showblocbydefault'])) $hide = (empty($parameters['showblocbydefault']) ? true : false); -if (isset($object->extraparams[$blocname]['showhide'])) $hide = (empty($object->extraparams[$blocname]['showhide']) ? true : false); +if (isset($parameters['showblocbydefault'])) { + $hide = (empty($parameters['showblocbydefault']) ? true : false); +} +if (isset($object->extraparams[$blocname]['showhide'])) { + $hide = (empty($object->extraparams[$blocname]['showhide']) ? true : false); +} ?> diff --git a/htdocs/core/tpl/card_presend.tpl.php b/htdocs/core/tpl/card_presend.tpl.php index 0a7ed20981e..de10465a736 100644 --- a/htdocs/core/tpl/card_presend.tpl.php +++ b/htdocs/core/tpl/card_presend.tpl.php @@ -33,23 +33,20 @@ if (empty($conf) || !is_object($conf)) { } -if ($action == 'presend') -{ +if ($action == 'presend') { $langs->load("mails"); $titreform = 'SendMail'; $object->fetch_projet(); - if (!in_array($object->element, array('societe', 'user', 'member'))) - { + if (!in_array($object->element, array('societe', 'user', 'member'))) { // TODO get also the main_lastdoc field of $object. If not found, try to guess with following code $ref = dol_sanitizeFileName($object->ref); include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Special case - if ($object->element == 'invoice_supplier') - { + if ($object->element == 'invoice_supplier') { $fileparams = dol_most_recent_file($diroutput.'/'.get_exdir($object->id, 2, 0, 0, $object, $object->element).$ref, preg_quote($ref, '/').'([^\-])+'); } else { $fileparams = dol_most_recent_file($diroutput.'/'.$ref, preg_quote($ref, '/').'[^\-]+'); @@ -61,17 +58,14 @@ if ($action == 'presend') // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($_REQUEST['lang_id'])) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && !empty($_REQUEST['lang_id'])) { $newlang = $_REQUEST['lang_id']; } - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) - { + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; } - if (!empty($newlang)) - { + if (!empty($newlang)) { $outputlangs = new Translate('', $conf); $outputlangs->setDefaultLang($newlang); // Load traductions files required by page @@ -87,19 +81,20 @@ if ($action == 'presend') // Build document if it not exists $forcebuilddoc = true; - if (in_array($object->element, array('societe', 'user', 'member'))) $forcebuilddoc = false; - if ($object->element == 'invoice_supplier' && empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) $forcebuilddoc = false; - if ($forcebuilddoc) // If there is no default value for supplier invoice, we do not generate file, even if modelpdf was set by a manual generation - { - if ((!$file || !is_readable($file)) && method_exists($object, 'generateDocument')) - { + if (in_array($object->element, array('societe', 'user', 'member'))) { + $forcebuilddoc = false; + } + if ($object->element == 'invoice_supplier' && empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) { + $forcebuilddoc = false; + } + if ($forcebuilddoc) { // If there is no default value for supplier invoice, we do not generate file, even if modelpdf was set by a manual generation + if ((!$file || !is_readable($file)) && method_exists($object, 'generateDocument')) { $result = $object->generateDocument(GETPOST('model') ? GETPOST('model') : $object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); if ($result < 0) { dol_print_error($db, $object->error, $object->errors); exit(); } - if ($object->element == 'invoice_supplier') - { + if ($object->element == 'invoice_supplier') { $fileparams = dol_most_recent_file($diroutput.'/'.get_exdir($object->id, 2, 0, 0, $object, $object->element).$ref, preg_quote($ref, '/').'([^\-])+'); } else { $fileparams = dol_most_recent_file($diroutput.'/'.$ref, preg_quote($ref, '/').'[^\-]+'); @@ -123,8 +118,7 @@ if ($action == 'presend') $formmail->param['langsmodels'] = (empty($newlang) ? $langs->defaultlang : $newlang); $formmail->fromtype = (GETPOST('fromtype') ?GETPOST('fromtype') : (!empty($conf->global->MAIN_MAIL_DEFAULT_FROMTYPE) ? $conf->global->MAIN_MAIL_DEFAULT_FROMTYPE : 'user')); - if ($formmail->fromtype === 'user') - { + if ($formmail->fromtype === 'user') { $formmail->fromid = $user->id; } @@ -145,8 +139,7 @@ if ($action == 'presend') } $formmail->trackid = $trackid; - if (!empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) // If bit 2 is set - { + if (!empty($conf->global->MAIN_EMAIL_ADD_TRACK_ID) && ($conf->global->MAIN_EMAIL_ADD_TRACK_ID & 2)) { // If bit 2 is set include DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; $formmail->frommail = dolAddEmailTrackId($formmail->frommail, $trackid); } @@ -170,8 +163,7 @@ if ($action == 'presend') if (!empty($object->socid) && $object->socid > 0 && !is_object($object->thirdparty) && method_exists($object, 'fetch_thirdparty')) { $object->fetch_thirdparty(); } - if (is_object($object->thirdparty)) - { + if (is_object($object->thirdparty)) { foreach ($object->thirdparty->thirdparty_and_contact_email_array(1) as $key => $value) { $liste[$key] = $value; } @@ -206,7 +198,9 @@ if ($action == 'presend') $formmail->withcancel = 1; //$arrayoffamiliestoexclude=array('system', 'mycompany', 'object', 'objectamount', 'date', 'user', ...); - if (!isset($arrayoffamiliestoexclude)) $arrayoffamiliestoexclude = null; + if (!isset($arrayoffamiliestoexclude)) { + $arrayoffamiliestoexclude = null; + } // Make substitution in email content $substitutionarray = getCommonSubstitutionArray($outputlangs, 0, $arrayoffamiliestoexclude, $object); diff --git a/htdocs/core/tpl/commonfields_add.tpl.php b/htdocs/core/tpl/commonfields_add.tpl.php index 388b4b63926..526d640b62a 100644 --- a/htdocs/core/tpl/commonfields_add.tpl.php +++ b/htdocs/core/tpl/commonfields_add.tpl.php @@ -23,8 +23,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -35,34 +34,57 @@ if (empty($conf) || !is_object($conf)) $object->fields = dol_sort_array($object->fields, 'position'); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // Discard if extrafield is a hidden field on form - if (abs($val['visible']) != 1 && abs($val['visible']) != 3) continue; + if (abs($val['visible']) != 1 && abs($val['visible']) != 3) { + continue; + } - if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) continue; // We don't want this field + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) { + continue; // We don't want this field + } print ''; print ''; - if (!empty($val['help'])) print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); - else print $langs->trans($val['label']); + if (!empty($val['help'])) { + print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); + } else { + print $langs->trans($val['label']); + } print ''; print ''; - if (!empty($val['picto'])) { print img_picto('', $val['picto']); } - if (in_array($val['type'], array('int', 'integer'))) $value = GETPOST($key, 'int'); - elseif ($val['type'] == 'double') $value = price2num(GETPOST($key, 'alphanohtml')); - elseif ($val['type'] == 'text' || $val['type'] == 'html') $value = GETPOST($key, 'restricthtml'); - elseif ($val['type'] == 'date') $value = dol_mktime(12, 0, 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); - elseif ($val['type'] == 'datetime') $value = dol_mktime(GETPOST($key.'hour', 'int'), GETPOST($key.'min', 'int'), 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); - elseif ($val['type'] == 'boolean') $value = (GETPOST($key) == 'on' ? 1 : 0); - else $value = GETPOST($key, 'alphanohtml'); - if ($val['noteditable']) print $object->showOutputField($val, $key, $value, '', '', '', 0); - else print $object->showInputField($val, $key, $value, '', '', '', 0); + if (!empty($val['picto'])) { + print img_picto('', $val['picto']); + } + if (in_array($val['type'], array('int', 'integer'))) { + $value = GETPOST($key, 'int'); + } elseif ($val['type'] == 'double') { + $value = price2num(GETPOST($key, 'alphanohtml')); + } elseif ($val['type'] == 'text' || $val['type'] == 'html') { + $value = GETPOST($key, 'restricthtml'); + } elseif ($val['type'] == 'date') { + $value = dol_mktime(12, 0, 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); + } elseif ($val['type'] == 'datetime') { + $value = dol_mktime(GETPOST($key.'hour', 'int'), GETPOST($key.'min', 'int'), 0, GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int')); + } elseif ($val['type'] == 'boolean') { + $value = (GETPOST($key) == 'on' ? 1 : 0); + } else { + $value = GETPOST($key, 'alphanohtml'); + } + if ($val['noteditable']) { + print $object->showOutputField($val, $key, $value, '', '', '', 0); + } else { + print $object->showInputField($val, $key, $value, '', '', '', 0); + } print ''; print ''; } diff --git a/htdocs/core/tpl/commonfields_edit.tpl.php b/htdocs/core/tpl/commonfields_edit.tpl.php index 76a9fafe417..8ea1befa009 100644 --- a/htdocs/core/tpl/commonfields_edit.tpl.php +++ b/htdocs/core/tpl/commonfields_edit.tpl.php @@ -22,12 +22,13 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } -if (!is_object($form)) $form = new Form($db); +if (!is_object($form)) { + $form = new Form($db); +} ?> @@ -35,26 +36,40 @@ if (!is_object($form)) $form = new Form($db); $object->fields = dol_sort_array($object->fields, 'position'); -foreach ($object->fields as $key => $val) -{ +foreach ($object->fields as $key => $val) { // Discard if extrafield is a hidden field on form - if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4) continue; + if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4) { + continue; + } - if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) continue; // We don't want this field + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) { + continue; // We don't want this field + } print ''; - if (!empty($val['help'])) print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); - else print $langs->trans($val['label']); + if (!empty($val['help'])) { + print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); + } else { + print $langs->trans($val['label']); + } print ''; print ''; - if (!empty($val['picto'])) { print img_picto('', $val['picto']); } - if (in_array($val['type'], array('int', 'integer'))) $value = GETPOSTISSET($key) ?GETPOST($key, 'int') : $object->$key; - elseif ($val['type'] == 'double') $value = GETPOSTISSET($key) ? price2num(GETPOST($key, 'alphanohtml')) : $object->$key; - elseif (preg_match('/^(text|html)/', $val['type'])) { + if (!empty($val['picto'])) { + print img_picto('', $val['picto']); + } + if (in_array($val['type'], array('int', 'integer'))) { + $value = GETPOSTISSET($key) ?GETPOST($key, 'int') : $object->$key; + } elseif ($val['type'] == 'double') { + $value = GETPOSTISSET($key) ? price2num(GETPOST($key, 'alphanohtml')) : $object->$key; + } elseif (preg_match('/^(text|html)/', $val['type'])) { $tmparray = explode(':', $val['type']); if (!empty($tmparray[1])) { $check = $tmparray[1]; @@ -62,11 +77,15 @@ foreach ($object->fields as $key => $val) $check = 'restricthtml'; } $value = GETPOSTISSET($key) ? GETPOST($key, $check) : $object->$key; + } else { + $value = GETPOSTISSET($key) ? GETPOST($key, 'alpha') : $object->$key; } - else $value = GETPOSTISSET($key) ? GETPOST($key, 'alpha') : $object->$key; //var_dump($val.' '.$key.' '.$value); - if ($val['noteditable']) print $object->showOutputField($val, $key, $value, '', '', '', 0); - else print $object->showInputField($val, $key, $value, '', '', '', 0); + if ($val['noteditable']) { + print $object->showOutputField($val, $key, $value, '', '', '', 0); + } else { + print $object->showInputField($val, $key, $value, '', '', '', 0); + } print ''; print ''; } diff --git a/htdocs/core/tpl/commonfields_view.tpl.php b/htdocs/core/tpl/commonfields_view.tpl.php index 5f58ba9e7e9..8fbd5aa2fb3 100644 --- a/htdocs/core/tpl/commonfields_view.tpl.php +++ b/htdocs/core/tpl/commonfields_view.tpl.php @@ -24,12 +24,13 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } -if (!is_object($form)) $form = new Form($db); +if (!is_object($form)) { + $form = new Form($db); +} ?> @@ -37,34 +38,54 @@ if (!is_object($form)) $form = new Form($db); $object->fields = dol_sort_array($object->fields, 'position'); -foreach ($object->fields as $key => $val) -{ - if (!empty($keyforbreak) && $key == $keyforbreak) break; // key used for break on second column +foreach ($object->fields as $key => $val) { + if (!empty($keyforbreak) && $key == $keyforbreak) { + break; // key used for break on second column + } // Discard if extrafield is a hidden field on form - if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4 && abs($val['visible']) != 5) continue; + if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4 && abs($val['visible']) != 5) { + continue; + } - if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) continue; // We don't want this field - if (in_array($key, array('ref', 'status'))) continue; // Ref and status are already in dol_banner + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) { + continue; // We don't want this field + } + if (in_array($key, array('ref', 'status'))) { + continue; // Ref and status are already in dol_banner + } $value = $object->$key; print ''; - if (!empty($val['help'])) print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); - else print $langs->trans($val['label']); + if (!empty($val['help'])) { + print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); + } else { + print $langs->trans($val['label']); + } print ''; print ''; - if (in_array($val['type'], array('text', 'html'))) print '
    '; + if (in_array($val['type'], array('text', 'html'))) { + print '
    '; + } print $object->showOutputField($val, $key, $value, '', '', '', 0); //print dol_escape_htmltag($object->$key, 1, 1); - if (in_array($val['type'], array('text', 'html'))) print '
    '; + if (in_array($val['type'], array('text', 'html'))) { + print '
    '; + } print ''; print ''; } @@ -79,10 +100,8 @@ print '
    '; print ''; $alreadyoutput = 1; -foreach ($object->fields as $key => $val) -{ - if ($alreadyoutput) - { +foreach ($object->fields as $key => $val) { + if ($alreadyoutput) { if (!empty($keyforbreak) && $key == $keyforbreak) { $alreadyoutput = 0; // key used for break on second column } else { @@ -91,29 +110,48 @@ foreach ($object->fields as $key => $val) } // Discard if extrafield is a hidden field on form - if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4 && abs($val['visible']) != 5) continue; + if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4 && abs($val['visible']) != 5) { + continue; + } - if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) continue; // We don't want this field - if (in_array($key, array('ref', 'status'))) continue; // Ref and status are already in dol_banner + if (array_key_exists('enabled', $val) && isset($val['enabled']) && !$val['enabled']) { + continue; // We don't want this field + } + if (in_array($key, array('ref', 'status'))) { + continue; // Ref and status are already in dol_banner + } $value = $object->$key; print ''; - if (!empty($val['help'])) print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); - else print $langs->trans($val['label']); + if (!empty($val['help'])) { + print $form->textwithpicto($langs->trans($val['label']), $langs->trans($val['help'])); + } else { + print $langs->trans($val['label']); + } print ''; print ''; print ''; } diff --git a/htdocs/core/tpl/contacts.tpl.php b/htdocs/core/tpl/contacts.tpl.php index e3c45b788c6..4c57ec953d4 100644 --- a/htdocs/core/tpl/contacts.tpl.php +++ b/htdocs/core/tpl/contacts.tpl.php @@ -24,8 +24,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -73,8 +72,7 @@ $userstatic = new User($db); '."\n"; print '
    '."\n"; @@ -91,15 +89,16 @@ if ($permission)
    " /> - '; ?> + '; + } ?>
    global->MAIN_INFO_SOCIETE_NOM; ?>
    @@ -107,14 +106,16 @@ if ($permission)
    element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) $tmpobject = $objectsrc; + if (($object->element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) { + $tmpobject = $objectsrc; + } $formcompany->selectTypeContact($tmpobject, '', 'type', 'internal'); ?>
     
    ">
    - id; ?>" /> - '; ?> + '; + } ?>
    socid; ?> @@ -145,8 +147,7 @@ if ($permission) $nbofcontacts = $form->num; $newcardbutton = ''; - if (!empty($object->socid) && $object->socid > 1 && $user->rights->societe->creer) - { + if (!empty($object->socid) && $object->socid > 1 && $user->rights->societe->creer) { $newcardbutton .= ''; } print $newcardbutton; @@ -155,17 +156,21 @@ if ($permission)
    element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) $tmpobject = $objectsrc; + if (($object->element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) { + $tmpobject = $objectsrc; + } $formcompany->selectTypeContact($tmpobject, $preselectedtypeofcontact, 'typecontact', 'external', 'position', 0, 'minwidth100imp'); ?>
     
    - "> + ">
    - "; @@ -179,17 +184,14 @@ if ($permission) // TODO: replace this with direct SQL string to use $db->sort($sortfield, $sortorder) $list = array(); -foreach (array('internal', 'external') as $source) -{ - if (($object->element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) - { +foreach (array('internal', 'external') as $source) { + if (($object->element == 'shipping' || $object->element == 'reception') && is_object($objectsrc)) { $contactlist = $objectsrc->liste_contact(-1, $source); } else { $contactlist = $object->liste_contact(-1, $source); } - foreach ($contactlist as $contact) - { + foreach ($contactlist as $contact) { $entry = new stdClass(); $entry->id = $contact['rowid']; $entry->type = $contact['libelle']; @@ -200,15 +202,13 @@ foreach (array('internal', 'external') as $source) $entry->contact_name = ""; $entry->status = ""; - if ($contact['source'] == 'internal') - { + if ($contact['source'] == 'internal') { $entry->nature = $langs->trans("User"); } elseif ($contact['source'] == 'external') { $entry->nature = $langs->trans("ThirdPartyContact"); } - if ($contact['socid'] > 0) - { + if ($contact['socid'] > 0) { $companystatic->fetch($contact['socid']); $entry->thirdparty_html = $companystatic->getNomUrl(1); $entry->thirdparty_name = strtolower($companystatic->getFullName($langs)); @@ -217,8 +217,7 @@ foreach (array('internal', 'external') as $source) $entry->thirdparty_name = strtolower($conf->global->MAIN_INFO_SOCIETE_NOM); } - if ($contact['source'] == 'internal') - { + if ($contact['source'] == 'internal') { $userstatic->fetch($contact['id']); $entry->contact_html = $userstatic->getNomUrl(-1, '', 0, 0, 0, 0, '', 'valignmiddle'); $entry->contact_name = strtolower($userstatic->getFullName($langs)); @@ -228,8 +227,7 @@ foreach (array('internal', 'external') as $source) $entry->contact_name = strtolower($contactstatic->getFullName($langs)); } - if ($contact['source'] == 'internal') - { + if ($contact['source'] == 'internal') { $entry->status = $userstatic->LibStatut($contact['statuscontact'], 3); } elseif ($contact['source'] == 'external') { $entry->status = $contactstatic->LibStatut($contact['statuscontact'], 3); @@ -243,8 +241,12 @@ foreach (array('internal', 'external') as $source) $sortfield = GETPOST("sortfield", "aZ09comma"); $sortorder = GETPOST("sortorder", 'aZ09comma'); -if (!$sortfield) $sortfield = "nature"; -if (!$sortorder) $sortorder = "asc"; +if (!$sortfield) { + $sortfield = "nature"; +} +if (!$sortorder) { + $sortorder = "asc"; +} // Re-sort list $list = dol_sort_array($list, $sortfield, $sortorder, 1, 0, 1); @@ -286,8 +288,7 @@ print_liste_field_titre($arrayfields['status']['label'], $_SERVER["PHP_SELF"], " print_liste_field_titre('', $_SERVER["PHP_SELF"], "", "", "", "", $sortfield, $sortorder, 'center maxwidthsearch '); print ""; -foreach ($list as $entry) -{ +foreach ($list as $entry) { print '
    '; print ''; @@ -296,8 +297,7 @@ foreach ($list as $entry) print ''; print ''; - if ($permission) - { + if ($permission) { $href = $_SERVER["PHP_SELF"]; $href .= '?id='.$object->id; $href .= '&action=deletecontact&token='.newToken(); diff --git a/htdocs/core/tpl/document_actions_post_headers.tpl.php b/htdocs/core/tpl/document_actions_post_headers.tpl.php index 80fd0d7df12..0dc0962af56 100644 --- a/htdocs/core/tpl/document_actions_post_headers.tpl.php +++ b/htdocs/core/tpl/document_actions_post_headers.tpl.php @@ -30,25 +30,32 @@ // $savingdocmask = dol_sanitizeFileName($object->ref).'-__file__'; // Protection to avoid direct call of template -if (empty($langs) || !is_object($langs)) -{ +if (empty($langs) || !is_object($langs)) { print "Error, template page can't be called as URL"; exit; } $langs->load("link"); -if (empty($relativepathwithnofile)) $relativepathwithnofile = ''; +if (empty($relativepathwithnofile)) { + $relativepathwithnofile = ''; +} -if (!isset($permission)) $permission = $permissiontoadd; -if (!isset($permtoedit)) $permtoedit = $permissiontoadd; +if (!isset($permission)) { + $permission = $permissiontoadd; +} +if (!isset($permtoedit)) { + $permtoedit = $permissiontoadd; +} // Drag and drop for up and down allowed on product, thirdparty, ... // The drag and drop call the page core/ajax/row.php // If you enable the move up/down of files here, check that page that include template set its sortorder on 'position_name' instead of 'name' // Also the object->fk_element must be defined. $disablemove = 1; -if (in_array($modulepart, array('product', 'produit', 'societe', 'user', 'ticket', 'holiday', 'expensereport'))) $disablemove = 0; +if (in_array($modulepart, array('product', 'produit', 'societe', 'user', 'ticket', 'holiday', 'expensereport'))) { + $disablemove = 0; +} @@ -56,17 +63,16 @@ if (in_array($modulepart, array('product', 'produit', 'societe', 'user', 'ticket * Confirm form to delete */ -if ($action == 'delete') -{ +if ($action == 'delete') { $langs->load("companies"); // Need for string DeleteFile+ConfirmDeleteFiles print $form->formconfirm( - $_SERVER["PHP_SELF"].'?id='.$object->id.'&urlfile='.urlencode(GETPOST("urlfile")).'&linkid='.GETPOST('linkid', 'int').(empty($param) ? '' : $param), - $langs->trans('DeleteFile'), - $langs->trans('ConfirmDeleteFile'), - 'confirm_deletefile', - '', - 0, - 1 + $_SERVER["PHP_SELF"].'?id='.$object->id.'&urlfile='.urlencode(GETPOST("urlfile")).'&linkid='.GETPOST('linkid', 'int').(empty($param) ? '' : $param), + $langs->trans('DeleteFile'), + $langs->trans('ConfirmDeleteFile'), + 'confirm_deletefile', + '', + 0, + 1 ); } @@ -99,8 +105,7 @@ if (!isset($savingdocmask) || !empty($conf->global->MAIN_DISABLE_SUGGEST_REF_AS_ 'product_batch', 'bom', 'mrp' - ))) - { + ))) { $savingdocmask = dol_sanitizeFileName($object->ref).'-__file__'; } /*if (in_array($modulepart,array('member'))) diff --git a/htdocs/core/tpl/extrafields_add.tpl.php b/htdocs/core/tpl/extrafields_add.tpl.php index 53cbe3d99cf..f194a177178 100644 --- a/htdocs/core/tpl/extrafields_add.tpl.php +++ b/htdocs/core/tpl/extrafields_add.tpl.php @@ -26,8 +26,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,13 +36,17 @@ if (empty($conf) || !is_object($conf)) executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { $params = array(); - if (isset($tpl_context)) $params['tpl_context'] = $tpl_context; + if (isset($tpl_context)) { + $params['tpl_context'] = $tpl_context; + } $params['cols'] = $parameters['colspanvalue']; print $object->showOptionals($extrafields, 'create', $params); } diff --git a/htdocs/core/tpl/extrafields_edit.tpl.php b/htdocs/core/tpl/extrafields_edit.tpl.php index dbc2b9745cd..5915fb8a633 100644 --- a/htdocs/core/tpl/extrafields_edit.tpl.php +++ b/htdocs/core/tpl/extrafields_edit.tpl.php @@ -26,8 +26,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,7 +36,9 @@ if (empty($conf) || !is_object($conf)) executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; if (empty($reshook)) { diff --git a/htdocs/core/tpl/extrafields_list_array_fields.tpl.php b/htdocs/core/tpl/extrafields_list_array_fields.tpl.php index bbc5ba3370b..d1fe41d8c1f 100644 --- a/htdocs/core/tpl/extrafields_list_array_fields.tpl.php +++ b/htdocs/core/tpl/extrafields_list_array_fields.tpl.php @@ -3,22 +3,24 @@ // So no output must be done. // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } -if (empty($extrafieldsobjectkey) && is_object($object)) $extrafieldsobjectkey = $object->table_element; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} // Loop to show all columns of extrafields from $obj, $extrafields and $db -if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ +if (!empty($extrafieldsobjectkey)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... if (is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label']) > 0) { - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) { - if (!empty($extrafields->attributes[$extrafieldsobjectkey]['list'][$key])) + if (!empty($extrafields->attributes[$extrafieldsobjectkey]['list'][$key])) { $arrayfields[$extrafieldsobjectprefix.$key] = array( 'label' => $extrafields->attributes[$extrafieldsobjectkey]['label'][$key], 'checked' => (($extrafields->attributes[$extrafieldsobjectkey]['list'][$key] < 0) ? 0 : 1), @@ -27,6 +29,7 @@ if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_e 'langfile' => $extrafields->attributes[$extrafieldsobjectkey]['langfile'][$key], 'help' => $extrafields->attributes[$extrafieldsobjectkey]['help'][$key], ); + } } } } diff --git a/htdocs/core/tpl/extrafields_list_print_fields.tpl.php b/htdocs/core/tpl/extrafields_list_print_fields.tpl.php index 8c46e34b428..5ea0e4821d6 100644 --- a/htdocs/core/tpl/extrafields_list_print_fields.tpl.php +++ b/htdocs/core/tpl/extrafields_list_print_fields.tpl.php @@ -1,37 +1,36 @@ table_element; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} // Loop to show all columns of extrafields from $obj, $extrafields and $db -if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ - if (is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) - { - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; +if (!empty($extrafieldsobjectkey)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) { + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } - foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) - { - if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) - { + foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) { + if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) { $align = $extrafields->getAlignFlag($key, $extrafieldsobjectkey); print ''; $tmpkey = 'options_'.$key; - if (in_array($extrafields->attributes[$extrafieldsobjectkey]['type'][$key], array('date', 'datetime', 'timestamp')) && !is_numeric($obj->$tmpkey)) - { + if (in_array($extrafields->attributes[$extrafieldsobjectkey]['type'][$key], array('date', 'datetime', 'timestamp')) && !is_numeric($obj->$tmpkey)) { $datenotinstring = $obj->$tmpkey; - if (!is_numeric($obj->$tmpkey)) // For backward compatibility - { + if (!is_numeric($obj->$tmpkey)) { // For backward compatibility $datenotinstring = $db->jdate($datenotinstring); } $value = $datenotinstring; @@ -39,8 +38,7 @@ if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_e $value = $obj->$tmpkey; } // If field is a computed field, we make computation to get value - if ($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key]) - { + if ($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key]) { //global $obj, $object; //var_dump($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key]); //var_dump($obj); @@ -51,18 +49,23 @@ if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_e print $extrafields->showOutputField($key, $value, '', $extrafieldsobjectkey); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } if ($extrafields->attributes[$extrafieldsobjectkey]['totalizable'][$key]) { if (!$i) { // we keep position for the first line $totalarray['totalizable'][$key]['pos'] = $totalarray['nbfield']; } - if (is_numeric($obj->$tmpkey)) $totalarray['totalizable'][$key]['total'] += $obj->$tmpkey; + if (is_numeric($obj->$tmpkey)) { + $totalarray['totalizable'][$key]['total'] += $obj->$tmpkey; + } } - if (!empty($val['isameasure'])) - { - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = $extrafieldsobjectprefix.$tmpkey; + if (!empty($val['isameasure'])) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = $extrafieldsobjectprefix.$tmpkey; + } $totalarray['val'][$extrafieldsobjectprefix.$tmpkey] += $obj->$tmpkey; } } diff --git a/htdocs/core/tpl/extrafields_list_search_input.tpl.php b/htdocs/core/tpl/extrafields_list_search_input.tpl.php index d69c045641d..77329eb06a4 100644 --- a/htdocs/core/tpl/extrafields_list_search_input.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_input.tpl.php @@ -3,44 +3,50 @@ print ''."\n"; // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } -if (empty($extrafieldsobjectkey) && is_object($object)) $extrafieldsobjectkey = $object->table_element; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} // Loop to show all columns of extrafields for the search title line -if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ - if (!empty($extrafields->attributes[$extrafieldsobjectkey]['label']) && is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) - { - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; - if (empty($search_options_pattern)) $search_options_pattern = 'search_options_'; +if (!empty($extrafieldsobjectkey)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (!empty($extrafields->attributes[$extrafieldsobjectkey]['label']) && is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) { + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } + if (empty($search_options_pattern)) { + $search_options_pattern = 'search_options_'; + } - foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) - { + foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) { if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) { $align = $extrafields->getAlignFlag($key); $typeofextrafield = $extrafields->attributes[$extrafieldsobjectkey]['type'][$key]; print ''; diff --git a/htdocs/core/tpl/extrafields_list_search_param.tpl.php b/htdocs/core/tpl/extrafields_list_search_param.tpl.php index 5fca6bc70a9..56652b87dd3 100644 --- a/htdocs/core/tpl/extrafields_list_search_param.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_param.tpl.php @@ -1,19 +1,18 @@ table_element like 'societe', 'socpeople', ... -{ - if (empty($search_options_pattern)) $search_options_pattern = 'search_options_'; +if (!empty($search_array_options) && is_array($search_array_options)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (empty($search_options_pattern)) { + $search_options_pattern = 'search_options_'; + } - foreach ($search_array_options as $key => $val) - { + foreach ($search_array_options as $key => $val) { $crit = $val; $tmpkey = preg_replace('/'.$search_options_pattern.'/', '', $key); if (is_array($val) && array_key_exists('start', $val) && array_key_exists('end', $val)) { @@ -32,6 +31,8 @@ if (!empty($search_array_options) && is_array($search_array_options)) // $extraf $param .= '&' . $search_options_pattern.$tmpkey.'_endmin=' . dol_print_date($val['end'], '%M'); $val = ''; } - if ($val != '') $param .= '&'.$search_options_pattern.$tmpkey.'='.urlencode($val); + if ($val != '') { + $param .= '&'.$search_options_pattern.$tmpkey.'='.urlencode($val); + } } } diff --git a/htdocs/core/tpl/extrafields_list_search_sql.tpl.php b/htdocs/core/tpl/extrafields_list_search_sql.tpl.php index b0fb03f2709..7268da76007 100644 --- a/htdocs/core/tpl/extrafields_list_search_sql.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_sql.tpl.php @@ -1,28 +1,30 @@ table_element; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} // Loop to complete the sql search criterias from extrafields -if (!empty($extrafieldsobjectkey) && !empty($search_array_options) && is_array($search_array_options)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; - if (empty($search_options_pattern)) $search_options_pattern = 'search_options_'; +if (!empty($extrafieldsobjectkey) && !empty($search_array_options) && is_array($search_array_options)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } + if (empty($search_options_pattern)) { + $search_options_pattern = 'search_options_'; + } - foreach ($search_array_options as $key => $val) - { + foreach ($search_array_options as $key => $val) { $crit = $val; $tmpkey = preg_replace('/'.$search_options_pattern.'/', '', $key); $typ = $extrafields->attributes[$extrafieldsobjectkey]['type'][$tmpkey]; - if ($crit != '' && in_array($typ, array('date', 'datetime', 'timestamp'))) - { + if ($crit != '' && in_array($typ, array('date', 'datetime', 'timestamp'))) { if (is_numeric($crit)) { $sql .= " AND ".$extrafieldsobjectprefix.$tmpkey." = '".$db->idate($crit)."'"; } elseif (is_array($crit)) { @@ -34,22 +36,31 @@ if (!empty($extrafieldsobjectkey) && !empty($search_array_options) && is_array($ $sql .= ' AND ('.$extrafieldsobjectprefix.$tmpkey." <= '". $db->idate($crit['end'])."')"; } } - } elseif (in_array($typ, array('boolean'))) - { + } elseif (in_array($typ, array('boolean'))) { if ($crit !== '-1' && $crit !== '') { $sql .= " AND (".$extrafieldsobjectprefix.$tmpkey." = '".$db->escape($crit)."'"; - if ($crit == '0') $sql .= " OR ".$extrafieldsobjectprefix.$tmpkey." IS NULL"; + if ($crit == '0') { + $sql .= " OR ".$extrafieldsobjectprefix.$tmpkey." IS NULL"; + } $sql .= ")"; } - } elseif ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0') && (!in_array($typ, array('link')) || $crit != '-1')) - { + } elseif ($crit != '' && (!in_array($typ, array('select', 'sellist')) || $crit != '0') && (!in_array($typ, array('link')) || $crit != '-1')) { $mode_search = 0; - if (in_array($typ, array('int', 'double', 'real', 'price'))) $mode_search = 1; // Search on a numeric - if (in_array($typ, array('sellist', 'link')) && $crit != '0' && $crit != '-1') $mode_search = 2; // Search on a foreign key int - if (in_array($typ, array('sellist')) && !is_numeric($crit)) $mode_search = 0;// Search on a foreign key string - if (in_array($typ, array('chkbxlst', 'checkbox'))) $mode_search = 4; // Search on a multiselect field with sql type = text - if (is_array($crit)) $crit = implode(' ', $crit); // natural_search() expects a string - elseif ($typ === 'select' and is_string($crit) and strpos($crit, ' ') === false) { + if (in_array($typ, array('int', 'double', 'real', 'price'))) { + $mode_search = 1; // Search on a numeric + } + if (in_array($typ, array('sellist', 'link')) && $crit != '0' && $crit != '-1') { + $mode_search = 2; // Search on a foreign key int + } + if (in_array($typ, array('sellist')) && !is_numeric($crit)) { + $mode_search = 0;// Search on a foreign key string + } + if (in_array($typ, array('chkbxlst', 'checkbox'))) { + $mode_search = 4; // Search on a multiselect field with sql type = text + } + if (is_array($crit)) { + $crit = implode(' ', $crit); // natural_search() expects a string + } elseif ($typ === 'select' and is_string($crit) and strpos($crit, ' ') === false) { $sql .= ' AND ('.$extrafieldsobjectprefix.$tmpkey.' = "'.$db->escape($crit).'")'; continue; } diff --git a/htdocs/core/tpl/extrafields_list_search_title.tpl.php b/htdocs/core/tpl/extrafields_list_search_title.tpl.php index f1ea80871b8..0a61e51d33d 100644 --- a/htdocs/core/tpl/extrafields_list_search_title.tpl.php +++ b/htdocs/core/tpl/extrafields_list_search_title.tpl.php @@ -1,29 +1,32 @@ table_element; -if (!isset($disablesortlink)) $disablesortlink = 0; +if (empty($extrafieldsobjectkey) && is_object($object)) { + $extrafieldsobjectkey = $object->table_element; +} +if (!isset($disablesortlink)) { + $disablesortlink = 0; +} // Loop to show all columns of extrafields for the title line -if (!empty($extrafieldsobjectkey)) // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... -{ - if (!empty($extrafields->attributes[$extrafieldsobjectkey]['label']) && is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) - { - if (empty($extrafieldsobjectprefix)) $extrafieldsobjectprefix = 'ef.'; +if (!empty($extrafieldsobjectkey)) { // $extrafieldsobject is the $object->table_element like 'societe', 'socpeople', ... + if (!empty($extrafields->attributes[$extrafieldsobjectkey]['label']) && is_array($extrafields->attributes[$extrafieldsobjectkey]['label']) && count($extrafields->attributes[$extrafieldsobjectkey]['label'])) { + if (empty($extrafieldsobjectprefix)) { + $extrafieldsobjectprefix = 'ef.'; + } - foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) - { - if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) - { + foreach ($extrafields->attributes[$extrafieldsobjectkey]['label'] as $key => $val) { + if (!empty($arrayfields[$extrafieldsobjectprefix.$key]['checked'])) { $align = $extrafields->getAlignFlag($key); $sortonfield = $extrafieldsobjectprefix.$key; - if (!empty($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key])) $sortonfield = ''; + if (!empty($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key])) { + $sortonfield = ''; + } if ($extrafields->attributes[$extrafieldsobjectkey]['type'][$key] == 'separate') { print ''; } else { diff --git a/htdocs/core/tpl/extrafields_view.tpl.php b/htdocs/core/tpl/extrafields_view.tpl.php index f8d86f2abee..1721f686776 100644 --- a/htdocs/core/tpl/extrafields_view.tpl.php +++ b/htdocs/core/tpl/extrafields_view.tpl.php @@ -26,74 +26,86 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } -if (!is_object($form)) $form = new Form($db); +if (!is_object($form)) { + $form = new Form($db); +} ?> fk_soc)) $parameters['socid'] = $object->fk_soc; +if (!is_array($parameters)) { + $parameters = array(); +} +if (!empty($cols)) { + $parameters['colspan'] = ' colspan="'.$cols.'"'; +} +if (!empty($cols)) { + $parameters['cols'] = $cols; +} +if (!empty($object->fk_soc)) { + $parameters['socid'] = $object->fk_soc; +} $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); print $hookmanager->resPrint; -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} //var_dump($extrafields->attributes[$object->table_element]); -if (empty($reshook) && is_array($extrafields->attributes[$object->table_element]['label'])) -{ +if (empty($reshook) && is_array($extrafields->attributes[$object->table_element]['label'])) { $lastseparatorkeyfound = ''; $extrafields_collapse_num = ''; $extrafields_collapse_num_old = ''; $i = 0; - foreach ($extrafields->attributes[$object->table_element]['label'] as $tmpkeyextra => $tmplabelextra) - { + foreach ($extrafields->attributes[$object->table_element]['label'] as $tmpkeyextra => $tmplabelextra) { $i++; // Discard if extrafield is a hidden field on form $enabled = 1; - if ($enabled && isset($extrafields->attributes[$object->table_element]['enabled'][$tmpkeyextra])) - { + if ($enabled && isset($extrafields->attributes[$object->table_element]['enabled'][$tmpkeyextra])) { $enabled = dol_eval($extrafields->attributes[$object->table_element]['enabled'][$tmpkeyextra], 1); } - if ($enabled && isset($extrafields->attributes[$object->table_element]['list'][$tmpkeyextra])) - { + if ($enabled && isset($extrafields->attributes[$object->table_element]['list'][$tmpkeyextra])) { $enabled = dol_eval($extrafields->attributes[$object->table_element]['list'][$tmpkeyextra], 1); } $perms = 1; - if ($perms && isset($extrafields->attributes[$object->table_element]['perms'][$tmpkeyextra])) - { + if ($perms && isset($extrafields->attributes[$object->table_element]['perms'][$tmpkeyextra])) { $perms = dol_eval($extrafields->attributes[$object->table_element]['perms'][$tmpkeyextra], 1); } //print $tmpkeyextra.'-'.$enabled.'-'.$perms.'-'.$tmplabelextra.$_POST["options_" . $tmpkeyextra].'
    '."\n"; - if (empty($enabled)) continue; // 0 = Never visible field - if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation - if (empty($perms)) continue; // 0 = Not visible + if (empty($enabled)) { + continue; // 0 = Never visible field + } + if (abs($enabled) != 1 && abs($enabled) != 3 && abs($enabled) != 5 && abs($enabled) != 4) { + continue; // <> -1 and <> 1 and <> 3 = not visible on forms, only on list <> 4 = not visible at the creation + } + if (empty($perms)) { + continue; // 0 = Not visible + } // Load language if required - if (!empty($extrafields->attributes[$object->table_element]['langfile'][$tmpkeyextra])) $langs->load($extrafields->attributes[$object->table_element]['langfile'][$tmpkeyextra]); - if ($action == 'edit_extras') - { + if (!empty($extrafields->attributes[$object->table_element]['langfile'][$tmpkeyextra])) { + $langs->load($extrafields->attributes[$object->table_element]['langfile'][$tmpkeyextra]); + } + if ($action == 'edit_extras') { $value = (GETPOSTISSET("options_".$tmpkeyextra) ? GETPOST("options_".$tmpkeyextra) : $object->array_options["options_".$tmpkeyextra]); } else { - $value = (!empty($object->array_options["options_".$tmpkeyextra]) ? $object->array_options["options_".$tmpkeyextra] : ''); + $value = (!empty($object->array_options["options_".$tmpkeyextra]) ? $object->array_options["options_".$tmpkeyextra] : ''); //var_dump($tmpkeyextra.' - '.$value); } // Print line tr of extra field - if ($extrafields->attributes[$object->table_element]['type'][$tmpkeyextra] == 'separate') - { + if ($extrafields->attributes[$object->table_element]['type'][$tmpkeyextra] == 'separate') { $extrafields_collapse_num = ''; $extrafield_param = $extrafields->attributes[$object->table_element]['param'][$tmpkeyextra]; if (!empty($extrafield_param) && is_array($extrafield_param)) { @@ -126,7 +138,9 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element] print ''; print ''; } print '
    '; - if (in_array($val['type'], array('text', 'html'))) print '
    '; + if (in_array($val['type'], array('text', 'html'))) { + print '
    '; + } print $object->showOutputField($val, $key, $value, '', '', '', 0); //print dol_escape_htmltag($object->$key, 1, 1); - if (in_array($val['type'], array('text', 'html'))) print '
    '; + if (in_array($val['type'], array('text', 'html'))) { + print '
    '; + } print '
    '.$entry->thirdparty_html.''.$entry->type.''.$entry->status.''; $tmpkey = preg_replace('/'.$search_options_pattern.'/', '', $key); - if (in_array($typeofextrafield, array('varchar', 'int', 'double')) && empty($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key])) - { + if (in_array($typeofextrafield, array('varchar', 'int', 'double')) && empty($extrafields->attributes[$extrafieldsobjectkey]['computed'][$key])) { $searchclass = ''; - if (in_array($typeofextrafield, array('varchar'))) $searchclass = 'searchstring'; - if (in_array($typeofextrafield, array('int', 'double'))) $searchclass = 'searchnum'; + if (in_array($typeofextrafield, array('varchar'))) { + $searchclass = 'searchstring'; + } + if (in_array($typeofextrafield, array('int', 'double'))) { + $searchclass = 'searchnum'; + } print ''; - } elseif (in_array($typeofextrafield, array('datetime', 'timestamp'))) - { + } elseif (in_array($typeofextrafield, array('datetime', 'timestamp'))) { $morecss = ''; echo $extrafields->showInputField($key, $search_array_options[$search_options_pattern.$tmpkey], '', '', $search_options_pattern, $morecss, 0, $extrafieldsobjectkey, 1); } else { // for the type as 'checkbox', 'chkbxlst', 'sellist' we should use code instead of id (example: I declare a 'chkbxlst' to have a link with dictionnairy, I have to extend it with the 'code' instead 'rowid') $morecss = ''; - if (in_array($typeofextrafield, array('link', 'sellist', 'text', 'html'))) $morecss = 'maxwidth200'; + if (in_array($typeofextrafield, array('link', 'sellist', 'text', 'html'))) { + $morecss = 'maxwidth200'; + } echo $extrafields->showInputField($key, $search_array_options[$search_options_pattern.$tmpkey], '', '', $search_options_pattern, $morecss, 0, $extrafieldsobjectkey, 1); } print '
    '; if (!empty($extrafields->attributes[$object->table_element]['help'][$tmpkeyextra])) { // You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click. @@ -141,23 +155,42 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element] //var_dump($user->rights); $permok = false; $keyforperm = $object->element; - if ($object->element == 'fichinter') $keyforperm = 'ficheinter'; - if (isset($user->rights->$keyforperm)) $permok = $user->rights->$keyforperm->creer || $user->rights->$keyforperm->create || $user->rights->$keyforperm->write; - if ($object->element == 'order_supplier') $permok = $user->rights->fournisseur->commande->creer; - if ($object->element == 'invoice_supplier') $permok = $user->rights->fournisseur->facture->creer; - if ($object->element == 'shipping') $permok = $user->rights->expedition->creer; - if ($object->element == 'delivery') $permok = $user->rights->expedition->delivery->creer; - if ($object->element == 'productlot') $permok = $user->rights->stock->creer; - if ($object->element == 'facturerec') $permok = $user->rights->facture->creer; - if ($object->element == 'mo') $permok = $user->rights->mrp->write; + if ($object->element == 'fichinter') { + $keyforperm = 'ficheinter'; + } + if (isset($user->rights->$keyforperm)) { + $permok = $user->rights->$keyforperm->creer || $user->rights->$keyforperm->create || $user->rights->$keyforperm->write; + } + if ($object->element == 'order_supplier') { + $permok = $user->rights->fournisseur->commande->creer; + } + if ($object->element == 'invoice_supplier') { + $permok = $user->rights->fournisseur->facture->creer; + } + if ($object->element == 'shipping') { + $permok = $user->rights->expedition->creer; + } + if ($object->element == 'delivery') { + $permok = $user->rights->expedition->delivery->creer; + } + if ($object->element == 'productlot') { + $permok = $user->rights->stock->creer; + } + if ($object->element == 'facturerec') { + $permok = $user->rights->facture->creer; + } + if ($object->element == 'mo') { + $permok = $user->rights->mrp->write; + } $isdraft = ((isset($object->statut) && $object->statut == 0) || (isset($object->status) && $object->status == 0)); if (($isdraft || !empty($extrafields->attributes[$object->table_element]['alwayseditable'][$tmpkeyextra])) && $permok && $enabled != 5 && ($action != 'edit_extras' || GETPOST('attribute') != $tmpkeyextra) - && empty($extrafields->attributes[$object->table_element]['computed'][$tmpkeyextra])) - { + && empty($extrafields->attributes[$object->table_element]['computed'][$tmpkeyextra])) { $fieldid = 'id'; - if ($object->table_element == 'societe') $fieldid = 'socid'; + if ($object->table_element == 'societe') { + $fieldid = 'socid'; + } print ''.img_edit().'
    '; @@ -168,12 +201,10 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element] print ''; // Convert date into timestamp format - if (in_array($extrafields->attributes[$object->table_element]['type'][$tmpkeyextra], array('date', 'datetime'))) - { + if (in_array($extrafields->attributes[$object->table_element]['type'][$tmpkeyextra], array('date', 'datetime'))) { $datenotinstring = $object->array_options['options_'.$tmpkeyextra]; // print 'X'.$object->array_options['options_' . $tmpkeyextra].'-'.$datenotinstring.'x'; - if (!is_numeric($object->array_options['options_'.$tmpkeyextra])) // For backward compatibility - { + if (!is_numeric($object->array_options['options_'.$tmpkeyextra])) { // For backward compatibility $datenotinstring = $db->jdate($datenotinstring); } //print 'x'.$object->array_options['options_' . $tmpkeyextra].'-'.$datenotinstring.' - '.dol_print_date($datenotinstring, 'dayhour'); @@ -181,10 +212,11 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element] } //TODO Improve element and rights detection - if ($action == 'edit_extras' && $permok && GETPOST('attribute', 'restricthtml') == $tmpkeyextra) - { + if ($action == 'edit_extras' && $permok && GETPOST('attribute', 'restricthtml') == $tmpkeyextra) { $fieldid = 'id'; - if ($object->table_element == 'societe') $fieldid = 'socid'; + if ($object->table_element == 'societe') { + $fieldid = 'socid'; + } print '
    '; print ''; print ''; @@ -208,8 +240,7 @@ if (empty($reshook) && is_array($extrafields->attributes[$object->table_element] // Add code to manage list depending on others // TODO Test/enhance this with a more generic solution - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print "\n"; print ' + }); + use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE include_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; $formfile = new FormFile($db); $formfile->form_attach_new_file($_SERVER["PHP_SELF"], 'none', 0, ($section ? $section : -1), $permtoupload, 48, null, '', 0, '', 0, $nameforformuserfile, '', $sectiondir); -} else print ' '; +} else { + print ' '; +} print '
    '; // End "Add new file" area @@ -131,15 +127,13 @@ print '
    '; // Ask confirmation of deletion of directory -if ($action == 'delete_section') -{ +if ($action == 'delete_section') { print $form->formconfirm($_SERVER["PHP_SELF"].'?section='.$section, $langs->trans('DeleteSection'), $langs->trans('ConfirmDeleteSection', $ecmdir->label), 'confirm_deletesection', '', '', 1); } // End confirm -if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg_match('/refresh/i', $action) || $action == 'delete') -{ +if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg_match('/refresh/i', $action) || $action == 'delete') { $langs->load("ecm"); print ''."\n"; @@ -155,14 +149,15 @@ if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg // Manual section $htmltooltip = $langs->trans("ECMAreaDesc2"); - if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) - { + if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) { // Show the link to "Root" - if ($showroot) - { + if ($showroot) { print ''; } @@ -171,7 +166,9 @@ if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg // Show filemanager tree (will be filled by a call of ajax /ecm/tpl/enablefiletreeajax.tpl.php, later, that executes ajaxdirtree.php) print '
    '; - if ($action == 'deletefile') print $form->formconfirm('eeeee', $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', '', 'deletefile'); + if ($action == 'deletefile') { + print $form->formconfirm('eeeee', $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', '', 'deletefile'); + } print ''; } else { // Show filtree when ajax is disabled (rare) @@ -188,7 +185,9 @@ if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg // $_GET['modulepart'], $_GET['openeddir'], $_GET['sortfield'], $_GET['sortorder'] // $_POST['dir'] $mode = 'noajax'; - if (empty($url)) $url = DOL_URL_ROOT.'/ecm/index.php'; + if (empty($url)) { + $url = DOL_URL_ROOT.'/ecm/index.php'; + } include DOL_DOCUMENT_ROOT.'/core/ajax/ajaxdirtree.php'; print ''; @@ -211,7 +210,9 @@ if (empty($action) || $action == 'editfile' || $action == 'file_manager' || preg $mode = 'noajax'; -if (empty($url)) $url = DOL_URL_ROOT.'/ecm/index.php'; +if (empty($url)) { + $url = DOL_URL_ROOT.'/ecm/index.php'; +} include DOL_DOCUMENT_ROOT.'/core/ajax/ajaxdirpreview.php'; // Show content of a directory on right side @@ -225,14 +226,15 @@ include DOL_DOCUMENT_ROOT.'/core/ajax/ajaxdirpreview.php'; // Show content of a use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) // Show filtree when ajax is enabled -{ +if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_ECM_DISABLE_JS)) { // Show filtree when ajax is enabled //var_dump($modulepart); // Variables that may be defined: // $_GET['modulepart'], $_GET['openeddir'], $_GET['sortfield'], $_GET['sortorder'] // $_POST['dir'] // $_POST['section_dir'], $_POST['section_id'], $_POST['token'], $_POST['max_file_size'], $_POST['sendit'] - if (GETPOST('section_dir', 'alpha')) { $preopened = GETPOST('section_dir', 'alpha'); } + if (GETPOST('section_dir', 'alpha')) { + $preopened = GETPOST('section_dir', 'alpha'); + } include DOL_DOCUMENT_ROOT.'/ecm/tpl/enablefiletreeajax.tpl.php'; } diff --git a/htdocs/core/tpl/list_print_total.tpl.php b/htdocs/core/tpl/list_print_total.tpl.php index 2cd485a9510..80baabf8a1e 100644 --- a/htdocs/core/tpl/list_print_total.tpl.php +++ b/htdocs/core/tpl/list_print_total.tpl.php @@ -7,20 +7,23 @@ if (is_array($totalarray['totalizable'])) { } } // Show total line -if (isset($totalarray['pos'])) -{ +if (isset($totalarray['pos'])) { print ''; $i = 0; - while ($i < $totalarray['nbfield']) - { + while ($i < $totalarray['nbfield']) { $i++; - if (!empty($totalarray['pos'][$i])) print ''; - else { - if ($i == 1) - { - if ($num < $limit) print ''; - else print ''; - } else print ''; + if (!empty($totalarray['pos'][$i])) { + print ''; + } else { + if ($i == 1) { + if ($num < $limit) { + print ''; + } else { + print ''; + } + } else { + print ''; + } } } print ''; diff --git a/htdocs/core/tpl/login.tpl.php b/htdocs/core/tpl/login.tpl.php index 8d9c79f807d..b5dc9b90be0 100644 --- a/htdocs/core/tpl/login.tpl.php +++ b/htdocs/core/tpl/login.tpl.php @@ -20,7 +20,9 @@ // Caller can also set $morelogincontent = array(['options']=>array('js'=>..., 'table'=>...); -if (!defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', 1); +if (!defined('NOBROWSERNOTIF')) { + define('NOBROWSERNOTIF', 1); +} // Protection to avoid direct call of template if (empty($conf) || !is_object($conf)) { @@ -34,18 +36,32 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; header('Cache-Control: Public, must-revalidate'); header("Content-type: text/html; charset=".$conf->file->character_set_client); -if (GETPOST('dol_hide_topmenu')) $conf->dol_hide_topmenu = 1; -if (GETPOST('dol_hide_leftmenu')) $conf->dol_hide_leftmenu = 1; -if (GETPOST('dol_optimize_smallscreen')) $conf->dol_optimize_smallscreen = 1; -if (GETPOST('dol_no_mouse_hover')) $conf->dol_no_mouse_hover = 1; -if (GETPOST('dol_use_jmobile')) $conf->dol_use_jmobile = 1; +if (GETPOST('dol_hide_topmenu')) { + $conf->dol_hide_topmenu = 1; +} +if (GETPOST('dol_hide_leftmenu')) { + $conf->dol_hide_leftmenu = 1; +} +if (GETPOST('dol_optimize_smallscreen')) { + $conf->dol_optimize_smallscreen = 1; +} +if (GETPOST('dol_no_mouse_hover')) { + $conf->dol_no_mouse_hover = 1; +} +if (GETPOST('dol_use_jmobile')) { + $conf->dol_use_jmobile = 1; +} // If we force to use jmobile, then we reenable javascript -if (!empty($conf->dol_use_jmobile)) $conf->use_javascript_ajax = 1; +if (!empty($conf->dol_use_jmobile)) { + $conf->use_javascript_ajax = 1; +} $php_self = dol_escape_htmltag($_SERVER['PHP_SELF']); $php_self .= dol_escape_htmltag($_SERVER["QUERY_STRING"]) ? '?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]) : ''; -if (!preg_match('/mainmenu=/', $php_self)) $php_self .= (preg_match('/\?/', $php_self) ? '&' : '?').'mainmenu=home'; +if (!preg_match('/mainmenu=/', $php_self)) { + $php_self .= (preg_match('/\?/', $php_self) ? '&' : '?').'mainmenu=home'; +} // Javascript code on logon page only to detect user tz, dst_observed, dst_first, dst_second $arrayofjs = array( @@ -62,14 +78,20 @@ if (!empty($conf->global->MAIN_APPLICATION_TITLE)) { $titleofloginpage .= ' @ '.$titletruedolibarrversion; // $titletruedolibarrversion is defined by dol_loginfunction in security2.lib.php. We must keep the @, some tools use it to know it is login page and find true dolibarr version. $disablenofollow = 1; -if (!preg_match('/'.constant('DOL_APPLICATION_TITLE').'/', $title)) $disablenofollow = 0; -if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) $disablenofollow = 0; +if (!preg_match('/'.constant('DOL_APPLICATION_TITLE').'/', $title)) { + $disablenofollow = 0; +} +if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + $disablenofollow = 0; +} print top_htmlhead('', $titleofloginpage, 0, 0, $arrayofjs, array(), 0, $disablenofollow); $colorbackhmenu1 = '60,70,100'; // topmenu -if (!isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) $conf->global->THEME_ELDY_TOPMENU_BACK1 = $colorbackhmenu1; +if (!isset($conf->global->THEME_ELDY_TOPMENU_BACK1)) { + $conf->global->THEME_ELDY_TOPMENU_BACK1 = $colorbackhmenu1; +} $colorbackhmenu1 = empty($user->conf->THEME_ELDY_ENABLE_PERSONALIZED) ? (empty($conf->global->THEME_ELDY_TOPMENU_BACK1) ? $colorbackhmenu1 : $conf->global->THEME_ELDY_TOPMENU_BACK1) : (empty($user->conf->THEME_ELDY_TOPMENU_BACK1) ? $colorbackhmenu1 : $user->conf->THEME_ELDY_TOPMENU_BACK1); $colorbackhmenu1 = join(',', colorStringToArray($colorbackhmenu1)); // Normalize value to 'x,y,z' @@ -91,7 +113,9 @@ if (!empty($conf->global->ADD_UNSPLASH_LOGIN_BACKGROUND)) { @@ -122,9 +146,13 @@ $(document).ready(function () { @@ -147,7 +175,9 @@ if ($disablenofollow) echo '';
    -global->MAIN_OPTIMIZEFORTEXTBROWSER)) { ?> +global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + ?> " name="username" class="flat input-icon-user minwidth150" value="" tabindex="1" autofocus="autofocus" /> @@ -157,7 +187,9 @@ if ($disablenofollow) echo '';
    -global->MAIN_OPTIMIZEFORTEXTBROWSER)) { ?> +global->MAIN_OPTIMIZEFORTEXTBROWSER)) { + ?> " name="password" class="flat input-icon-password minwidth150" type="password" value="" tabindex="2" autocomplete="global->MAIN_LOGIN_ENABLE_PASSWORD_AUTOCOMPLETE) ? 'off' : 'on'; ?>" /> @@ -167,8 +199,11 @@ if ($disablenofollow) echo ''; if ($captcha) { // Add a variable param to force not using cache (jmobile) $php_self = preg_replace('/[&\?]time=(\d+)/', '', $php_self); // Remove param time - if (preg_match('/\?/', $php_self)) $php_self .= '&time='.dol_print_date(dol_now(), 'dayhourlog'); - else $php_self .= '?time='.dol_print_date(dol_now(), 'dayhourlog'); + if (preg_match('/\?/', $php_self)) { + $php_self .= '&time='.dol_print_date(dol_now(), 'dayhourlog'); + } else { + $php_self .= '?time='.dol_print_date(dol_now(), 'dayhourlog'); + } // TODO: provide accessible captcha variants ?> @@ -190,8 +225,7 @@ if ($captcha) { if (!empty($morelogincontent)) { if (is_array($morelogincontent)) { - foreach ($morelogincontent as $format => $option) - { + foreach ($morelogincontent as $format => $option) { if ($format == 'table') { echo ''; echo $option; @@ -221,29 +255,42 @@ if (!empty($morelogincontent)) {
    '; echo '
    '; if ($forgetpasslink) { $url = DOL_URL_ROOT.'/user/passwordforgotten.php'.$moreparam; - if (!empty($conf->global->MAIN_PASSWORD_FORGOTLINK)) $url = $conf->global->MAIN_PASSWORD_FORGOTLINK; + if (!empty($conf->global->MAIN_PASSWORD_FORGOTLINK)) { + $url = $conf->global->MAIN_PASSWORD_FORGOTLINK; + } echo ''; echo $langs->trans('PasswordForgotten'); echo ''; } - if ($forgetpasslink && $helpcenterlink) echo ' - '; + if ($forgetpasslink && $helpcenterlink) { + echo ' - '; + } if ($helpcenterlink) { $url = DOL_URL_ROOT.'/support/index.php'.$moreparam; - if (!empty($conf->global->MAIN_HELPCENTER_LINKTOUSE)) $url = $conf->global->MAIN_HELPCENTER_LINKTOUSE; + if (!empty($conf->global->MAIN_HELPCENTER_LINKTOUSE)) { + $url = $conf->global->MAIN_HELPCENTER_LINKTOUSE; + } echo ''; echo $langs->trans('NeedHelpCenter'); echo ''; @@ -251,8 +298,7 @@ if ($forgetpasslink || $helpcenterlink) echo '
    '; } -if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication)) -{ +if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->file->main_authentication)) { $langs->load("users"); //if (! empty($conf->global->MAIN_OPENIDURL_PERUSER)) $url= @@ -260,8 +306,9 @@ if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->fil echo '
    '; $url = $conf->global->MAIN_AUTHENTICATION_OPENID_URL; - if (!empty($url)) print ''.$langs->trans("LoginUsingOpenID").''; - else { + if (!empty($url)) { + print ''.$langs->trans("LoginUsingOpenID").''; + } else { $langs->load("errors"); print ''.$langs->trans("ErrorOpenIDSetupNotComplete", 'MAIN_AUTHENTICATION_OPENID_URL').''; } @@ -282,8 +329,7 @@ if (isset($conf->file->main_authentication) && preg_match('/openid/', $conf->fil
    '; // Multicurrency -if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print ''; +if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) { + print ''; +} -if ($inputalsopricewithtax) print ''; +if ($inputalsopricewithtax) { + print ''; +} // Qty print ''; // Unit -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; } @@ -107,10 +109,8 @@ if ($this->situation_cycle_ref) { } // Purchase price -if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) -{ - if (!empty($user->rights->margins->creer)) - { +if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) { + if (!empty($user->rights->margins->creer)) { if ($conf->global->MARGIN_TYPE == "1") { print ''; } else { @@ -130,9 +130,13 @@ if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) print ''; // Multicurrency -if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) print ''; +if (!empty($conf->multicurrency->enabled) && $this->multicurrency_code != $conf->currency) { + print ''; +} -if ($outputalsopricetotalwithtax) print ''; +if ($outputalsopricetotalwithtax) { + print ''; +} print ''; // No width to allow autodim @@ -140,8 +144,7 @@ print ''; print ''; -if ($action == 'selectlines') -{ +if ($action == 'selectlines') { print ''; -if ($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') // We must have same test in printObjectLines -{ +if ($object->element == 'supplier_proposal' || $object->element == 'order_supplier' || $object->element == 'invoice_supplier') { // We must have same test in printObjectLines print ''; @@ -203,10 +225,18 @@ if ($object->element == 'supplier_proposal' || $object->element == 'order_suppli print ' @@ -229,11 +259,12 @@ if ((($line->info_bits & 2) != 2) && $line->special_code != 3) { // must also not be output for most entities (proposal, intervention, ...) //if($line->qty > $line->stock) print img_picto($langs->trans("StockTooLow"),"warning", 'style="vertical-align: bottom;"')." "; print price($line->qty, 0, '', 0, 0); // Yes, it is a quantity, not a price, but we just want the formating role of function price -} else print ' '; +} else { + print ' '; +} print ''; -if (!empty($conf->global->PRODUCT_USE_UNITS)) -{ +if (!empty($conf->global->PRODUCT_USE_UNITS)) { print ''; @@ -264,8 +294,7 @@ if ($this->situation_cycle_ref) print ''; } -if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) -{ +if ($usemargins && !empty($conf->margin->enabled) && empty($user->socid)) { if (!empty($user->rights->margins->creer)) { ?> margin->enabled) && empty($user->socid)) global->DISPLAY_MARK_RATES) && $user->rights->margins->liretous) {?> - - marque_tx, 'MT')).'%'; ?> + special_code == 3) { ?> @@ -282,8 +311,7 @@ if ($line->special_code == 3) { ?> '; $coldisplay++; - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $tooltiponprice = $langs->transcountry("TotalHT", $mysoc->country_code).'='.price($line->total_ht); $tooltiponprice .= '
    '.$langs->transcountry("TotalVAT", ($senderissupplier ? $object->thirdparty->country_code : $mysoc->country_code)).'='.price($line->total_tva); if (!$senderissupplier && is_object($object->thirdparty)) { @@ -307,8 +335,7 @@ if ($line->special_code == 3) { ?> print ''; } print price($sign * $line->total_ht); - if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { print ''; } print ''; diff --git a/htdocs/core/tpl/onlinepaymentlinks.tpl.php b/htdocs/core/tpl/onlinepaymentlinks.tpl.php index 959bf7fd6ad..c4b2ad5e3e4 100644 --- a/htdocs/core/tpl/onlinepaymentlinks.tpl.php +++ b/htdocs/core/tpl/onlinepaymentlinks.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -30,13 +29,11 @@ print ''; print ''.$langs->trans("FollowingUrlAreAvailableToMakePayments").':

    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnFreeAmount", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'free')."

    \n"; -if (!empty($conf->commande->enabled)) -{ +if (!empty($conf->commande->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnOrder", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'order')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("orders"); print ''; print ''; @@ -44,8 +41,7 @@ if (!empty($conf->commande->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("Order")).': '; print ''; print ''; - if (GETPOST('generate_order_ref', 'alpha')) - { + if (GETPOST('generate_order_ref', 'alpha')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'order', GETPOST('generate_order_ref', 'alpha')); print $url; @@ -55,13 +51,11 @@ if (!empty($conf->commande->enabled)) } print '
    '; } -if (!empty($conf->facture->enabled)) -{ +if (!empty($conf->facture->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnInvoice", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'invoice')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("bills"); print ''; print ''; @@ -69,8 +63,7 @@ if (!empty($conf->facture->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("Invoice")).': '; print ''; print ''; - if (GETPOST('generate_invoice_ref', 'alpha')) - { + if (GETPOST('generate_invoice_ref', 'alpha')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'invoice', GETPOST('generate_invoice_ref', 'alpha')); print $url; @@ -80,13 +73,11 @@ if (!empty($conf->facture->enabled)) } print '
    '; } -if (!empty($conf->contrat->enabled)) -{ +if (!empty($conf->contrat->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnContractLine", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'contractline')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("contracts"); print ''; print ''; @@ -94,8 +85,7 @@ if (!empty($conf->contrat->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("ContractLine")).': '; print ''; print ''; - if (GETPOST('generate_contract_ref')) - { + if (GETPOST('generate_contract_ref')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'contractline', GETPOST('generate_contract_ref', 'alpha')); print $url; @@ -105,13 +95,11 @@ if (!empty($conf->contrat->enabled)) } print '
    '; } -if (!empty($conf->adherent->enabled)) -{ +if (!empty($conf->adherent->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnMemberSubscription", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'membersubscription')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("members"); print ''; print ''; @@ -119,8 +107,7 @@ if (!empty($conf->adherent->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("Member")).': '; print ''; print ''; - if (GETPOST('generate_member_ref')) - { + if (GETPOST('generate_member_ref')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'membersubscription', GETPOST('generate_member_ref', 'alpha')); print $url; @@ -130,13 +117,11 @@ if (!empty($conf->adherent->enabled)) } print '
    '; } -if (!empty($conf->don->enabled)) -{ +if (!empty($conf->don->enabled)) { print '
    '; print img_picto('', 'globe').' '.$langs->trans("ToOfferALinkForOnlinePaymentOnDonation", $servicename).':
    '; print ''.getOnlinePaymentUrl(1, 'donation')."
    \n"; - if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) - { + if (!empty($conf->global->PAYMENT_SECURITY_TOKEN) && !empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) { $langs->load("members"); print ''; print ''; @@ -144,8 +129,7 @@ if (!empty($conf->don->enabled)) print $langs->trans("EnterRefToBuildUrl", $langs->transnoentitiesnoconv("Don")).': '; print ''; print ''; - if (GETPOST('generate_donation_ref')) - { + if (GETPOST('generate_donation_ref')) { print '
    -> '; $url = getOnlinePaymentUrl(0, 'donation', GETPOST('generate_donation_ref', 'alpha')); print $url; @@ -156,8 +140,7 @@ if (!empty($conf->don->enabled)) print '
    '; } -if (!empty($conf->use_javascript_ajax)) -{ +if (!empty($conf->use_javascript_ajax)) { print "\n".' @@ -81,9 +98,13 @@ $(document).ready(function () { @@ -116,8 +137,11 @@ if (!empty($disablenofollow)) echo ''; if (!empty($captcha)) { // Add a variable param to force not using cache (jmobile) $php_self = preg_replace('/[&\?]time=(\d+)/', '', $php_self); // Remove param time - if (preg_match('/\?/', $php_self)) $php_self .= '&time='.dol_print_date(dol_now(), 'dayhourlog'); - else $php_self .= '?time='.dol_print_date(dol_now(), 'dayhourlog'); + if (preg_match('/\?/', $php_self)) { + $php_self .= '&time='.dol_print_date(dol_now(), 'dayhourlog'); + } else { + $php_self .= '?time='.dol_print_date(dol_now(), 'dayhourlog'); + } // TODO: provide accessible captcha variants ?> @@ -139,8 +163,7 @@ if (!empty($captcha)) { if (!empty($morelogincontent)) { if (is_array($morelogincontent)) { - foreach ($morelogincontent as $format => $option) - { + foreach ($morelogincontent as $format => $option) { if ($format == 'table') { echo ''; echo $option; @@ -169,10 +192,18 @@ if (!empty($morelogincontent)) {
    dol_hide_topmenu)) $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_hide_topmenu='.$conf->dol_hide_topmenu; - if (!empty($conf->dol_hide_leftmenu)) $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_hide_leftmenu='.$conf->dol_hide_leftmenu; - if (!empty($conf->dol_no_mouse_hover)) $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_no_mouse_hover='.$conf->dol_no_mouse_hover; - if (!empty($conf->dol_use_jmobile)) $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_use_jmobile='.$conf->dol_use_jmobile; + if (!empty($conf->dol_hide_topmenu)) { + $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_hide_topmenu='.$conf->dol_hide_topmenu; + } + if (!empty($conf->dol_hide_leftmenu)) { + $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_hide_leftmenu='.$conf->dol_hide_leftmenu; + } + if (!empty($conf->dol_no_mouse_hover)) { + $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_no_mouse_hover='.$conf->dol_no_mouse_hover; + } + if (!empty($conf->dol_use_jmobile)) { + $moreparam .= (strpos($moreparam, '?') === false ? '?' : '&').'dol_use_jmobile='.$conf->dol_use_jmobile; + } print ''.$langs->trans('BackToLoginPage').''; ?> @@ -210,11 +241,12 @@ if (!empty($morelogincontent)) { global->MAIN_HTML_FOOTER)) print $conf->global->MAIN_HTML_FOOTER; +if (!empty($conf->global->MAIN_HTML_FOOTER)) { + print $conf->global->MAIN_HTML_FOOTER; +} if (!empty($morelogincontent) && is_array($morelogincontent)) { - foreach ($morelogincontent as $format => $option) - { + foreach ($morelogincontent as $format => $option) { if ($format == 'js') { echo "\n".''; echo $option."\n"; @@ -227,8 +259,7 @@ if (!empty($morelogincontent) && is_array($morelogincontent)) { // Google Analytics // TODO Add a hook here -if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) -{ +if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) { $tmptagarray = explode(',', $conf->global->MAIN_GOOGLE_AN_ID); foreach ($tmptagarray as $tmptag) { print "\n"; @@ -249,10 +280,8 @@ if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AN_ID)) // TODO Replace this with a hook // Google Adsense (need Google module) -if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) -{ - if (empty($conf->dol_use_jmobile)) - { +if (!empty($conf->google->enabled) && !empty($conf->global->MAIN_GOOGLE_AD_CLIENT) && !empty($conf->global->MAIN_GOOGLE_AD_SLOT)) { + if (empty($conf->dol_use_jmobile)) { ?>

    '; + '; print ''; print dol_get_fiche_end(); - } // end edit or not edit - } // end of if result - else { + } + } else { dol_print_error($db); } - } //fin si id > 0 + } } /* @@ -2532,8 +2490,7 @@ if ($action == 'create') print '
    '; -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { $object = new ExpenseReport($db); $object->fetch($id, $ref); @@ -2552,16 +2509,13 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_author == user courant * Afficher : "Enregistrer" / "Modifier" / "Supprimer" */ - if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_DRAFT) - { - if (in_array($object->fk_user_author, $user->getAllChildIds(1)) || !empty($user->rights->expensereport->writeall_advance)) - { + if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_DRAFT) { + if (in_array($object->fk_user_author, $user->getAllChildIds(1)) || !empty($user->rights->expensereport->writeall_advance)) { // Modify print ''; // Validate - if (count($object->lines) > 0) - { + if (count($object->lines) > 0) { print ''; } } @@ -2572,10 +2526,8 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_author == user courant * Afficher : "Enregistrer" / "Modifier" / "Supprimer" */ - if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_REFUSED) - { - if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) - { + if ($user->rights->expensereport->creer && $object->status == ExpenseReport::STATUS_REFUSED) { + if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) { // Modify print ''; @@ -2586,10 +2538,8 @@ if ($action != 'create' && $action != 'edit') } } - if ($user->rights->expensereport->to_paid && $object->status == ExpenseReport::STATUS_APPROVED) - { - if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) - { + if ($user->rights->expensereport->to_paid && $object->status == ExpenseReport::STATUS_APPROVED) { + if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) { // setdraft print ''; } @@ -2600,17 +2550,14 @@ if ($action != 'create' && $action != 'edit') * ET fk_user_validator == user courant * Afficher : "Valider" / "Refuser" / "Supprimer" */ - if ($object->status == ExpenseReport::STATUS_VALIDATED) - { - if (in_array($object->fk_user_author, $user->getAllChildIds(1))) - { + if ($object->status == ExpenseReport::STATUS_VALIDATED) { + if (in_array($object->fk_user_author, $user->getAllChildIds(1))) { // set draft print ''; } } - if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_VALIDATED) - { + if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_VALIDATED) { //if($object->fk_user_validator==$user->id) //{ // Validate @@ -2619,8 +2566,7 @@ if ($action != 'create' && $action != 'edit') print ''; //} - if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) - { + if ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) { // Cancel print ''; } @@ -2630,17 +2576,14 @@ if ($action != 'create' && $action != 'edit') // If status is Approved // --------------------- - if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_APPROVED) - { + if ($user->rights->expensereport->approve && $object->status == ExpenseReport::STATUS_APPROVED) { print ''; } // If bank module is used - if ($user->rights->expensereport->to_paid && !empty($conf->banque->enabled) && $object->status == ExpenseReport::STATUS_APPROVED) - { + if ($user->rights->expensereport->to_paid && !empty($conf->banque->enabled) && $object->status == ExpenseReport::STATUS_APPROVED) { // Pay - if ($remaintopay == 0) - { + if ($remaintopay == 0) { print '
    '.$langs->trans('DoPayment').'
    '; } else { print ''; @@ -2648,30 +2591,25 @@ if ($action != 'create' && $action != 'edit') } // If bank module is not used - if (($user->rights->expensereport->to_paid || empty($conf->banque->enabled)) && $object->status == ExpenseReport::STATUS_APPROVED) - { + if (($user->rights->expensereport->to_paid || empty($conf->banque->enabled)) && $object->status == ExpenseReport::STATUS_APPROVED) { //if ((round($remaintopay) == 0 || empty($conf->banque->enabled)) && $object->paid == 0) - if ($object->paid == 0) - { + if ($object->paid == 0) { print '"; } } - if ($user->rights->expensereport->creer && ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) && $object->status == ExpenseReport::STATUS_APPROVED) - { - // Cancel - print ''; - } - - // TODO Replace this. It should be SetUnpaid and should go back to status unpaid not canceled. - if (($user->rights->expensereport->approve || $user->rights->expensereport->to_paid) && $object->status == ExpenseReport::STATUS_CLOSED) - { + if ($user->rights->expensereport->creer && ($user->id == $object->fk_user_author || $user->id == $object->fk_user_valid) && $object->status == ExpenseReport::STATUS_APPROVED) { // Cancel print ''; } - if ($user->rights->expensereport->to_paid && $object->paid && $object->status == ExpenseReport::STATUS_CLOSED) - { + // TODO Replace this. It should be SetUnpaid and should go back to status unpaid not canceled. + if (($user->rights->expensereport->approve || $user->rights->expensereport->to_paid) && $object->status == ExpenseReport::STATUS_CLOSED) { + // Cancel + print ''; + } + + if ($user->rights->expensereport->to_paid && $object->paid && $object->status == ExpenseReport::STATUS_CLOSED) { // Set unpaid print ''; } @@ -2682,12 +2620,10 @@ if ($action != 'create' && $action != 'edit') } /* If draft, validated, cancel, and user can create, he can always delete its card before it is approved */ - if ($user->rights->expensereport->creer && $user->id == $object->fk_user_author && $object->status < ExpenseReport::STATUS_APPROVED) - { + if ($user->rights->expensereport->creer && $user->id == $object->fk_user_author && $object->status < ExpenseReport::STATUS_APPROVED) { // Delete print ''; - } elseif ($user->rights->expensereport->supprimer && $object->status != ExpenseReport::STATUS_CLOSED) - { + } elseif ($user->rights->expensereport->supprimer && $object->status != ExpenseReport::STATUS_CLOSED) { // Delete print ''; } @@ -2704,8 +2640,7 @@ if (GETPOST('modelselected', 'alpha')) { $action = 'presend'; } -if ($action != 'presend') -{ +if ($action != 'presend') { /* * Generate documents */ @@ -2713,8 +2648,7 @@ if ($action != 'presend') print '
    '; print ''; // ancre - if ($user->rights->expensereport->creer && $action != 'create' && $action != 'edit') - { + if ($user->rights->expensereport->creer && $action != 'create' && $action != 'edit') { $filename = dol_sanitizeFileName($object->ref); $filedir = $conf->expensereport->dir_output."/".dol_sanitizeFileName($object->ref); $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; @@ -2732,7 +2666,7 @@ if ($action != 'presend') $linktoelem = $form->showLinkToObjectBlock($object, null, array('expensereport')); $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); } - */ + */ print '
    '; // List of actions on element diff --git a/htdocs/expensereport/class/api_expensereports.class.php b/htdocs/expensereport/class/api_expensereports.class.php index aa892e50fc0..98da4534e0c 100644 --- a/htdocs/expensereport/class/api_expensereports.class.php +++ b/htdocs/expensereport/class/api_expensereports.class.php @@ -33,7 +33,7 @@ class ExpenseReports extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'fk_user_author' ); @@ -107,11 +107,12 @@ class ExpenseReports extends DolibarrApi $sql = "SELECT t.rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as t"; $sql .= ' WHERE t.entity IN ('.getEntity('expensereport').')'; - if ($user_ids) $sql .= " AND t.fk_user_author IN (".$user_ids.")"; + if ($user_ids) { + $sql .= " AND t.fk_user_author IN (".$user_ids.")"; + } // Add sql filters - if ($sqlfilters) - { + if ($sqlfilters) { if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } @@ -131,13 +132,11 @@ class ExpenseReports extends DolibarrApi $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $expensereport_static = new ExpenseReport($this->db); if ($expensereport_static->fetch($obj->rowid)) { @@ -172,12 +171,12 @@ class ExpenseReports extends DolibarrApi $this->expensereport->$field = $value; } /*if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->expensereport->lines = $lines; - }*/ + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->expensereport->lines = $lines; + }*/ if ($this->expensereport->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating expensereport", array_merge(array($this->expensereport->error), $this->expensereport->errors)); } @@ -195,28 +194,28 @@ class ExpenseReports extends DolibarrApi * @return int */ /* - public function getLines($id) - { - if(! DolibarrApiAccess::$user->rights->expensereport->lire) { - throw new RestException(401); - } + public function getLines($id) + { + if(! DolibarrApiAccess::$user->rights->expensereport->lire) { + throw new RestException(401); + } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->expensereport->getLinesArray(); - $result = array(); - foreach ($this->expensereport->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - */ + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->expensereport->getLinesArray(); + $result = array(); + foreach ($this->expensereport->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + */ /** * Add a line to given Expense Report @@ -229,56 +228,56 @@ class ExpenseReports extends DolibarrApi * @return int */ /* - public function postLine($id, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } + public function postLine($id, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->expensereport->addline( - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - $request_data->fk_product, - $request_data->remise_percent, - $request_data->info_bits, - $request_data->fk_remise_except, - 'HT', - 0, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->rang, - $request_data->special_code, - $fk_parent_line, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->array_options, - $request_data->fk_unit, - $this->element, - $request_data->id - ); + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->expensereport->addline( + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + $request_data->fk_product, + $request_data->remise_percent, + $request_data->info_bits, + $request_data->fk_remise_except, + 'HT', + 0, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->rang, + $request_data->special_code, + $fk_parent_line, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->array_options, + $request_data->fk_unit, + $this->element, + $request_data->id + ); - if ($updateRes > 0) { - return $updateRes; + if ($updateRes > 0) { + return $updateRes; - } - return false; - } - */ + } + return false; + } + */ /** * Update a line to given Expense Report @@ -292,53 +291,53 @@ class ExpenseReports extends DolibarrApi * @return object */ /* - public function putLine($id, $lineid, $request_data = null) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } + public function putLine($id, $lineid, $request_data = null) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $request_data = (object) $request_data; - $updateRes = $this->expensereport->updateline( - $lineid, - $request_data->desc, - $request_data->subprice, - $request_data->qty, - $request_data->remise_percent, - $request_data->tva_tx, - $request_data->localtax1_tx, - $request_data->localtax2_tx, - 'HT', - $request_data->info_bits, - $request_data->date_start, - $request_data->date_end, - $request_data->product_type, - $request_data->fk_parent_line, - 0, - $request_data->fk_fournprice, - $request_data->pa_ht, - $request_data->label, - $request_data->special_code, - $request_data->array_options, - $request_data->fk_unit - ); + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $request_data = (object) $request_data; + $updateRes = $this->expensereport->updateline( + $lineid, + $request_data->desc, + $request_data->subprice, + $request_data->qty, + $request_data->remise_percent, + $request_data->tva_tx, + $request_data->localtax1_tx, + $request_data->localtax2_tx, + 'HT', + $request_data->info_bits, + $request_data->date_start, + $request_data->date_end, + $request_data->product_type, + $request_data->fk_parent_line, + 0, + $request_data->fk_fournprice, + $request_data->pa_ht, + $request_data->label, + $request_data->special_code, + $request_data->array_options, + $request_data->fk_unit + ); - if ($updateRes > 0) { - $result = $this->get($id); - unset($result->line); - return $this->_cleanObjectDatas($result); - } - return false; - } - */ + if ($updateRes > 0) { + $result = $this->get($id); + unset($result->line); + return $this->_cleanObjectDatas($result); + } + return false; + } + */ /** * Delete a line of given Expense Report @@ -351,30 +350,30 @@ class ExpenseReports extends DolibarrApi * @return int */ /* - public function deleteLine($id, $lineid) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } + public function deleteLine($id, $lineid) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - // TODO Check the lineid $lineid is a line of ojbect + // TODO Check the lineid $lineid is a line of ojbect - $updateRes = $this->expensereport->deleteline($lineid); - if ($updateRes == 1) { - return $this->get($id); - } - return false; - } - */ + $updateRes = $this->expensereport->deleteline($lineid); + if ($updateRes == 1) { + return $this->get($id); + } + return false; + } + */ /** * Update Expense Report general fields (won't touch lines of expensereport) @@ -403,12 +402,13 @@ class ExpenseReports extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->expensereport->$field = $value; } - if ($this->expensereport->update(DolibarrApiAccess::$user) > 0) - { + if ($this->expensereport->update(DolibarrApiAccess::$user) > 0) { return $this->get($id); } else { throw new RestException(500, $this->expensereport->error); @@ -464,31 +464,31 @@ class ExpenseReports extends DolibarrApi * } */ /* - public function validate($id, $idwarehouse=0) - { - if(! DolibarrApiAccess::$user->rights->expensereport->creer) { - throw new RestException(401); - } - $result = $this->expensereport->fetch($id); - if( ! $result ) { - throw new RestException(404, 'expensereport not found'); - } + public function validate($id, $idwarehouse=0) + { + if(! DolibarrApiAccess::$user->rights->expensereport->creer) { + throw new RestException(401); + } + $result = $this->expensereport->fetch($id); + if( ! $result ) { + throw new RestException(404, 'expensereport not found'); + } - if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } + if( ! DolibarrApi::_checkAccessToResource('expensereport',$this->expensereport->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } - if( ! $this->expensereport->valid(DolibarrApiAccess::$user, $idwarehouse)) { - throw new RestException(500, 'Error when validate expensereport'); - } + if( ! $this->expensereport->valid(DolibarrApiAccess::$user, $idwarehouse)) { + throw new RestException(500, 'Error when validate expensereport'); + } - return array( - 'success' => array( - 'code' => 200, - 'message' => 'expensereport validated' - ) - ); - }*/ + return array( + 'success' => array( + 'code' => 200, + 'message' => 'expensereport validated' + ) + ); + }*/ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore /** @@ -555,8 +555,9 @@ class ExpenseReports extends DolibarrApi { $expensereport = array(); foreach (ExpenseReports::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $expensereport[$field] = $data[$field]; } return $expensereport; diff --git a/htdocs/expensereport/class/expensereport.class.php b/htdocs/expensereport/class/expensereport.class.php index cdc4fe4da5d..f95302cdba2 100644 --- a/htdocs/expensereport/class/expensereport.class.php +++ b/htdocs/expensereport/class/expensereport.class.php @@ -237,14 +237,15 @@ class ExpenseReport extends CommonObject $error = 0; // Check parameters - if (empty($this->date_debut) || empty($this->date_fin)) - { + if (empty($this->date_debut) || empty($this->date_fin)) { $this->error = $langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Date')); return -1; } $fuserid = $this->fk_user_author; // Note fk_user_author is not the 'author' but the guy the expense report is for. - if (empty($fuserid)) $fuserid = $user->id; + if (empty($fuserid)) { + $fuserid = $user->id; + } $this->db->begin(); @@ -289,25 +290,20 @@ class ExpenseReport extends CommonObject $sql .= ")"; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->ref = '(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element." SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $error++; } - if (!$error) - { - if (is_array($this->lines) && count($this->lines) > 0) - { - foreach ($this->lines as $line) - { + if (!$error) { + if (is_array($this->lines) && count($this->lines) > 0) { + foreach ($this->lines as $line) { // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. if (!is_object($line)) { @@ -334,8 +330,7 @@ class ExpenseReport extends CommonObject //$newndfline=new ExpenseReportLine($this->db); $newndfline->fk_expensereport = $this->id; $result = $newndfline->insert(); - if ($result < 0) - { + if ($result < 0) { $this->error = $newndfline->error; $this->errors = $newndfline->errors; $error++; @@ -345,19 +340,17 @@ class ExpenseReport extends CommonObject } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { $result = $this->update_price(); - if ($result > 0) - { - if (!$notrigger) - { + if ($result > 0) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_CREATE', $user); @@ -367,8 +360,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return $this->id; } else { @@ -405,7 +397,9 @@ class ExpenseReport extends CommonObject $error = 0; - if (empty($fk_user_author)) $fk_user_author = $user->id; + if (empty($fk_user_author)) { + $fk_user_author = $user->id; + } $this->db->begin(); @@ -430,10 +424,8 @@ class ExpenseReport extends CommonObject $this->date_validation = ''; // Remove link on lines to a joined file - if (is_array($this->lines) && count($this->lines) > 0) - { - foreach ($this->lines as $key => $line) - { + if (is_array($this->lines) && count($this->lines) > 0) { + foreach ($this->lines as $key => $line) { $this->lines[$key]->fk_ecm_files = 0; } } @@ -441,25 +433,26 @@ class ExpenseReport extends CommonObject // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$objFrom); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($this->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -490,8 +483,7 @@ class ExpenseReport extends CommonObject $sql .= " , total_tva = ".$this->total_tva; $sql .= " , date_debut = '".$this->db->idate($this->date_debut)."'"; $sql .= " , date_fin = '".$this->db->idate($this->date_fin)."'"; - if ($userofexpensereport && is_object($userofexpensereport)) - { + if ($userofexpensereport && is_object($userofexpensereport)) { $sql .= " , fk_user_author = ".($userofexpensereport->id > 0 ? $userofexpensereport->id : "null"); // Note fk_user_author is not the 'author' but the guy the expense report is for. } $sql .= " , fk_user_validator = ".($this->fk_user_validator > 0 ? $this->fk_user_validator : "null"); @@ -507,10 +499,8 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::update sql=".$sql, LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if (!$notrigger) - { + if ($result) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_UPDATE', $user); @@ -520,8 +510,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -556,17 +545,18 @@ class ExpenseReport extends CommonObject $sql .= " d.fk_user_valid, d.fk_user_approve,"; $sql .= " d.fk_statut as status, d.fk_c_paiement, d.paid"; $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as d"; - if ($ref) $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'"; - else $sql .= " WHERE d.rowid = ".$id; + if ($ref) { + $sql .= " WHERE d.ref = '".$this->db->escape($ref)."'"; + } else { + $sql .= " WHERE d.rowid = ".$id; + } //$sql.= $restrict; dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $this->id = $obj->rowid; $this->ref = $obj->ref; @@ -599,13 +589,18 @@ class ExpenseReport extends CommonObject $this->fk_user_approve = $obj->fk_user_approve; $user_author = new User($this->db); - if ($this->fk_user_author > 0) $user_author->fetch($this->fk_user_author); + if ($this->fk_user_author > 0) { + $user_author->fetch($this->fk_user_author); + } $this->user_author_infos = dolGetFirstLastname($user_author->firstname, $user_author->lastname); $user_approver = new User($this->db); - if ($this->fk_user_approve > 0) $user_approver->fetch($this->fk_user_approve); - elseif ($this->fk_user_validator > 0) $user_approver->fetch($this->fk_user_validator); // For backward compatibility + if ($this->fk_user_approve > 0) { + $user_approver->fetch($this->fk_user_approve); + } elseif ($this->fk_user_validator > 0) { + $user_approver->fetch($this->fk_user_validator); // For backward compatibility + } $this->user_validator_infos = dolGetFirstLastname($user_approver->firstname, $user_approver->lastname); $this->fk_statut = $obj->status; // deprecated @@ -613,10 +608,11 @@ class ExpenseReport extends CommonObject $this->fk_c_paiement = $obj->fk_c_paiement; $this->paid = $obj->paid; - if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED) - { + if ($this->status == self::STATUS_APPROVED || $this->status == self::STATUS_CLOSED) { $user_valid = new User($this->db); - if ($this->fk_user_valid > 0) $user_valid->fetch($this->fk_user_valid); + if ($this->fk_user_valid > 0) { + $user_valid->fetch($this->fk_user_valid); + } $this->user_valid_infos = dolGetFirstLastname($user_valid->firstname, $user_valid->lastname); } @@ -671,12 +667,9 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::set_paid sql=".$sql, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->affected_rows($resql)) - { - if (!$notrigger) - { + if ($resql) { + if ($this->db->affected_rows($resql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_PAID', $fuser); @@ -686,8 +679,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -763,10 +755,8 @@ class ExpenseReport extends CommonObject $sql .= " AND f.entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -780,26 +770,22 @@ class ExpenseReport extends CommonObject $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; - if ($obj->fk_user_creation) - { + if ($obj->fk_user_creation) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_creation); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_modification) - { + if ($obj->fk_user_modification) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modification); $this->user_modification = $muser; } - if ($obj->fk_user_approve) - { + if ($obj->fk_user_approve) { $auser = new User($this->db); $auser->fetch($obj->fk_user_approve); $this->user_approve = $auser; @@ -898,15 +884,13 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; $total_HT = 0; $total_TTC = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $sql2 = "SELECT d.rowid, d.fk_user_author, d.ref, d.fk_statut as status"; @@ -953,13 +937,13 @@ class ExpenseReport extends CommonObject break; } /* - if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5'); - if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); - if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1'); - if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3'); - if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); - if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6'); - */ + if ($status==4) return img_picto($langs->trans('StatusOrderCanceled'),'statut5'); + if ($status==1) return img_picto($langs->trans('StatusOrderDraft'),'statut0'); + if ($status==2) return img_picto($langs->trans('StatusOrderValidated'),'statut1'); + if ($status==2) return img_picto($langs->trans('StatusOrderOnProcess'),'statut3'); + if ($status==5) return img_picto($langs->trans('StatusOrderToBill'),'statut4'); + if ($status==6) return img_picto($langs->trans('StatusOrderOnProcess'),'statut6'); + */ print ''; print '
    '; @@ -994,11 +978,10 @@ class ExpenseReport extends CommonObject $total_ht = 0; $total_tva = 0; $total_ttc = 0; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num): + while ($i < $num) : $objp = $this->db->fetch_object($result); $total_ht += $objp->total_ht; $total_tva += $objp->total_tva; @@ -1012,7 +995,7 @@ class ExpenseReport extends CommonObject $sql .= " , total_tva = ".$total_tva; $sql .= " WHERE rowid = ".$id; $result = $this->db->query($sql); - if ($result): + if ($result) : $this->db->free($result); return 1; else : @@ -1049,20 +1032,17 @@ class ExpenseReport extends CommonObject $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_type_fees as ctf ON de.fk_c_type_fees = ctf.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'projet as p ON de.fk_projet = p.rowid'; $sql .= ' WHERE de.'.$this->fk_element.' = '.$this->id; - if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID)) - { + if (!empty($conf->global->EXPENSEREPORT_LINES_SORTED_BY_ROWID)) { $sql .= ' ORDER BY de.rang ASC, de.rowid ASC'; } else { $sql .= ' ORDER BY de.rang ASC, de.date ASC'; } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($resql); $deplig = new ExpenseReportLine($this->db); @@ -1128,7 +1108,9 @@ class ExpenseReport extends CommonObject if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSEREPORT_DELETE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -1148,13 +1130,17 @@ class ExpenseReport extends CommonObject if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } if (!$error) { // Delete linked contacts $res = $this->delete_linked_contact(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } // Removed extrafields of object @@ -1239,8 +1225,7 @@ class ExpenseReport extends CommonObject $now = dol_now(); // Protection - if ($this->status == self::STATUS_VALIDATED) - { + if ($this->status == self::STATUS_VALIDATED) { dol_syslog(get_class($this)."::valid action abandonned: already validated", LOG_WARNING); return 0; } @@ -1248,13 +1233,14 @@ class ExpenseReport extends CommonObject $this->date_valid = $now; // Required for the getNextNum later. // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef(); } else { $num = $this->ref; } - if (empty($num) || $num < 0) return -1; + if (empty($num) || $num < 0) { + return -1; + } $this->newref = dol_sanitizeFileName($num); @@ -1269,10 +1255,8 @@ class ExpenseReport extends CommonObject $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { - if (!$error && !$notrigger) - { + if ($resql) { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_VALIDATE', $fuser); if ($result < 0) { @@ -1281,37 +1265,34 @@ class ExpenseReport extends CommonObject // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'expensereport/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'expensereport/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->expensereport->dir_output.'/'.$oldref; $dirdest = $conf->expensereport->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::setValidate() rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->expensereport->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -1324,14 +1305,12 @@ class ExpenseReport extends CommonObject } // Set new ref and current status - if (!$error) - { + if (!$error) { $this->ref = $num; $this->status = self::STATUS_VALIDATED; } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1369,16 +1348,14 @@ class ExpenseReport extends CommonObject $this->date_debut = $this->db->jdate($objp->date_debut); - if ($this->status != self::STATUS_VALIDATED) - { + if ($this->status != self::STATUS_VALIDATED) { $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET fk_statut = ".self::STATUS_VALIDATED; $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::set_save_from_refuse sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { return 1; } else { $this->error = $this->db->lasterror(); @@ -1403,18 +1380,15 @@ class ExpenseReport extends CommonObject // date approval $this->date_approve = $now; - if ($this->status != self::STATUS_APPROVED) - { + if ($this->status != self::STATUS_APPROVED) { $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_APPROVED.", fk_user_approve = ".$fuser->id.","; $sql .= " date_approve='".$this->db->idate($this->date_approve)."'"; $sql .= ' WHERE rowid = '.$this->id; - if ($this->db->query($sql)) - { - if (!$notrigger) - { + if ($this->db->query($sql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_APPROVE', $fuser); @@ -1424,8 +1398,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1459,24 +1432,21 @@ class ExpenseReport extends CommonObject $error = 0; // date de refus - if ($this->status != self::STATUS_REFUSED) - { + if ($this->status != self::STATUS_REFUSED) { $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET ref = '".$this->db->escape($this->ref)."', fk_statut = ".self::STATUS_REFUSED.", fk_user_refuse = ".$fuser->id.","; $sql .= " date_refuse='".$this->db->idate($now)."',"; $sql .= " detail_refuse='".$this->db->escape($details)."',"; $sql .= " fk_user_approve = NULL"; $sql .= ' WHERE rowid = '.$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->fk_statut = 99; // deprecated $this->status = 99; $this->fk_user_refuse = $fuser->id; $this->detail_refuse = $details; $this->date_refuse = $now; - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_DENY', $fuser); @@ -1486,8 +1456,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1533,8 +1502,7 @@ class ExpenseReport extends CommonObject { $error = 0; - if ($this->paid) - { + if ($this->paid) { $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; @@ -1543,10 +1511,8 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::set_unpaid sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { - if (!$notrigger) - { + if ($this->db->query($sql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_UNPAID', $fuser); @@ -1556,8 +1522,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1589,8 +1554,7 @@ class ExpenseReport extends CommonObject // phpcs:enable $error = 0; $this->date_cancel = $this->db->idate(dol_now()); - if ($this->status != self::STATUS_CANCELED) - { + if ($this->status != self::STATUS_CANCELED) { $this->db->begin(); $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; @@ -1601,10 +1565,8 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::set_cancel sql=".$sql, LOG_DEBUG); - if ($this->db->query($sql)) - { - if (!$notrigger) - { + if ($this->db->query($sql)) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('EXPENSE_REPORT_CANCEL', $fuser); @@ -1614,8 +1576,7 @@ class ExpenseReport extends CommonObject // End call triggers } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return 1; } else { @@ -1643,8 +1604,7 @@ class ExpenseReport extends CommonObject global $langs, $conf; $langs->load("trips"); - if (!empty($conf->global->EXPENSEREPORT_ADDON)) - { + if (!empty($conf->global->EXPENSEREPORT_ADDON)) { $mybool = false; $file = $conf->global->EXPENSEREPORT_ADDON.".php"; @@ -1652,8 +1612,7 @@ class ExpenseReport extends CommonObject // Include file with class $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']); - foreach ($dirmodels as $reldir) - { + foreach ($dirmodels as $reldir) { $dir = dol_buildpath($reldir."core/modules/expensereport/"); // Load file with numbering class (if found) @@ -1668,8 +1627,7 @@ class ExpenseReport extends CommonObject $obj = new $classname(); $numref = $obj->getNextValue($this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -1702,38 +1660,50 @@ class ExpenseReport extends CommonObject $url = DOL_URL_ROOT.'/expensereport/card.php?id='.$this->id; - if ($short) return $url; + if ($short) { + return $url; + } $label = img_picto('', $this->picto).' '.$langs->trans("ExpenseReport").''; if (isset($this->status)) { $label .= ' '.$this->getLibStatut(5); } - if (!empty($this->ref)) + if (!empty($this->ref)) { $label .= '
    '.$langs->trans('Ref').': '.$this->ref; - if (!empty($this->total_ht)) + } + 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)) + } + if (!empty($this->total_tva)) { $label .= '
    '.$langs->trans('VAT').': '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_ttc)) + } + if (!empty($this->total_ttc)) { $label .= '
    '.$langs->trans('AmountTTC').': '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($moretitle) $label .= ' - '.$moretitle; + } + if ($moretitle) { + $label .= ' - '.$moretitle; + } //if ($option != 'nolink') //{ // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } //} $ref = $this->ref; - if (empty($ref)) $ref = $this->id; + if (empty($ref)) { + $ref = $this->id; + } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowExpenseReport"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -1746,8 +1716,12 @@ class ExpenseReport extends CommonObject $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($max ?dol_trunc($ref, $max) : $ref); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= ($max ?dol_trunc($ref, $max) : $ref); + } $result .= $linkend; return $result; @@ -1775,7 +1749,7 @@ class ExpenseReport extends CommonObject $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if ($result): + if ($result) : return 1; else : $this->error = $this->db->error(); @@ -1805,7 +1779,7 @@ class ExpenseReport extends CommonObject $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if ($result): + if ($result) : return 1; else : $this->error = $this->db->error(); @@ -1834,14 +1808,25 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::addline qty=$qty, up=$up, fk_c_type_fees=$fk_c_type_fees, vatrate=$vatrate, date=$date, fk_project=$fk_project, type=$type, comments=$comments", LOG_DEBUG); - if ($this->status == self::STATUS_DRAFT) - { - if (empty($qty)) $qty = 0; - if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) $fk_c_type_fees = 0; - if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) $fk_c_exp_tax_cat = 0; - if (empty($vatrate) || $vatrate < 0) $vatrate = 0; - if (empty($date)) $date = ''; - if (empty($fk_project)) $fk_project = 0; + if ($this->status == self::STATUS_DRAFT) { + if (empty($qty)) { + $qty = 0; + } + if (empty($fk_c_type_fees) || $fk_c_type_fees < 0) { + $fk_c_type_fees = 0; + } + if (empty($fk_c_exp_tax_cat) || $fk_c_exp_tax_cat < 0) { + $fk_c_exp_tax_cat = 0; + } + if (empty($vatrate) || $vatrate < 0) { + $vatrate = 0; + } + if (empty($date)) { + $date = ''; + } + if (empty($fk_project)) { + $fk_project = 0; + } $qty = price2num($qty); if (!preg_match('/\s*\((.*)\)/', $vatrate)) { @@ -1857,8 +1842,7 @@ class ExpenseReport extends CommonObject $vat_src_code = ''; $reg = array(); - if (preg_match('/\s*\((.*)\)/', $vatrate, $reg)) - { + if (preg_match('/\s*\((.*)\)/', $vatrate, $reg)) { $vat_src_code = $reg[1]; $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. } @@ -1890,11 +1874,9 @@ class ExpenseReport extends CommonObject $this->checkRules($type, $seller); $result = $this->line->insert(0, true); - if ($result > 0) - { + if ($result > 0) { $result = $this->update_price(); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->line->id; } else { @@ -1927,7 +1909,9 @@ class ExpenseReport extends CommonObject $langs->load('trips'); - if (empty($conf->global->MAIN_USE_EXPENSE_RULE)) return true; // if don't use rules + if (empty($conf->global->MAIN_USE_EXPENSE_RULE)) { + return true; // if don't use rules + } $rulestocheck = ExpenseReportRule::getAllRule($this->line->fk_c_type_fees, $this->line->date, $this->fk_user_author); @@ -1938,19 +1922,19 @@ class ExpenseReport extends CommonObject $new_current_total_ttc = $this->line->total_ttc; // check if one is violated - foreach ($rulestocheck as $rule) - { - if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type); - else $amount_to_test = $current_total_ttc; // EX_EXP + foreach ($rulestocheck as $rule) { + if (in_array($rule->code_expense_rules_type, array('EX_DAY', 'EX_MON', 'EX_YEA'))) { + $amount_to_test = $this->line->getExpAmount($rule, $this->fk_user_author, $rule->code_expense_rules_type); + } else { + $amount_to_test = $current_total_ttc; // EX_EXP + } $amount_to_test = $amount_to_test - $current_total_ttc + $new_current_total_ttc; // if amount as been modified by a previous rule - if ($amount_to_test > $rule->amount) - { + if ($amount_to_test > $rule->amount) { $violation++; - if ($rule->restrictive) - { + if ($rule->restrictive) { $this->error = 'ExpenseReportConstraintViolationError'; $this->errors[] = $this->error; @@ -1969,8 +1953,7 @@ class ExpenseReport extends CommonObject $this->line->rule_warning_message = implode('\n', $rule_warning_message_tab); - if ($violation > 0) - { + if ($violation > 0) { $tmp = calcul_price_total($this->line->qty, $new_current_total_ttc / $this->line->qty, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller); $this->line->value_unit = $tmp[5]; @@ -1979,7 +1962,9 @@ class ExpenseReport extends CommonObject $this->line->total_tva = $tmp[1]; return false; - } else return true; + } else { + return true; + } } /** @@ -1991,11 +1976,12 @@ class ExpenseReport extends CommonObject { global $conf; - if (empty($conf->global->MAIN_USE_EXPENSE_IK)) return false; + if (empty($conf->global->MAIN_USE_EXPENSE_IK)) { + return false; + } $userauthor = new User($this->db); - if ($userauthor->fetch($this->fk_user_author) <= 0) - { + if ($userauthor->fetch($this->fk_user_author) <= 0) { $this->error = 'ErrorCantFetchUser'; $this->errors[] = 'ErrorCantFetchUser'; return false; @@ -2003,19 +1989,20 @@ class ExpenseReport extends CommonObject $range = ExpenseReportIk::getRangeByUser($userauthor, $this->line->fk_c_exp_tax_cat); - if (empty($range)) - { + if (empty($range)) { $this->error = 'ErrorNoRangeAvailable'; $this->errors[] = 'ErrorNoRangeAvailable'; return false; } - if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) $ikoffset = $range->ikoffset; - else $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year + if (!empty($conf->global->MAIN_EXPENSE_APPLY_ENTIRE_OFFSET)) { + $ikoffset = $range->ikoffset; + } else { + $ikoffset = $range->ikoffset / 12; // The amount of offset is a global value for the year + } // Test if ikoffset has been applied for the current month - if (!$this->offsetAlreadyGiven()) - { + if (!$this->offsetAlreadyGiven()) { $new_up = $range->coef + ($ikoffset / $this->line->qty); $tmp = calcul_price_total($this->line->qty, $new_up, 0, $this->line->vatrate, 0, 0, 0, 'TTC', 0, $type, $seller); @@ -2042,14 +2029,17 @@ class ExpenseReport extends CommonObject $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_type_fees f ON (d.fk_c_type_fees = f.id AND f.code = "EX_KME")'; $sql .= ' WHERE e.fk_user_author = '.(int) $this->fk_user_author; $sql .= ' AND YEAR(d.date) = "'.dol_print_date($this->line->date, '%Y').'" AND MONTH(d.date) = "'.dol_print_date($this->line->date, '%m').'"'; - if (!empty($this->line->id)) $sql .= ' AND d.rowid <> '.$this->line->id; + if (!empty($this->line->id)) { + $sql .= ' AND d.rowid <> '.$this->line->id; + } dol_syslog(get_class($this)."::offsetAlreadyGiven sql=".$sql); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 0) return true; + if ($num > 0) { + return true; + } } else { dol_print_error($this->db); } @@ -2077,8 +2067,7 @@ class ExpenseReport extends CommonObject { global $user, $mysoc; - if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) - { + if ($this->status == self::STATUS_DRAFT || $this->status == self::STATUS_REFUSED) { $this->db->begin(); $type = 0; // TODO What if type is service ? @@ -2092,8 +2081,7 @@ class ExpenseReport extends CommonObject // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $vatrate, $reg)) - { + if (preg_match('/\((.*)\)/', $vatrate, $reg)) { $vat_src_code = $reg[1]; $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. } @@ -2138,8 +2126,7 @@ class ExpenseReport extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."c_type_fees as c"; $sql .= " WHERE c.id = ".$type_fees_id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $objp_fees = $this->db->fetch_object($resql); $this->line->type_fees_code = $objp_fees->code_type_fees; $this->line->type_fees_libelle = $objp_fees->libelle_type_fees; @@ -2162,8 +2149,7 @@ class ExpenseReport extends CommonObject $this->checkRules(); $result = $this->line->update($user); - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return 1; } else { @@ -2191,8 +2177,7 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::deleteline sql=".$sql); $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->error = $this->db->error(); dol_syslog(get_class($this)."::deleteline Error ".$this->error, LOG_ERR); $this->db->rollback(); @@ -2225,27 +2210,30 @@ class ExpenseReport extends CommonObject if ($result) { $num_rows = $this->db->num_rows($result); $i = 0; - if ($num_rows > 0) - { + if ($num_rows > 0) { $date_d_form = $date_debut; $date_f_form = $date_fin; $existe = false; - while ($i < $num_rows) - { + while ($i < $num_rows) { $objp = $this->db->fetch_object($result); $date_d_req = $this->db->jdate($objp->date_debut); // 3 $date_f_req = $this->db->jdate($objp->date_fin); // 4 - if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) $existe = true; + if (!($date_f_form < $date_d_req || $date_d_form > $date_f_req)) { + $existe = true; + } $i++; } - if ($existe) return 1; - else return 0; + if ($existe) { + return 1; + } else { + return 0; + } } else { return 0; } @@ -2280,11 +2268,9 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::fetch_users_approver_expensereport sql=".$sql); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num_rows = $this->db->num_rows($result); $i = 0; - while ($i < $num_rows) - { + while ($i < $num_rows) { $objp = $this->db->fetch_object($result); array_push($users_validator, $objp->fk_user); $i++; @@ -2348,12 +2334,10 @@ class ExpenseReport extends CommonObject $sql .= " WHERE active = ".$active; dol_syslog(get_class($this)."::listOfTypes", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $ret[$obj->code] = (($langs->transnoentitiesnoconv($obj->code) != $obj->code) ? $langs->transnoentitiesnoconv($obj->code) : $obj->label); $i++; @@ -2381,8 +2365,7 @@ class ExpenseReport extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; $sql .= " WHERE ex.fk_statut > 0"; $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; - if (empty($user->rights->expensereport->readall)) - { + if (empty($user->rights->expensereport->readall)) { $userchildids = $user->getAllChildIds(1); $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")"; $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))"; @@ -2415,30 +2398,32 @@ class ExpenseReport extends CommonObject // phpcs:enable global $conf, $langs; - if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe + if ($user->socid) { + return -1; // protection pour eviter appel par utilisateur externe + } $now = dol_now(); $sql = "SELECT ex.rowid, ex.date_valid"; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as ex"; - if ($option == 'toapprove') $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED; - else $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED; + if ($option == 'toapprove') { + $sql .= " WHERE ex.fk_statut = ".self::STATUS_VALIDATED; + } else { + $sql .= " WHERE ex.fk_statut = ".self::STATUS_APPROVED; + } $sql .= " AND ex.entity IN (".getEntity('expensereport').")"; - if (empty($user->rights->expensereport->readall)) - { + if (empty($user->rights->expensereport->readall)) { $userchildids = $user->getAllChildIds(1); $sql .= " AND (ex.fk_user_author IN (".join(',', $userchildids).")"; $sql .= " OR ex.fk_user_validator IN (".join(',', $userchildids)."))"; } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $langs->load("trips"); $response = new WorkboardResponse(); - if ($option == 'toapprove') - { + if ($option == 'toapprove') { $response->warning_delay = $conf->expensereport->approve->warning_delay / 60 / 60 / 24; $response->label = $langs->trans("ExpenseReportsToApprove"); $response->labelShort = $langs->trans("ToApprove"); @@ -2451,12 +2436,10 @@ class ExpenseReport extends CommonObject } $response->img = img_object('', "trip"); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; - if ($option == 'toapprove') - { + if ($option == 'toapprove') { if ($this->db->jdate($obj->date_valid) < ($now - $conf->expensereport->approve->warning_delay)) { $response->nbtodolate++; } @@ -2486,8 +2469,12 @@ class ExpenseReport extends CommonObject global $conf; // Only valid expenses reports - if ($option == 'toapprove' && $this->status != 2) return false; - if ($option == 'topay' && $this->status != 5) return false; + if ($option == 'toapprove' && $this->status != 2) { + return false; + } + if ($option == 'topay' && $this->status != 5) { + return false; + } $now = dol_now(); if ($option == 'toapprove') { @@ -2510,11 +2497,9 @@ class ExpenseReport extends CommonObject $sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$this->db->escape($type)."' AND ab.fk_doc = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $alreadydispatched = $obj->nb; } } else { @@ -2522,8 +2507,7 @@ class ExpenseReport extends CommonObject return -1; } - if ($alreadydispatched) - { + if ($alreadydispatched) { return 1; } return 0; @@ -2545,8 +2529,7 @@ class ExpenseReport extends CommonObject dol_syslog(get_class($this)."::getSumPayments", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $this->db->free($resql); return (empty($obj->amount) ? 0 : $obj->amount); @@ -2649,8 +2632,7 @@ class ExpenseReportLine $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); $this->rowid = $objp->rowid; @@ -2700,10 +2682,14 @@ class ExpenseReportLine // Clean parameters $this->comments = trim($this->comments); - if (empty($this->value_unit)) $this->value_unit = 0; + if (empty($this->value_unit)) { + $this->value_unit = 0; + } $this->qty = price2num($this->qty); $this->vatrate = price2num($this->vatrate); - if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0; + if (empty($this->fk_c_exp_tax_cat)) { + $this->fk_c_exp_tax_cat = 0; + } $this->db->begin(); @@ -2728,17 +2714,14 @@ class ExpenseReportLine $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'expensereport_det'); - if (!$fromaddline) - { + if (!$fromaddline) { $tmpparent = new ExpenseReport($this->db); $tmpparent->fetch($this->fk_expensereport); $result = $tmpparent->update_price(); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $tmpparent->error; $this->errors = $tmpparent->errors; @@ -2748,8 +2731,7 @@ class ExpenseReportLine $error++; } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -2776,20 +2758,24 @@ class ExpenseReportLine $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_det d'; $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'expensereport e ON (d.fk_expensereport = e.rowid)'; $sql .= ' WHERE e.fk_user_author = '.$fk_user; - if (!empty($this->id)) $sql .= ' AND d.rowid <> '.$this->id; + if (!empty($this->id)) { + $sql .= ' AND d.rowid <> '.$this->id; + } $sql .= ' AND d.fk_c_type_fees = '.$rule->fk_c_type_fees; - if ($mode == 'day' || $mode == 'EX_DAY') $sql .= ' AND d.date = \''.dol_print_date($this->date, '%Y-%m-%d').'\''; - elseif ($mode == 'mon' || $mode == 'EX_MON') $sql .= ' AND DATE_FORMAT(d.date, \'%Y-%m\') = \''.dol_print_date($this->date, '%Y-%m').'\''; // @todo DATE_FORMAT is forbidden - elseif ($mode == 'year' || $mode == 'EX_YEA') $sql .= ' AND DATE_FORMAT(d.date, \'%Y\') = \''.dol_print_date($this->date, '%Y').'\''; // @todo DATE_FORMAT is forbidden + if ($mode == 'day' || $mode == 'EX_DAY') { + $sql .= ' AND d.date = \''.dol_print_date($this->date, '%Y-%m-%d').'\''; + } elseif ($mode == 'mon' || $mode == 'EX_MON') { + $sql .= ' AND DATE_FORMAT(d.date, \'%Y-%m\') = \''.dol_print_date($this->date, '%Y-%m').'\''; // @todo DATE_FORMAT is forbidden + } elseif ($mode == 'year' || $mode == 'EX_YEA') { + $sql .= ' AND DATE_FORMAT(d.date, \'%Y\') = \''.dol_print_date($this->date, '%Y').'\''; // @todo DATE_FORMAT is forbidden + } dol_syslog('ExpenseReportLine::getExpAmount'); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { $obj = $this->db->fetch_object($resql); $amount = (double) $obj->total_amount; } @@ -2816,7 +2802,9 @@ class ExpenseReportLine $this->comments = trim($this->comments); $this->vatrate = price2num($this->vatrate); $this->value_unit = price2num($this->value_unit); - if (empty($this->fk_c_exp_tax_cat)) $this->fk_c_exp_tax_cat = 0; + if (empty($this->fk_c_exp_tax_cat)) { + $this->fk_c_exp_tax_cat = 0; + } $this->db->begin(); @@ -2834,24 +2822,27 @@ class ExpenseReportLine $sql .= ",rule_warning_message='".$this->db->escape($this->rule_warning_message)."'"; $sql .= ",fk_c_exp_tax_cat=".$this->db->escape($this->fk_c_exp_tax_cat); $sql .= ",fk_ecm_files=".($this->fk_ecm_files > 0 ? $this->fk_ecm_files : 'null'); - if ($this->fk_c_type_fees) $sql .= ",fk_c_type_fees=".$this->db->escape($this->fk_c_type_fees); - else $sql .= ",fk_c_type_fees=null"; - if ($this->fk_project > 0) $sql .= ",fk_projet=".$this->db->escape($this->fk_project); - else $sql .= ",fk_projet=null"; + if ($this->fk_c_type_fees) { + $sql .= ",fk_c_type_fees=".$this->db->escape($this->fk_c_type_fees); + } else { + $sql .= ",fk_c_type_fees=null"; + } + if ($this->fk_project > 0) { + $sql .= ",fk_projet=".$this->db->escape($this->fk_project); + } else { + $sql .= ",fk_projet=null"; + } $sql .= " WHERE rowid = ".$this->db->escape($this->rowid ? $this->rowid : $this->id); dol_syslog("ExpenseReportLine::update sql=".$sql); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $tmpparent = new ExpenseReport($this->db); $result = $tmpparent->fetch($this->fk_expensereport); - if ($result > 0) - { + if ($result > 0) { $result = $tmpparent->update_price(); - if ($result < 0) - { + if ($result < 0) { $error++; $this->error = $tmpparent->error; $this->errors = $tmpparent->errors; @@ -2866,8 +2857,7 @@ class ExpenseReportLine dol_print_error($this->db); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { diff --git a/htdocs/expensereport/class/expensereport_ik.class.php b/htdocs/expensereport/class/expensereport_ik.class.php index 55af1eb00ed..18a0503cdd7 100644 --- a/htdocs/expensereport/class/expensereport_ik.class.php +++ b/htdocs/expensereport/class/expensereport_ik.class.php @@ -111,15 +111,16 @@ class ExpenseReportIk extends CoreObject $sql = 'SELECT rowid, label, entity, active'; $sql .= ' FROM '.MAIN_DB_PREFIX.'c_exp_tax_cat'; $sql .= ' WHERE entity IN ('.getEntity('c_exp_tax_cat').')'; - if ($mode == 1) $sql .= ' AND active = 1'; - elseif ($mode == 2) $sql .= 'AND active = 0'; + if ($mode == 1) { + $sql .= ' AND active = 1'; + } elseif ($mode == 2) { + $sql .= 'AND active = 0'; + } dol_syslog(get_called_class().'::getTaxCategories sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $categories[$obj->rowid] = $obj; } } else { @@ -142,8 +143,11 @@ class ExpenseReportIk extends CoreObject $ranges = self::getRangesByCategory($fk_c_exp_tax_cat); // substract 1 because array start from 0 - if (empty($ranges) || !isset($ranges[$default_range - 1])) return false; - else return $ranges[$default_range - 1]; + if (empty($ranges) || !isset($ranges[$default_range - 1])) { + return false; + } else { + return $ranges[$default_range - 1]; + } } /** @@ -160,20 +164,21 @@ class ExpenseReportIk extends CoreObject $ranges = array(); $sql = 'SELECT r.rowid FROM '.MAIN_DB_PREFIX.'c_exp_tax_range r'; - if ($active) $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_exp_tax_cat c ON (r.fk_c_exp_tax_cat = c.rowid)'; + if ($active) { + $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'c_exp_tax_cat c ON (r.fk_c_exp_tax_cat = c.rowid)'; + } $sql .= ' WHERE r.fk_c_exp_tax_cat = '.$fk_c_exp_tax_cat; - if ($active) $sql .= ' AND r.active = 1 AND c.active = 1'; + if ($active) { + $sql .= ' AND r.active = 1 AND c.active = 1'; + } $sql .= ' ORDER BY r.range_ik'; dol_syslog(get_called_class().'::getRangesByCategory sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num > 0) - { - while ($obj = $db->fetch_object($resql)) - { + if ($num > 0) { + while ($obj = $db->fetch_object($resql)) { $object = new ExpenseReportIk($db); $object->fetch($obj->rowid); @@ -207,15 +212,17 @@ class ExpenseReportIk extends CoreObject dol_syslog(get_called_class().'::getAllRanges sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $ik = new ExpenseReportIk($db); - if ($obj->fk_expense_ik > 0) $ik->fetch($obj->fk_expense_ik); + if ($obj->fk_expense_ik > 0) { + $ik->fetch($obj->fk_expense_ik); + } $obj->ik = $ik; - if (!isset($ranges[$obj->fk_c_exp_tax_cat])) $ranges[$obj->fk_c_exp_tax_cat] = array('label' => $obj->label, 'active' => $obj->cat_active, 'ranges' => array()); + if (!isset($ranges[$obj->fk_c_exp_tax_cat])) { + $ranges[$obj->fk_c_exp_tax_cat] = array('label' => $obj->label, 'active' => $obj->cat_active, 'ranges' => array()); + } $ranges[$obj->fk_c_exp_tax_cat]['ranges'][] = $obj; } } else { @@ -239,14 +246,15 @@ class ExpenseReportIk extends CoreObject $sql .= ' SELECT COUNT(*) as counted'; $sql .= ' FROM '.MAIN_DB_PREFIX.'c_exp_tax_range r'; $sql .= ' WHERE r.entity IN (0, '.$conf->entity.')'; - if ($default_c_exp_tax_cat > 0) $sql .= ' AND r.fk_c_exp_tax_cat = '.$default_c_exp_tax_cat; + if ($default_c_exp_tax_cat > 0) { + $sql .= ' AND r.fk_c_exp_tax_cat = '.$default_c_exp_tax_cat; + } $sql .= ' GROUP BY r.fk_c_exp_tax_cat'; $sql .= ') as counts'; dol_syslog(get_called_class().'::getMaxRangeNumber sql='.$sql, LOG_DEBUG); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); return $obj->nbRange; } else { diff --git a/htdocs/expensereport/class/expensereport_rule.class.php b/htdocs/expensereport/class/expensereport_rule.class.php index 9a172cd7563..4e4d1009750 100644 --- a/htdocs/expensereport/class/expensereport_rule.class.php +++ b/htdocs/expensereport/class/expensereport_rule.class.php @@ -156,18 +156,15 @@ class ExpenseReportRule extends CoreObject $sql = 'SELECT er.rowid'; $sql .= ' FROM '.MAIN_DB_PREFIX.'expensereport_rules er'; $sql .= ' WHERE er.entity IN (0,'.getEntity('').')'; - if (!empty($fk_c_type_fees)) - { + if (!empty($fk_c_type_fees)) { $sql .= ' AND er.fk_c_type_fees IN (-1, '.$fk_c_type_fees.')'; } - if (!empty($date)) - { + if (!empty($date)) { $date = dol_print_date($date, '%Y-%m-%d'); $sql .= ' AND er.dates <= \''.$date.'\''; $sql .= ' AND er.datee >= \''.$date.'\''; } - if ($fk_user > 0) - { + if ($fk_user > 0) { $sql .= ' AND (er.is_for_all = 1'; $sql .= ' OR er.fk_user = '.$fk_user; $sql .= ' OR er.fk_usergroup IN (SELECT ugu.fk_usergroup FROM '.MAIN_DB_PREFIX.'usergroup_user ugu WHERE ugu.fk_user = '.$fk_user.') )'; @@ -177,13 +174,14 @@ class ExpenseReportRule extends CoreObject dol_syslog("ExpenseReportRule::getAllRule sql=".$sql); $resql = $db->query($sql); - if ($resql) - { - while ($obj = $db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $db->fetch_object($resql)) { $rule = new ExpenseReportRule($db); - if ($rule->fetch($obj->rowid) > 0) $rules[$rule->id] = $rule; - else dol_print_error($db); + if ($rule->fetch($obj->rowid) > 0) { + $rules[$rule->id] = $rule; + } else { + dol_print_error($db); + } } } else { dol_print_error($db); @@ -201,11 +199,9 @@ class ExpenseReportRule extends CoreObject { include_once DOL_DOCUMENT_ROOT.'/user/class/usergroup.class.php'; - if ($this->fk_usergroup > 0) - { + if ($this->fk_usergroup > 0) { $group = new UserGroup($this->db); - if ($group->fetch($this->fk_usergroup) > 0) - { + if ($group->fetch($this->fk_usergroup) > 0) { return $group->nom; } else { $this->error = $group->error; @@ -225,11 +221,9 @@ class ExpenseReportRule extends CoreObject { include_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; - if ($this->fk_user > 0) - { + if ($this->fk_user > 0) { $u = new User($this->db); - if ($u->fetch($this->fk_user) > 0) - { + if ($u->fetch($this->fk_user) > 0) { return dolGetFirstLastname($u->firstname, $u->lastname); } else { $this->error = $u->error; diff --git a/htdocs/expensereport/class/expensereportstats.class.php b/htdocs/expensereport/class/expensereportstats.class.php index c4167e3002f..3d627cbce8d 100644 --- a/htdocs/expensereport/class/expensereportstats.class.php +++ b/htdocs/expensereport/class/expensereportstats.class.php @@ -70,20 +70,20 @@ class ExpenseReportStats extends Stats $this->where .= ' e.entity IN ('.getEntity('expensereport').')'; //$this->where.= " AND entity = ".$conf->entity; - if ($this->socid) - { + if ($this->socid) { $this->where .= " AND e.fk_soc = ".$this->socid; } // Only me and subordinates - if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) - { + if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) { $childids = $user->getAllChildIds(); $childids[] = $user->id; $this->where .= " AND e.fk_user_author IN (".(join(',', $childids)).")"; } - if ($this->userid > 0) $this->where .= ' AND e.fk_user_author = '.$this->userid; + if ($this->userid > 0) { + $this->where .= ' AND e.fk_user_author = '.$this->userid; + } } diff --git a/htdocs/expensereport/class/paymentexpensereport.class.php b/htdocs/expensereport/class/paymentexpensereport.class.php index be8693f223e..56525e7b99c 100644 --- a/htdocs/expensereport/class/paymentexpensereport.class.php +++ b/htdocs/expensereport/class/paymentexpensereport.class.php @@ -119,19 +119,36 @@ class PaymentExpenseReport extends CommonObject } // Clean parameters - if (isset($this->fk_expensereport)) $this->fk_expensereport = trim($this->fk_expensereport); - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepayment)) $this->fk_typepayment = trim($this->fk_typepayment); - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note)) $this->note = trim($this->note); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->fk_bank)) $this->fk_bank = trim($this->fk_bank); - if (isset($this->fk_user_creat)) $this->fk_user_creat = trim($this->fk_user_creat); - if (isset($this->fk_user_modif)) $this->fk_user_modif = trim($this->fk_user_modif); + if (isset($this->fk_expensereport)) { + $this->fk_expensereport = trim($this->fk_expensereport); + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepayment)) { + $this->fk_typepayment = trim($this->fk_typepayment); + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note)) { + $this->note = trim($this->note); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->fk_bank)) { + $this->fk_bank = trim($this->fk_bank); + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = trim($this->fk_user_creat); + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = trim($this->fk_user_modif); + } $totalamount = 0; - foreach ($this->amounts as $key => $value) // How payment is dispatch - { + foreach ($this->amounts as $key => $value) { // How payment is dispatch $newvalue = price2num($value, 'MT'); $this->amounts[$key] = $newvalue; $totalamount += $newvalue; @@ -139,13 +156,14 @@ class PaymentExpenseReport extends CommonObject $totalamount = price2num($totalamount); // Check parameters - if ($totalamount == 0) return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + if ($totalamount == 0) { + return -1; // On accepte les montants negatifs pour les rejets de prelevement mais pas null + } $this->db->begin(); - if ($totalamount != 0) - { + if ($totalamount != 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_expensereport (fk_expensereport, datec, datep, amount,"; $sql .= " fk_typepayment, num_payment, note, fk_user_creat, fk_bank)"; $sql .= " VALUES ($this->fk_expensereport, '".$this->db->idate($now)."',"; @@ -156,16 +174,14 @@ class PaymentExpenseReport extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_expensereport"); } else { $error++; } } - if ($totalamount != 0 && !$error) - { + if ($totalamount != 0 && !$error) { $this->amount = $totalamount; $this->db->commit(); return $this->id; @@ -206,10 +222,8 @@ class PaymentExpenseReport extends CommonObject dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -258,14 +272,30 @@ class PaymentExpenseReport extends CommonObject // Clean parameters - if (isset($this->fk_expensereport)) $this->fk_expensereport = trim($this->fk_expensereport); - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->fk_typepayment)) $this->fk_typepayment = trim($this->fk_typepayment); - if (isset($this->num_payment)) $this->num_payment = trim($this->num_payment); - if (isset($this->note)) $this->note = trim($this->note); - if (isset($this->fk_bank)) $this->fk_bank = trim($this->fk_bank); - if (isset($this->fk_user_creat)) $this->fk_user_creat = trim($this->fk_user_creat); - if (isset($this->fk_user_modif)) $this->fk_user_modif = trim($this->fk_user_modif); + if (isset($this->fk_expensereport)) { + $this->fk_expensereport = trim($this->fk_expensereport); + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->fk_typepayment)) { + $this->fk_typepayment = trim($this->fk_typepayment); + } + if (isset($this->num_payment)) { + $this->num_payment = trim($this->num_payment); + } + if (isset($this->note)) { + $this->note = trim($this->note); + } + if (isset($this->fk_bank)) { + $this->fk_bank = trim($this->fk_bank); + } + if (isset($this->fk_user_creat)) { + $this->fk_user_creat = trim($this->fk_user_creat); + } + if (isset($this->fk_user_modif)) { + $this->fk_user_modif = trim($this->fk_user_modif); + } // Check parameters @@ -293,13 +323,13 @@ class PaymentExpenseReport extends CommonObject dol_syslog(get_class($this)."::update", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -327,18 +357,18 @@ class PaymentExpenseReport extends CommonObject $this->db->begin(); - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url"; $sql .= " WHERE type='payment_expensereport' AND url_id=".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_expensereport"; $sql .= " WHERE rowid=".$this->id; @@ -351,10 +381,8 @@ class PaymentExpenseReport extends CommonObject } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -396,8 +424,7 @@ class PaymentExpenseReport extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $error++; } @@ -405,8 +432,7 @@ class PaymentExpenseReport extends CommonObject unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -487,8 +513,7 @@ class PaymentExpenseReport extends CommonObject $error = 0; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { include_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; $acc = new Account($this->db); @@ -497,7 +522,9 @@ class PaymentExpenseReport extends CommonObject //Fix me field $total = $this->amount; - if ($mode == 'payment_expensereport') $amount = $total; + if ($mode == 'payment_expensereport') { + $amount = $total; + } // Insert payment into llx_bank $bank_line_id = $acc->addline( @@ -514,35 +541,30 @@ class PaymentExpenseReport extends CommonObject // Update fk_bank in llx_paiement. // On connait ainsi le paiement qui a genere l'ecriture bancaire - if ($bank_line_id > 0) - { + if ($bank_line_id > 0) { $result = $this->update_fk_bank($bank_line_id); - if ($result <= 0) - { + if ($result <= 0) { $error++; dol_print_error($this->db); } // Add link 'payment', 'payment_supplier', 'payment_expensereport' in bank_url between payment and bank transaction $url = ''; - if ($mode == 'payment_expensereport') $url = DOL_URL_ROOT.'/expensereport/payment/card.php?rowid='; - if ($url) - { + if ($mode == 'payment_expensereport') { + $url = DOL_URL_ROOT.'/expensereport/payment/card.php?rowid='; + } + if ($url) { $result = $acc->add_url_line($bank_line_id, $this->id, $url, '(paiement)', $mode); - if ($result <= 0) - { + if ($result <= 0) { $error++; dol_print_error($this->db); } } // Add link 'user' in bank_url between user and bank transaction - if (!$error) - { - foreach ($this->amounts as $key => $value) // We should have always same user but we loop in case of. - { - if ($mode == 'payment_expensereport') - { + if (!$error) { + foreach ($this->amounts as $key => $value) { // We should have always same user but we loop in case of. + if ($mode == 'payment_expensereport') { $fuser = new User($this->db); $fuser->fetch($key); @@ -553,8 +575,7 @@ class PaymentExpenseReport extends CommonObject $fuser->getFullName($langs), 'user' ); - if ($result <= 0) - { + if ($result <= 0) { $this->error = $this->db->lasterror(); dol_syslog(get_class($this).'::addPaymentToBank '.$this->error); $error++; @@ -568,8 +589,7 @@ class PaymentExpenseReport extends CommonObject } } - if (!$error) - { + if (!$error) { return 1; } else { return -1; @@ -591,8 +611,7 @@ class PaymentExpenseReport extends CommonObject dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { return 1; } else { $this->error = $this->db->error(); @@ -613,17 +632,24 @@ class PaymentExpenseReport extends CommonObject $result = ''; - if (empty($this->ref)) $this->ref = $this->label; + if (empty($this->ref)) { + $this->ref = $this->label; + } $label = $langs->trans("ShowPayment").': '.$this->ref; - if (!empty($this->id)) - { + if (!empty($this->id)) { $link = ''; $linkend = ''; - if ($withpicto) $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); - if ($withpicto && $withpicto != 2) $result .= ' '; - if ($withpicto != 2) $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + if ($withpicto) { + $result .= ($link.img_object($label, 'payment', 'class="classfortooltip"').$linkend.' '); + } + if ($withpicto && $withpicto != 2) { + $result .= ' '; + } + if ($withpicto != 2) { + $result .= $link.($maxlen ?dol_trunc($this->ref, $maxlen) : $this->ref).$linkend; + } } return $result; @@ -644,20 +670,16 @@ class PaymentExpenseReport extends CommonObject dol_syslog(get_class($this).'::info', LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_creat) - { + if ($obj->fk_user_creat) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_creat); $this->user_creation = $cuser; } - if ($obj->fk_user_modif) - { + if ($obj->fk_user_modif) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modif); $this->user_modification = $muser; diff --git a/htdocs/expensereport/document.php b/htdocs/expensereport/document.php index 55799b10589..7713745a0a3 100644 --- a/htdocs/expensereport/document.php +++ b/htdocs/expensereport/document.php @@ -45,7 +45,9 @@ $confirm = GETPOST('confirm', 'alpha'); $childids = $user->getAllChildIds(1); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); @@ -54,17 +56,22 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "position_name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "position_name"; +} $object = new ExpenseReport($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); } @@ -74,14 +81,16 @@ $modulepart = 'trip'; // Load object //include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals -if ($object->id > 0) -{ +if ($object->id > 0) { // Check current user can read this expense report $canread = 0; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; - if (!$canread) - { + if (!empty($user->rights->expensereport->readall)) { + $canread = 1; + } + if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -104,8 +113,7 @@ $title = $langs->trans("ExpenseReport")." - ".$langs->trans("Documents"); $helpurl = "EN:Module_Expense_Reports"; llxHeader("", $title, $helpurl); -if ($object->id) -{ +if ($object->id) { $object->fetch_thirdparty(); $head = expensereport_prepare_head($object); @@ -124,8 +132,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } diff --git a/htdocs/expensereport/index.php b/htdocs/expensereport/index.php index 046bde4efa1..541c2c0738e 100644 --- a/htdocs/expensereport/index.php +++ b/htdocs/expensereport/index.php @@ -42,19 +42,27 @@ $langs->loadLangs(array('companies', 'users', 'trips')); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', '', ''); $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 +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 = "d.date_create"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "d.date_create"; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; @@ -80,8 +88,7 @@ $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as d, ".MAIN_DB_PREFIX."expensere $sql .= " WHERE de.fk_expensereport = d.rowid AND d.entity IN (".getEntity('expensereport').") AND de.fk_c_type_fees = tf.id"; // RESTRICT RIGHTS if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous) - && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) -{ + && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) { $childids = $user->getAllChildIds(); $childids[] = $user->id; $sql .= " AND d.fk_user_author IN (".join(',', $childids).")\n"; @@ -90,12 +97,10 @@ if (empty($user->rights->expensereport->readall) && empty($user->rights->expense $sql .= " GROUP BY tf.code, tf.label"; $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($result); $somme[$objp->code] = $objp->km; @@ -123,13 +128,11 @@ print '
    '; print "\n"; $listoftype = $tripandexpense_static->listOfTypes(); -foreach ($listoftype as $code => $label) -{ +foreach ($listoftype as $code => $label) { $dataseries[] = array($label, (isset($somme[$code]) ? (int) $somme[$code] : 0)); } -if ($conf->use_javascript_ajax) -{ +if ($conf->use_javascript_ajax) { print ''; print ''; print ''; - if ($num) - { + if ($num) { $total_ttc = $totalam = $total = 0; $expensereportstatic = new ExpenseReport($db); $userstatic = new User($db); - while ($i < $num && $i < $max) - { + while ($i < $num && $i < $max) { $obj = $db->fetch_object($result); $expensereportstatic->id = $obj->rowid; @@ -241,7 +246,9 @@ if ($result) print ''; } print '
    '.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").''.price($totalarray['val'][$totalarray['pos'][$i]]).''.$langs->trans("Total").''.$langs->trans("Totalforthispage").'
    '.$langs->trans('PriceUHT').''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''.$langs->trans('PriceUHTCurrency', $this->multicurrency_code).''.$langs->trans('PriceUTTC').''.$langs->trans('PriceUTTC').''.$langs->trans('Qty').''.$langs->trans('Unit').''.$langs->trans('BuyingPrice').''.$langs->trans('TotalHTShort').''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''.$langs->trans('TotalHTShortCurrency', $this->multicurrency_code).''.$langs->trans('TotalTTCShort').''.$langs->trans('TotalTTCShort').''; print ''; print ''; diff --git a/htdocs/core/tpl/objectline_view.tpl.php b/htdocs/core/tpl/objectline_view.tpl.php index e3516b8b2fc..1a223416787 100644 --- a/htdocs/core/tpl/objectline_view.tpl.php +++ b/htdocs/core/tpl/objectline_view.tpl.php @@ -39,8 +39,7 @@ */ // Protection to avoid direct call of template -if (empty($object) || !is_object($object)) -{ +if (empty($object) || !is_object($object)) { print "Error, template page can't be called as URL"; exit; } @@ -49,13 +48,25 @@ global $mysoc; global $forceall, $senderissupplier, $inputalsopricewithtax, $outputalsopricetotalwithtax; $usemargins = 0; -if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'facturerec', 'propal', 'commande'))) $usemargins = 1; +if (!empty($conf->margin->enabled) && !empty($object->element) && in_array($object->element, array('facture', 'facturerec', 'propal', 'commande'))) { + $usemargins = 1; +} -if (empty($dateSelector)) $dateSelector = 0; -if (empty($forceall)) $forceall = 0; -if (empty($senderissupplier)) $senderissupplier = 0; -if (empty($inputalsopricewithtax)) $inputalsopricewithtax = 0; -if (empty($outputalsopricetotalwithtax)) $outputalsopricetotalwithtax = 0; +if (empty($dateSelector)) { + $dateSelector = 0; +} +if (empty($forceall)) { + $forceall = 0; +} +if (empty($senderissupplier)) { + $senderissupplier = 0; +} +if (empty($inputalsopricewithtax)) { + $inputalsopricewithtax = 0; +} +if (empty($outputalsopricetotalwithtax)) { + $outputalsopricetotalwithtax = 0; +} // add html5 elements $domData = ' data-element="'.$line->element.'"'; @@ -81,34 +92,34 @@ if (($line->info_bits & 2) == 2) { print ''; $txt = ''; print img_object($langs->trans("ShowReduc"), 'reduc').' '; - if ($line->description == '(DEPOSIT)') $txt = $langs->trans("Deposit"); - elseif ($line->description == '(EXCESS RECEIVED)') $txt = $langs->trans("ExcessReceived"); - elseif ($line->description == '(EXCESS PAID)') $txt = $langs->trans("ExcessPaid"); + if ($line->description == '(DEPOSIT)') { + $txt = $langs->trans("Deposit"); + } elseif ($line->description == '(EXCESS RECEIVED)') { + $txt = $langs->trans("ExcessReceived"); + } elseif ($line->description == '(EXCESS PAID)') { + $txt = $langs->trans("ExcessPaid"); + } //else $txt=$langs->trans("Discount"); print $txt; print ''; - if ($line->description) - { - if ($line->description == '(CREDIT_NOTE)' && $line->fk_remise_except > 0) - { + if ($line->description) { + if ($line->description == '(CREDIT_NOTE)' && $line->fk_remise_except > 0) { $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); print ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromCreditNote", $discount->getNomUrl(0)); - } elseif ($line->description == '(DEPOSIT)' && $line->fk_remise_except > 0) - { + } elseif ($line->description == '(DEPOSIT)' && $line->fk_remise_except > 0) { $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); print ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromDeposit", $discount->getNomUrl(0)); // Add date of deposit - if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) + if (!empty($conf->global->INVOICE_ADD_DEPOSIT_DATE)) { print ' ('.dol_print_date($discount->datec).')'; - } elseif ($line->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) - { + } + } elseif ($line->description == '(EXCESS RECEIVED)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); print ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessReceived", $discount->getNomUrl(0)); - } elseif ($line->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) - { + } elseif ($line->description == '(EXCESS PAID)' && $objp->fk_remise_except > 0) { $discount = new DiscountAbsolute($this->db); $discount->fetch($line->fk_remise_except); print ($txt ? ' - ' : '').$langs->transnoentities("DiscountFromExcessPaid", $discount->getNomUrl(0)); @@ -123,14 +134,19 @@ if (($line->info_bits & 2) == 2) { print $form->textwithtooltip($text, $description, 3, '', '', $i, 0, (!empty($line->fk_parent_line) ?img_picto('', 'rightarrow') : '')); } else { $type = (!empty($line->product_type) ? $line->product_type : $line->fk_product_type); - if ($type == 1) $text = img_object($langs->trans('Service'), 'service'); - else $text = img_object($langs->trans('Product'), 'product'); + if ($type == 1) { + $text = img_object($langs->trans('Service'), 'service'); + } else { + $text = img_object($langs->trans('Product'), 'product'); + } if (!empty($line->label)) { $text .= ' '.$line->label.''; print $form->textwithtooltip($text, dol_htmlentitiesbr($line->description), 3, '', '', $i, 0, (!empty($line->fk_parent_line) ?img_picto('', 'rightarrow') : '')); } else { - if (!empty($line->fk_parent_line)) print img_picto('', 'rightarrow'); + if (!empty($line->fk_parent_line)) { + print img_picto('', 'rightarrow'); + } if (preg_match('/^\(DEPOSIT\)/', $line->description)) { $newdesc = preg_replace('/^\(DEPOSIT\)/', $langs->trans("Deposit"), $line->description); print $text.' '.dol_htmlentitiesbr($newdesc); @@ -142,24 +158,34 @@ if (($line->info_bits & 2) == 2) { // Show date range if ($line->element == 'facturedetrec') { - if ($line->date_start_fill || $line->date_end_fill) print '
    '; - if ($line->date_start_fill) print $langs->trans('AutoFillDateFromShort').': '.yn($line->date_start_fill); - if ($line->date_start_fill && $line->date_end_fill) print ' - '; - if ($line->date_end_fill) print $langs->trans('AutoFillDateToShort').': '.yn($line->date_end_fill); - if ($line->date_start_fill || $line->date_end_fill) print '
    '; + if ($line->date_start_fill || $line->date_end_fill) { + print '
    '; + } + if ($line->date_start_fill) { + print $langs->trans('AutoFillDateFromShort').': '.yn($line->date_start_fill); + } + if ($line->date_start_fill && $line->date_end_fill) { + print ' - '; + } + if ($line->date_end_fill) { + print $langs->trans('AutoFillDateToShort').': '.yn($line->date_end_fill); + } + if ($line->date_start_fill || $line->date_end_fill) { + print '
    '; + } } else { - if ($line->date_start || $line->date_end) print '
    '.get_date_range($line->date_start, $line->date_end, $format).'
    '; + if ($line->date_start || $line->date_end) { + print '
    '.get_date_range($line->date_start, $line->date_end, $format).'
    '; + } //print get_date_range($line->date_start, $line->date_end, $format); } // Add description in form - if ($line->fk_product > 0 && !empty($conf->global->PRODUIT_DESC_IN_FORM)) - { + if ($line->fk_product > 0 && !empty($conf->global->PRODUIT_DESC_IN_FORM)) { print (!empty($line->description) && $line->description != $line->product_label) ? '
    '.dol_htmlentitiesbr($line->description) : ''; } //Line extrafield - if (!empty($extrafields)) - { + if (!empty($extrafields)) { $temps = $line->showOptionals($extrafields, 'view', array(), '', '', 1, 'line'); if (!empty($temps)) { print '
    '; @@ -169,32 +195,28 @@ if (($line->info_bits & 2) == 2) { } } -if ($user->rights->fournisseur->lire && $line->fk_fournprice > 0 && empty($conf->global->SUPPLIER_HIDE_SUPPLIER_OBJECTLINES)) -{ +if ($user->rights->fournisseur->lire && $line->fk_fournprice > 0 && empty($conf->global->SUPPLIER_HIDE_SUPPLIER_OBJECTLINES)) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; $productfourn = new ProductFournisseur($this->db); $productfourn->fetch_product_fournisseur_price($line->fk_fournprice); print '
    '; print ''.$langs->trans('Supplier').' : '.$productfourn->getSocNomUrl(1, 'supplier').' - '.$langs->trans('Ref').' : '; // Supplier ref - if ($user->rights->produit->creer || $user->rights->service->creer) // change required right here - { + if ($user->rights->produit->creer || $user->rights->service->creer) { // change required right here print $productfourn->getNomUrl(); } else { print $productfourn->ref_supplier; } } -if (!empty($conf->accounting->enabled) && $line->fk_accounting_account > 0) -{ +if (!empty($conf->accounting->enabled) && $line->fk_accounting_account > 0) { $accountingaccount = new AccountingAccount($this->db); $accountingaccount->fetch($line->fk_accounting_account); print '

    '.$langs->trans('AccountingAffectation').' : '.$accountingaccount->getNomUrl(0, 1, 1); } print '
    '; print ($line->ref_fourn ? $line->ref_fourn : $line->ref_supplier); print ''; $coldisplay++; $positiverates = ''; -if (price2num($line->tva_tx)) $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); -if (price2num($line->total_localtax1)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); -if (price2num($line->total_localtax2)) $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); -if (empty($positiverates)) $positiverates = '0'; +if (price2num($line->tva_tx)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->tva_tx); +} +if (price2num($line->total_localtax1)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax1_tx); +} +if (price2num($line->total_localtax2)) { + $positiverates .= ($positiverates ? '/' : '').price2num($line->localtax2_tx); +} +if (empty($positiverates)) { + $positiverates = '0'; +} print vatrate($positiverates.($line->vat_src_code ? ' ('.$line->vat_src_code.')' : ''), '%', $line->info_bits); //print vatrate($line->tva_tx.($line->vat_src_code?(' ('.$line->vat_src_code.')'):''), '%', $line->info_bits); ?>'; $label = $line->getLabelOfUnit('short'); if ($label !== '') { @@ -253,8 +284,7 @@ if (!empty($line->remise_percent) && $line->special_code != 3) { } // Fields for situation invoices -if ($this->situation_cycle_ref) -{ +if ($this->situation_cycle_ref) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; $coldisplay++; print ''.$line->situation_percent.'%'.price($sign * $tmp[0]).'pa_ht); ?> pa_ht == 0) ? 'n/a' : price(price2num($line->marge_tx, 'MT')).'%'); ?> marque_tx, 'MT')).'%'; ?>
    '.$langs->trans("Statistics").'
    '; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -168,25 +171,29 @@ $langs->load("boxes"); $sql = "SELECT u.rowid as uid, u.lastname, u.firstname, u.login, u.statut as user_status, u.photo, u.email, u.admin,"; $sql .= " d.rowid, d.ref, d.date_debut as dated, d.date_fin as datef, d.date_create as dm, d.total_ht, d.total_ttc, d.fk_statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as d, ".MAIN_DB_PREFIX."user as u"; -if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE u.rowid = d.fk_user_author"; // RESTRICT RIGHTS if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous) - && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) -{ + && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) { $childids = $user->getAllChildIds(); $childids[] = $user->id; $sql .= " AND d.fk_user_author IN (".join(',', $childids).")\n"; } $sql .= ' AND d.entity IN ('.getEntity('expensereport').')'; -if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND d.fk_user_author = s.rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND d.fk_user_author = ".$socid; +if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND d.fk_user_author = s.rowid AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND d.fk_user_author = ".$socid; +} $sql .= $db->order($sortfield, $sortorder); $sql .= $db->plimit($max, 0); $result = $db->query($sql); -if ($result) -{ +if ($result) { $var = false; $num = $db->num_rows($result); @@ -201,14 +208,12 @@ if ($result) print ''.$langs->trans("DateModificationShort").' 
    '.$langs->trans("None").'

    '; -} else dol_print_error($db); +} else { + dol_print_error($db); +} print '
    '; diff --git a/htdocs/expensereport/info.php b/htdocs/expensereport/info.php index 53d1531f4b9..605197d14ac 100644 --- a/htdocs/expensereport/info.php +++ b/htdocs/expensereport/info.php @@ -37,23 +37,26 @@ $ref = GETPOST('ref', 'alpha'); $childids = $user->getAllChildIds(1); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); $object = new ExpenseReport($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); } -if ($object->id > 0) -{ +if ($object->id > 0) { // Check current user can read this expense report $canread = 0; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; - if (!$canread) - { + if (!empty($user->rights->expensereport->readall)) { + $canread = 1; + } + if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -69,8 +72,7 @@ $title = $langs->trans("ExpenseReport")." - ".$langs->trans("Info"); $helpurl = "EN:Module_Expense_Reports"; llxHeader("", $title, $helpurl); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object = new ExpenseReport($db); $object->fetch($id, $ref); $object->info($object->id); diff --git a/htdocs/expensereport/list.php b/htdocs/expensereport/list.php index 7afb464e4f4..ea3a034e252 100644 --- a/htdocs/expensereport/list.php +++ b/htdocs/expensereport/list.php @@ -54,18 +54,24 @@ $childids = $user->getAllChildIds(1); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', '', ''); $id = GETPOST('id', 'int'); // If we are on the view of a specific user -if ($id > 0) -{ +if ($id > 0) { $canread = 0; - if ($id == $user->id) $canread = 1; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($id, $childids)) $canread = 1; - if (!$canread) - { + if ($id == $user->id) { + $canread = 1; + } + if (!empty($user->rights->expensereport->readall)) { + $canread = 1; + } + if (!empty($user->rights->expensereport->lire) && in_array($id, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -78,12 +84,18 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) $sortfield = "d.date_debut"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "d.date_debut"; +} $sall = trim((GETPOST('search_all', 'alphanohtml') != '') ?GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); @@ -101,8 +113,12 @@ $month_end = GETPOST("month_end", "int"); $year_end = GETPOST("year_end", "int"); $optioncss = GETPOST('optioncss', 'alpha'); -if ($search_status == '') $search_status = -1; -if ($search_user == '') $search_user = -1; +if ($search_status == '') { + $search_status = -1; +} +if ($search_user == '') { + $search_user = -1; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new ExpenseReport($db); @@ -123,7 +139,9 @@ $fieldstosearchall = array( 'u.firstname'=>"Firstname", 'u.login'=>"Login", ); -if (empty($user->socid)) $fieldstosearchall["d.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["d.note_private"] = "NotePrivate"; +} $arrayfields = array( 'd.ref'=>array('label'=>$langs->trans("Ref"), 'checked'=>1), @@ -151,21 +169,25 @@ $objectuser = new User($db); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $parameters = array('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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { + 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_user = ""; $search_amount_ht = ""; @@ -181,8 +203,7 @@ if (empty($reshook)) $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -216,8 +237,7 @@ $min_year = 10; // Get current user id $user_id = $user->id; -if ($id > 0) -{ +if ($id > 0) { // Charge utilisateur edite $fuser->fetch($id, '', '', 1); $fuser->getrights(); @@ -231,35 +251,50 @@ $sql .= " d.date_debut, d.date_fin, d.date_create, d.tms as date_modif, d.date_v $sql .= " u.rowid as id_user, u.firstname, u.lastname, u.login, u.email, u.statut, u.photo"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."expensereport as d"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (d.rowid = ef.fk_object)"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (d.rowid = ef.fk_object)"; +} $sql .= ", ".MAIN_DB_PREFIX."user as u"; $sql .= " WHERE d.fk_user_author = u.rowid AND d.entity IN (".getEntity('expensereport').")"; // Search all -if (!empty($sall)) $sql .= natural_search(array_keys($fieldstosearchall), $sall); +if (!empty($sall)) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} // Ref -if (!empty($search_ref)) $sql .= natural_search('d.ref', $search_ref); +if (!empty($search_ref)) { + $sql .= natural_search('d.ref', $search_ref); +} // Date Start $sql .= dolSqlDateFilter("d.date_debut", $day_start, $month_start, $year_start); // Date End $sql .= dolSqlDateFilter("d.date_fin", $day_end, $month_end, $year_end); -if ($search_amount_ht != '') $sql .= natural_search('d.total_ht', $search_amount_ht, 1); -if ($search_amount_ttc != '') $sql .= natural_search('d.total_ttc', $search_amount_ttc, 1); +if ($search_amount_ht != '') { + $sql .= natural_search('d.total_ht', $search_amount_ht, 1); +} +if ($search_amount_ttc != '') { + $sql .= natural_search('d.total_ttc', $search_amount_ttc, 1); +} // User -if ($search_user != '' && $search_user >= 0) $sql .= " AND u.rowid = '".$db->escape($search_user)."'"; +if ($search_user != '' && $search_user >= 0) { + $sql .= " AND u.rowid = '".$db->escape($search_user)."'"; +} // Status -if ($search_status != '' && $search_status >= 0) $sql .= " AND d.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; +if ($search_status != '' && $search_status >= 0) { + $sql .= " AND d.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; +} // RESTRICT RIGHTS if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous) - && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) -{ + && (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || empty($user->rights->expensereport->writeall_advance))) { $sql .= " AND d.fk_user_author IN (".join(',', $childids).")\n"; } // Add where from extra fields @@ -273,12 +308,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -288,22 +321,39 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sall) $param .= "&sall=".urlencode($sall); - if ($search_ref) $param .= "&search_ref=".urlencode($search_ref); - if ($search_user) $param .= "&search_user=".urlencode($search_user); - if ($search_amount_ht) $param .= "&search_amount_ht=".urlencode($search_amount_ht); - if ($search_amount_ttc) $param .= "&search_amount_ttc=".urlencode($search_amount_ttc); - if ($search_status >= 0) $param .= "&search_status=".urlencode($search_status); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($sall) { + $param .= "&sall=".urlencode($sall); + } + if ($search_ref) { + $param .= "&search_ref=".urlencode($search_ref); + } + if ($search_user) { + $param .= "&search_user=".urlencode($search_user); + } + if ($search_amount_ht) { + $param .= "&search_amount_ht=".urlencode($search_amount_ht); + } + if ($search_amount_ttc) { + $param .= "&search_amount_ttc=".urlencode($search_amount_ttc); + } + if ($search_status >= 0) { + $param .= "&search_status=".urlencode($search_status); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -313,23 +363,30 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->expensereport->supprimer) $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if ($user->rights->expensereport->supprimer) { + $arrayofmassactions['predelete'] = ''.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); // Lines of title fields print '
    '."\n"; - if ($optioncss != '') print ''; + if ($optioncss != '') { + print ''; + } print ''; print ''; print ''; print ''; print ''; print ''; - if ($id > 0) print ''; + if ($id > 0) { + print ''; + } - if ($id > 0) // For user tab - { + if ($id > 0) { // For user tab $title = $langs->trans("User"); $linkback = ''.$langs->trans("BackToList").''; $head = user_prepare_head($fuser); @@ -340,8 +397,7 @@ if ($resql) print dol_get_fiche_end(); - if ($action != 'edit') - { + if ($action != 'edit') { print '
    '; $childids = $user->getAllChildIds(1); @@ -366,7 +422,9 @@ if ($resql) $title = $langs->trans("ListTripsAndExpenses"); $url = DOL_URL_ROOT.'/expensereport/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewTrip'), '', 'fa fa-plus-circle', $url, '', $user->rights->expensereport->creer); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'trip', 0, $newcardbutton, '', $limit, 0, 0, 1); @@ -378,9 +436,10 @@ if ($resql) $trackid = 'exp'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; } @@ -388,11 +447,13 @@ if ($resql) $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 (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; + } else { + $moreforfilter = $hookmanager->resPrint; + } - if (!empty($moreforfilter)) - { + if (!empty($moreforfilter)) { print '
    '; print $moreforfilter; print '
    '; @@ -407,17 +468,14 @@ if ($resql) // Filters print ''; - if (!empty($arrayfields['d.ref']['checked'])) - { + if (!empty($arrayfields['d.ref']['checked'])) { print ''; print ''; print ''; } // User - if (!empty($arrayfields['user']['checked'])) - { - if ($user->rights->expensereport->readall || $user->rights->expensereport->lire_tous) - { + if (!empty($arrayfields['user']['checked'])) { + if ($user->rights->expensereport->readall || $user->rights->expensereport->lire_tous) { print ''; print $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); print ''; @@ -426,8 +484,7 @@ if ($resql) } } // Date start - if (!empty($arrayfields['d.date_debut']['checked'])) - { + if (!empty($arrayfields['d.date_debut']['checked'])) { print ''; if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { print ''; @@ -438,8 +495,7 @@ if ($resql) print ''; } // Date end - if (!empty($arrayfields['d.date_fin']['checked'])) - { + if (!empty($arrayfields['d.date_fin']['checked'])) { print ''; if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { print ''; @@ -449,33 +505,28 @@ if ($resql) print ''; } // Date valid - if (!empty($arrayfields['d.date_valid']['checked'])) - { + if (!empty($arrayfields['d.date_valid']['checked'])) { print ''; //print ''; //$formother->select_year($year_end,'year_end',1, $min_year, $max_year); print ''; } // Date approve - if (!empty($arrayfields['d.date_approve']['checked'])) - { + if (!empty($arrayfields['d.date_approve']['checked'])) { print ''; //print ''; //$formother->select_year($year_end,'year_end',1, $min_year, $max_year); print ''; } // Amount with no tax - if (!empty($arrayfields['d.total_ht']['checked'])) - { + if (!empty($arrayfields['d.total_ht']['checked'])) { print ''; } - if (!empty($arrayfields['d.total_vat']['checked'])) - { + if (!empty($arrayfields['d.total_vat']['checked'])) { print ''; } // Amount with all taxes - if (!empty($arrayfields['d.total_ttc']['checked'])) - { + if (!empty($arrayfields['d.total_ttc']['checked'])) { print ''; } // Extra fields @@ -486,20 +537,17 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['d.date_create']['checked'])) - { + if (!empty($arrayfields['d.date_create']['checked'])) { print ''; print ''; } // Date modification - if (!empty($arrayfields['d.tms']['checked'])) - { + if (!empty($arrayfields['d.tms']['checked'])) { print ''; print ''; } // Status - if (!empty($arrayfields['d.fk_statut']['checked'])) - { + if (!empty($arrayfields['d.fk_statut']['checked'])) { print ''; $formexpensereport->selectExpensereportStatus($search_status, 'search_status', 1, 1); print ''; @@ -513,24 +561,48 @@ if ($resql) print "\n"; print ''; - if (!empty($arrayfields['d.ref']['checked'])) print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], "d.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['user']['checked'])) print_liste_field_titre($arrayfields['user']['label'], $_SERVER["PHP_SELF"], "u.lastname", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['d.date_debut']['checked'])) print_liste_field_titre($arrayfields['d.date_debut']['label'], $_SERVER["PHP_SELF"], "d.date_debut", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['d.date_fin']['checked'])) print_liste_field_titre($arrayfields['d.date_fin']['label'], $_SERVER["PHP_SELF"], "d.date_fin", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['d.date_valid']['checked'])) print_liste_field_titre($arrayfields['d.date_valid']['label'], $_SERVER["PHP_SELF"], "d.date_valid", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['d.date_approve']['checked'])) print_liste_field_titre($arrayfields['d.date_approve']['label'], $_SERVER["PHP_SELF"], "d.date_approve", "", $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['d.total_ht']['checked'])) print_liste_field_titre($arrayfields['d.total_ht']['label'], $_SERVER["PHP_SELF"], "d.total_ht", "", $param, 'align="right"', $sortfield, $sortorder); - if (!empty($arrayfields['d.total_vat']['checked'])) print_liste_field_titre($arrayfields['d.total_vat']['label'], $_SERVER["PHP_SELF"], "d.total_tva", "", $param, 'align="right"', $sortfield, $sortorder); - if (!empty($arrayfields['d.total_ttc']['checked'])) print_liste_field_titre($arrayfields['d.total_ttc']['label'], $_SERVER["PHP_SELF"], "d.total_ttc", "", $param, 'align="right"', $sortfield, $sortorder); + if (!empty($arrayfields['d.ref']['checked'])) { + print_liste_field_titre($arrayfields['d.ref']['label'], $_SERVER["PHP_SELF"], "d.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['user']['checked'])) { + print_liste_field_titre($arrayfields['user']['label'], $_SERVER["PHP_SELF"], "u.lastname", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.date_debut']['checked'])) { + print_liste_field_titre($arrayfields['d.date_debut']['label'], $_SERVER["PHP_SELF"], "d.date_debut", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.date_fin']['checked'])) { + print_liste_field_titre($arrayfields['d.date_fin']['label'], $_SERVER["PHP_SELF"], "d.date_fin", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.date_valid']['checked'])) { + print_liste_field_titre($arrayfields['d.date_valid']['label'], $_SERVER["PHP_SELF"], "d.date_valid", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.date_approve']['checked'])) { + print_liste_field_titre($arrayfields['d.date_approve']['label'], $_SERVER["PHP_SELF"], "d.date_approve", "", $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['d.total_ht']['label'], $_SERVER["PHP_SELF"], "d.total_ht", "", $param, 'align="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.total_vat']['checked'])) { + print_liste_field_titre($arrayfields['d.total_vat']['label'], $_SERVER["PHP_SELF"], "d.total_tva", "", $param, 'align="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['d.total_ttc']['label'], $_SERVER["PHP_SELF"], "d.total_ttc", "", $param, 'align="right"', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['d.date_create']['checked'])) print_liste_field_titre($arrayfields['d.date_create']['label'], $_SERVER["PHP_SELF"], "d.date_create", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (!empty($arrayfields['d.tms']['checked'])) print_liste_field_titre($arrayfields['d.tms']['label'], $_SERVER["PHP_SELF"], "d.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); - if (!empty($arrayfields['d.fk_statut']['checked'])) print_liste_field_titre($arrayfields['d.fk_statut']['label'], $_SERVER["PHP_SELF"], "d.fk_statut", "", $param, 'align="right"', $sortfield, $sortorder); + if (!empty($arrayfields['d.date_create']['checked'])) { + print_liste_field_titre($arrayfields['d.date_create']['label'], $_SERVER["PHP_SELF"], "d.date_create", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.tms']['checked'])) { + print_liste_field_titre($arrayfields['d.tms']['label'], $_SERVER["PHP_SELF"], "d.tms", "", $param, 'align="center" class="nowrap"', $sortfield, $sortorder); + } + if (!empty($arrayfields['d.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['d.fk_statut']['label'], $_SERVER["PHP_SELF"], "d.fk_statut", "", $param, 'align="right"', $sortfield, $sortorder); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', 'align="center"', $sortfield, $sortorder, 'maxwidthsearch '); print "\n"; @@ -541,12 +613,10 @@ if ($resql) $expensereportstatic = new ExpenseReport($db); $usertmp = new User($db); - if ($num > 0) - { + if ($num > 0) { $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $expensereportstatic->id = $obj->rowid; @@ -572,10 +642,13 @@ if ($resql) print ''; // Warning late icon and note print ''; - if ($expensereportstatic->status == 2 && $expensereportstatic->hasDelay('toappove')) print img_warning($langs->trans("Late")); - if ($expensereportstatic->status == 5 && $expensereportstatic->hasDelay('topay')) print img_warning($langs->trans("Late")); - if (!empty($obj->note_private) || !empty($obj->note_public)) - { + if ($expensereportstatic->status == 2 && $expensereportstatic->hasDelay('toappove')) { + print img_warning($langs->trans("Late")); + } + if ($expensereportstatic->status == 5 && $expensereportstatic->hasDelay('topay')) { + print img_warning($langs->trans("Late")); + } + if (!empty($obj->note_private) || !empty($obj->note_public)) { print ' '; print ''.img_picto($langs->trans("ViewPrivateNote"), 'object_generic').''; print ''; @@ -589,7 +662,9 @@ if ($resql) print ''; print ''; print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // User if (!empty($arrayfields['user']['checked'])) { @@ -603,50 +678,69 @@ if ($resql) $usertmp->email = $obj->email; print $usertmp->getNomUrl(-1); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Start date if (!empty($arrayfields['d.date_debut']['checked'])) { print ''.($obj->date_debut > 0 ? dol_print_date($db->jdate($obj->date_debut), 'day') : '').''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // End date if (!empty($arrayfields['d.date_fin']['checked'])) { print ''.($obj->date_fin > 0 ? dol_print_date($db->jdate($obj->date_fin), 'day') : '').''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date validation if (!empty($arrayfields['d.date_valid']['checked'])) { print ''.($obj->date_valid > 0 ? dol_print_date($db->jdate($obj->date_valid), 'day') : '').''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date approval if (!empty($arrayfields['d.date_approve']['checked'])) { print ''.($obj->date_approve > 0 ? dol_print_date($db->jdate($obj->date_approve), 'day') : '').''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['d.total_ht']['checked'])) - { + if (!empty($arrayfields['d.total_ht']['checked'])) { print ''.price($obj->total_ht)."\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'd.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'd.total_ht'; + } $totalarray['val']['d.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['d.total_vat']['checked'])) - { + if (!empty($arrayfields['d.total_vat']['checked'])) { print ''.price($obj->total_tva)."\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'd.total_tva'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'd.total_tva'; + } $totalarray['val']['d.total_tva'] += $obj->total_tva; } // Amount TTC - if (!empty($arrayfields['d.total_ttc']['checked'])) - { + if (!empty($arrayfields['d.total_ttc']['checked'])) { print ''.price($obj->total_ttc)."\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'd.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'd.total_ttc'; + } $totalarray['val']['d.total_ttc'] += $obj->total_ttc; } @@ -658,37 +752,43 @@ if ($resql) print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['d.date_create']['checked'])) - { + if (!empty($arrayfields['d.date_create']['checked'])) { print ''; print dol_print_date($db->jdate($obj->date_create), 'dayhour'); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['d.tms']['checked'])) - { + if (!empty($arrayfields['d.tms']['checked'])) { print ''; print dol_print_date($db->jdate($obj->date_modif), 'dayhour'); print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['d.fk_statut']['checked'])) - { + if (!empty($arrayfields['d.fk_statut']['checked'])) { print ''.$expensereportstatic->getLibStatut(5).''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print ''; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + if (in_array($obj->rowid, $arrayofselected)) { + $selected = 1; + } print ''; } print ''; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "\n"; @@ -700,7 +800,11 @@ if ($resql) } } else { $colspan = 1; - foreach ($arrayfields as $key => $val) { if (!empty($val['checked'])) $colspan++; } + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } print ''.$langs->trans("NoRecordFound").''; } @@ -718,10 +822,11 @@ if ($resql) print ''."\n"; - if (empty($id)) - { + if (empty($id)) { $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/expensereport/note.php b/htdocs/expensereport/note.php index ebb66ce42fd..b0156c6a475 100644 --- a/htdocs/expensereport/note.php +++ b/htdocs/expensereport/note.php @@ -41,26 +41,29 @@ $childids = $user->getAllChildIds(1); // Security check $socid = 0; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', $id, 'expensereport'); $object = new ExpenseReport($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); } $permissionnote = $user->rights->expensereport->creer; // Used by the include of actions_setnotes.inc.php -if ($object->id > 0) -{ +if ($object->id > 0) { // Check current user can read this expense report $canread = 0; - if (!empty($user->rights->expensereport->readall)) $canread = 1; - if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) $canread = 1; - if (!$canread) - { + if (!empty($user->rights->expensereport->readall)) { + $canread = 1; + } + if (!empty($user->rights->expensereport->lire) && in_array($object->fk_user_author, $childids)) { + $canread = 1; + } + if (!$canread) { accessforbidden(); } } @@ -82,8 +85,7 @@ llxHeader("", $title, $helpurl); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object = new ExpenseReport($db); $object->fetch($id, $ref); $object->info($object->id); diff --git a/htdocs/expensereport/payment/card.php b/htdocs/expensereport/payment/card.php index 14c95f2d68a..608309ceee0 100644 --- a/htdocs/expensereport/payment/card.php +++ b/htdocs/expensereport/payment/card.php @@ -26,7 +26,9 @@ require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/expensereport/modules_expensereport.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/expensereport.lib.php'; -if (!empty($conf->banque->enabled)) require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +if (!empty($conf->banque->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('bills', 'banks', 'companies', 'trips')); @@ -36,16 +38,19 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // TODO Add rule to restrict access payment //$result = restrictedArea($user, 'facture', $id,''); $object = new PaymentExpenseReport($db); -if ($id > 0) -{ +if ($id > 0) { $result = $object->fetch($id); - if (!$result) dol_print_error($db, 'Failed to get payment id '.$id); + if (!$result) { + dol_print_error($db, 'Failed to get payment id '.$id); + } } @@ -54,13 +59,11 @@ if ($id > 0) */ // Delete payment -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expensereport->supprimer) -{ +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->expensereport->supprimer) { $db->begin(); $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { $db->commit(); header("Location: ".DOL_URL_ROOT."/expensereport/index.php"); exit; @@ -86,8 +89,7 @@ print dol_get_fiche_head($head, 'payment', $langs->trans("ExpenseReportPayment") /* * Confirm deleting of the payment */ -if ($action == 'delete') -{ +if ($action == 'delete') { print $form->formconfirm('card.php?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete', '', 0, 2); } @@ -118,14 +120,11 @@ print ''.$langs->trans('Note').''.nl2 $disable_delete = 0; // Bank account -if (!empty($conf->banque->enabled)) -{ - if ($object->bank_account) - { +if (!empty($conf->banque->enabled)) { + if ($object->bank_account) { $bankline = new AccountLine($db); $bankline->fetch($object->bank_line); - if ($bankline->rappro) - { + if ($bankline->rappro) { $disable_delete = 1; $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment")); } @@ -167,8 +166,7 @@ $sql .= ' AND per.rowid = '.$id; dol_syslog("expensereport/payment/card.php", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -186,10 +184,8 @@ if ($resql) print ''.$langs->trans('Status').''; print "\n"; - if ($num > 0) - { - while ($i < $num) - { + if ($num > 0) { + while ($i < $num) { $objp = $db->fetch_object($resql); print ''; @@ -216,8 +212,7 @@ if ($resql) print "\n"; - if ($objp->paid == 1) // If at least one invoice is paid, disable delete - { + if ($objp->paid == 1) { // If at least one invoice is paid, disable delete $disable_delete = 2; $title_button = $langs->trans("CantRemovePaymentWithOneInvoicePaid"); } @@ -242,12 +237,9 @@ if ($resql) */ print '
    '; -if ($action == '') -{ - if ($user->rights->expensereport->supprimer) - { - if (!$disable_delete) - { +if ($action == '') { + if ($user->rights->expensereport->supprimer) { + if (!$disable_delete) { print ''.$langs->trans('Delete').''; } else { print ''.$langs->trans('Delete').''; diff --git a/htdocs/expensereport/payment/payment.php b/htdocs/expensereport/payment/payment.php index b66103f38f5..926559769b4 100644 --- a/htdocs/expensereport/payment/payment.php +++ b/htdocs/expensereport/payment/payment.php @@ -39,8 +39,7 @@ $accountid = GETPOST('accountid', 'int'); // Security check $socid = 0; -if ($user->socid > 0) -{ +if ($user->socid > 0) { $socid = $user->socid; } @@ -49,12 +48,10 @@ if ($user->socid > 0) * Actions */ -if ($action == 'add_payment') -{ +if ($action == 'add_payment') { $error = 0; - if ($_POST["cancel"]) - { + if ($_POST["cancel"]) { $loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id; header("Location: ".$loc); exit; @@ -62,53 +59,44 @@ if ($action == 'add_payment') $expensereport = new ExpenseReport($db); $result = $expensereport->fetch($id, $ref); - if (!$result) - { + if (!$result) { $error++; setEventMessages($expensereport->error, $expensereport->errors, 'errors'); } $datepaid = dol_mktime(12, 0, 0, $_POST["remonth"], $_POST["reday"], $_POST["reyear"]); - if (!($_POST["fk_typepayment"] > 0)) - { + if (!($_POST["fk_typepayment"] > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")), null, 'errors'); $error++; } - if ($datepaid == '') - { + if ($datepaid == '') { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors'); $error++; } - if (!empty($conf->banque->enabled) && !($accountid > 0)) - { + if (!empty($conf->banque->enabled) && !($accountid > 0)) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToDebit")), null, 'errors'); $error++; } - if (!$error) - { + if (!$error) { $paymentid = 0; $total = 0; // Read possible payments - foreach ($_POST as $key => $value) - { - if (substr($key, 0, 7) == 'amount_') - { + foreach ($_POST as $key => $value) { + if (substr($key, 0, 7) == 'amount_') { $amounts[$expensereport->fk_user_author] = price2num($_POST[$key]); $total += price2num($_POST[$key]); } } - if (count($amounts) <= 0) - { + if (count($amounts) <= 0) { $error++; $errmsg = 'ErrorNoPaymentDefined'; } - if (!$error) - { + if (!$error) { $db->begin(); // Create a line of payments @@ -121,21 +109,17 @@ if ($action == 'add_payment') $payment->num_payment = GETPOST("num_payment", 'alphanothtml'); $payment->note_public = GETPOST("note_public", 'restricthtml'); - if (!$error) - { + if (!$error) { $paymentid = $payment->create($user); - if ($paymentid < 0) - { + if ($paymentid < 0) { setEventMessages($payment->error, $payment->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $result = $payment->addPaymentToBank($user, 'payment_expensereport', '(ExpenseReportPayment)', $accountid, '', ''); - if (!$result > 0) - { + if (!$result > 0) { setEventMessages($payment->error, $payment->errors, 'errors'); $error++; } @@ -152,8 +136,7 @@ if ($action == 'add_payment') } } - if (!$error) - { + if (!$error) { $db->commit(); $loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id; header('Location: '.$loc); @@ -178,8 +161,7 @@ $form = new Form($db); // Form to create expense report payment -if ($action == 'create' || empty($action)) -{ +if ($action == 'create' || empty($action)) { $expensereport = new ExpenseReport($db); $expensereport->fetch($id, $ref); @@ -226,8 +208,7 @@ if ($action == 'create' || empty($action)) $sql .= " WHERE p.fk_expensereport = e.rowid AND p.fk_expensereport = ".$id; $sql .= ' AND e.entity IN ('.getEntity('expensereport').')'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); $sumpaid = $obj->total; $db->free(); @@ -257,8 +238,7 @@ if ($action == 'create' || empty($action)) print "\n"; print ''; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print ''; print ''.$langs->trans('AccountToDebit').''; print ''; @@ -299,8 +279,7 @@ if ($action == 'create' || empty($action)) $total = 0; $totalrecu = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $expensereport; print ''; @@ -310,12 +289,12 @@ if ($action == 'create' || empty($action)) print ''.price($sumpaid).""; print ''.price($objp->total_ttc - $sumpaid).""; print ''; - if ($sumpaid < $objp->total_ttc) - { + if ($sumpaid < $objp->total_ttc) { $namef = "amount_".$objp->id; $nameRemain = "remain_".$objp->id; // autofill remainder amount - if (!empty($conf->use_javascript_ajax)) // autofill remainder amount + if (!empty($conf->use_javascript_ajax)) { // autofill remainder amount print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->total_ttc - $sumpaid)."'"); // autofill remainder amount + } $remaintopay = $objp->total_ttc - $sumpaid; // autofill remainder amount print ''; // autofill remainder amount print ''; @@ -331,8 +310,7 @@ if ($action == 'create' || empty($action)) $totalrecu += $objp->am; $i++; } - if ($i > 1) - { + if ($i > 1) { // Print total print ''; print ''.$langs->trans("Total").':'; diff --git a/htdocs/expensereport/stats/index.php b/htdocs/expensereport/stats/index.php index f3a3e263fa7..87bac2dde1a 100644 --- a/htdocs/expensereport/stats/index.php +++ b/htdocs/expensereport/stats/index.php @@ -38,16 +38,19 @@ $mode = GETPOSTISSET("mode") ? GETPOST("mode", 'aZ09') : 'customer'; $object_status = GETPOST('object_status', 'intcomma'); $userid = GETPOST('userid', 'int'); -$socid = GETPOST('socid', 'int'); if ($socid < 0) $socid = 0; +$socid = GETPOST('socid', 'int'); if ($socid < 0) { + $socid = 0; +} $id = GETPOST('id', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'expensereport', $id, ''); $nowyear = strftime("%Y", dol_now()); @@ -75,7 +78,9 @@ print load_fiche_titre($title, '', 'trip'); dol_mkdir($dir); $stats = new ExpenseReportStats($db, $socid, $userid); -if ($object_status != '' && $object_status >= -1) $stats->where .= ' AND e.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($object_status != '' && $object_status >= -1) { + $stats->where .= ' AND e.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +} // Build graphic number of object // $data = array(array('Lib',val1,val2,val3),...) @@ -88,12 +93,10 @@ $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=tripsexpensesstats&file $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -120,12 +123,10 @@ $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=tripsexpensesstats& $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -146,25 +147,30 @@ if (!$mesg) $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filename_avg = $dir.'/ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$user->id.'-'.$year.'.png'; + } } else { $filename_avg = $dir.'/ordersaverage-'.$year.'.png'; - if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; - if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + if ($mode == 'customer') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstats&file=ordersaverage-'.$year.'.png'; + } + if ($mode == 'supplier') { + $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=orderstatssupplier&file=ordersaverage-'.$year.'.png'; + } } $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -189,7 +195,9 @@ $arrayyears = array(); foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; @@ -223,7 +231,9 @@ print ''; // User print ''.$langs->trans("User").''; $include = ''; -if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) $include = 'hierarchy'; +if (empty($user->rights->expensereport->readall) && empty($user->rights->expensereport->lire_tous)) { + $include = 'hierarchy'; +} print $form->select_dolusers($userid, 'userid', 1, '', 0, $include, '', 0, 0, 0, '', 0, '', 'maxwidth300'); print ''; // Status @@ -235,7 +245,9 @@ print ''; print ''; print $form->textwithpicto($langs->trans("Year"), $langs->trans("DateValidation")); print ''; -if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print ''; @@ -254,11 +266,9 @@ print ''.$langs->trans("AmountAverage").''; print ''; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while ($year && $oldyear > $year + 1) - { // If we have empty year + while ($year && $oldyear > $year + 1) { // If we have empty year $oldyear--; print ''; @@ -287,7 +297,9 @@ print '
    '; // Show graphs print ''; diff --git a/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php b/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php index 04bb2a71990..640f4c17b5d 100644 --- a/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php +++ b/htdocs/expensereport/tpl/expensereport_linktofile.tpl.php @@ -1,7 +1,6 @@ global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) -{ +if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) { print ''."\n"; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; @@ -12,23 +11,20 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) $nbFiles = count($arrayoffiles); $nbLinks = Link::count($db, $object->element, $object->id); - if ($nbFiles > 0) - { + if ($nbFiles > 0) { print 'global->MAIN_OPTIMIZEFORTEXTBROWSER) ? ' style="display: none"' : '').'>'; print ' > - - + + "; diff --git a/htdocs/exports/export.php b/htdocs/exports/export.php index c80ee4d248f..f1099f9692f 100644 --- a/htdocs/exports/export.php +++ b/htdocs/exports/export.php @@ -54,14 +54,14 @@ $entitytoicon = array( 'subscription' => 'payment', 'payment' => 'payment', 'tax' => 'generic', - 'tax_type' => 'generic', - 'other' => 'generic', + 'tax_type' => 'generic', + 'other' => 'generic', 'account' => 'account', 'product' => 'product', 'virtualproduct'=>'product', 'subproduct' => 'product', 'product_supplier_ref' => 'product', - 'stock' => 'stock', + 'stock' => 'stock', 'warehouse' => 'stock', 'batch' => 'stock', 'stockbatch' => 'stock', @@ -159,17 +159,16 @@ $usefilters = 1; * Actions */ -if ($action == 'selectfield') // Selection of field at step 2 -{ +if ($action == 'selectfield') { // Selection of field at step 2 $fieldsarray = $objexport->array_export_fields[0]; $fieldsentitiesarray = $objexport->array_export_entities[0]; $fieldsdependenciesarray = $objexport->array_export_dependencies[0]; - if ($field == 'all') - { - foreach ($fieldsarray as $key=>$val) - { - if (!empty($array_selected[$key])) continue; // If already selected, check next + if ($field == 'all') { + foreach ($fieldsarray as $key => $val) { + if (!empty($array_selected[$key])) { + continue; // If already selected, check next + } $array_selected[$key] = count($array_selected) + 1; //print_r($array_selected); $_SESSION["export_selected_fields"] = $array_selected; @@ -180,29 +179,30 @@ if ($action == 'selectfield') // Selection of field at step 2 $array_selected[$field] = count($array_selected) + 1; // We tag the key $field as "selected" // We check if there is a dependency to activate /*var_dump($field); - var_dump($fieldsentitiesarray[$field]); - var_dump($fieldsdependenciesarray);*/ + var_dump($fieldsentitiesarray[$field]); + var_dump($fieldsdependenciesarray);*/ $listofdependencies = array(); - if (!empty($fieldsentitiesarray[$field]) && !empty($fieldsdependenciesarray[$fieldsentitiesarray[$field]])) - { + if (!empty($fieldsentitiesarray[$field]) && !empty($fieldsdependenciesarray[$fieldsentitiesarray[$field]])) { // We found a dependency on the type of field $tmp = $fieldsdependenciesarray[$fieldsentitiesarray[$field]]; // $fieldsdependenciesarray=array('element'=>'fd.rowid') or array('element'=>array('fd.rowid','ab.rowid')) - if (is_array($tmp)) $listofdependencies = $tmp; - else $listofdependencies = array($tmp); - } elseif (!empty($field) && !empty($fieldsdependenciesarray[$field])) - { + if (is_array($tmp)) { + $listofdependencies = $tmp; + } else { + $listofdependencies = array($tmp); + } + } elseif (!empty($field) && !empty($fieldsdependenciesarray[$field])) { // We found a dependency on a dedicated field $tmp = $fieldsdependenciesarray[$field]; // $fieldsdependenciesarray=array('fd.fieldx'=>'fd.rowid') or array('fd.fieldx'=>array('fd.rowid','ab.rowid')) - if (is_array($tmp)) $listofdependencies = $tmp; - else $listofdependencies = array($tmp); + if (is_array($tmp)) { + $listofdependencies = $tmp; + } else { + $listofdependencies = array($tmp); + } } - if (count($listofdependencies)) - { - foreach ($listofdependencies as $fieldid) - { - if (empty($array_selected[$fieldid])) - { + if (count($listofdependencies)) { + foreach ($listofdependencies as $fieldid) { + if (empty($array_selected[$fieldid])) { $array_selected[$fieldid] = count($array_selected) + 1; // We tag the key $fieldid as "selected" $warnings[] = $langs->trans("ExportFieldAutomaticallyAdded", $langs->transnoentitiesnoconv($fieldsarray[$fieldid])); } @@ -214,10 +214,8 @@ if ($action == 'selectfield') // Selection of field at step 2 setEventMessages($warnings, null, 'warnings'); } } -if ($action == 'unselectfield') -{ - if ($_GET["field"] == 'all') - { +if ($action == 'unselectfield') { + if ($_GET["field"] == 'all') { $array_selected = array(); $_SESSION["export_selected_fields"] = $array_selected; } else { @@ -226,8 +224,7 @@ if ($action == 'unselectfield') asort($array_selected); $i = 0; $array_selected_save = $array_selected; - foreach ($array_selected as $code=>$value) - { + foreach ($array_selected as $code => $value) { $i++; $array_selected[$code] = $i; //print "x $code x $i y
    "; @@ -236,52 +233,48 @@ if ($action == 'unselectfield') } } -if ($action == 'downfield' || $action == 'upfield') -{ +if ($action == 'downfield' || $action == 'upfield') { $pos = $array_selected[$_GET["field"]]; - if ($action == 'downfield') $newpos = $pos + 1; - if ($action == 'upfield') $newpos = $pos - 1; + if ($action == 'downfield') { + $newpos = $pos + 1; + } + if ($action == 'upfield') { + $newpos = $pos - 1; + } // Recherche code avec qui switcher $newcode = ""; - foreach ($array_selected as $code=>$value) - { - if ($value == $newpos) - { + foreach ($array_selected as $code => $value) { + if ($value == $newpos) { $newcode = $code; break; } } //print("Switch pos=$pos (code=".$_GET["field"].") and newpos=$newpos (code=$newcode)"); - if ($newcode) // Si newcode trouve (protection contre resoumission de page) - { + if ($newcode) { // Si newcode trouve (protection contre resoumission de page) $array_selected[$_GET["field"]] = $newpos; $array_selected[$newcode] = $pos; $_SESSION["export_selected_fields"] = $array_selected; } } -if ($step == 1 || $action == 'cleanselect') -{ +if ($step == 1 || $action == 'cleanselect') { $_SESSION["export_selected_fields"] = array(); $_SESSION["export_filtered_fields"] = array(); $array_selected = array(); $array_filtervalue = array(); } -if ($action == 'builddoc') -{ +if ($action == 'builddoc') { $max_execution_time_for_importexport = (empty($conf->global->EXPORT_MAX_EXECUTION_TIME) ? 300 : $conf->global->EXPORT_MAX_EXECUTION_TIME); // 5mn if not defined $max_time = @ini_get("max_execution_time"); - if ($max_time && $max_time < $max_execution_time_for_importexport) - { + if ($max_time && $max_time < $max_execution_time_for_importexport) { dol_syslog("max_execution_time=".$max_time." is lower than max_execution_time_for_importexport=".$max_execution_time_for_importexport.". We try to increase it dynamically."); @ini_set("max_execution_time", $max_execution_time_for_importexport); // This work only if safe mode is off. also web servers has timeout of 300 } // Build export file $result = $objexport->build_file($user, GETPOST('model', 'alpha'), $datatoexport, $array_selected, $array_filtervalue); - if ($result < 0) - { + if ($result < 0) { setEventMessages($objexport->error, $objexport->errors, 'errors'); $sqlusedforexport = $objexport->sqlusedforexport; } else { @@ -291,47 +284,46 @@ if ($action == 'builddoc') } // Delete file -if ($step == 5 && $action == 'confirm_deletefile' && $confirm == 'yes') -{ +if ($step == 5 && $action == 'confirm_deletefile' && $confirm == 'yes') { $file = $upload_dir."/".GETPOST('file'); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP). $ret = dol_delete_file($file); - if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); - else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + if ($ret) { + setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs'); + } else { + setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors'); + } header('Location: '.$_SERVER["PHP_SELF"].'?step='.$step.'&datatoexport='.$datatoexport); exit; } -if ($action == 'deleteprof') -{ - if (GETPOST("id", 'int')) - { +if ($action == 'deleteprof') { + if (GETPOST("id", 'int')) { $objexport->fetch(GETPOST('id', 'int')); $result = $objexport->delete($user); } } // TODO The export for filter is not yet implemented (old code created conflicts with step 2). We must use same way of working and same combo list of predefined export than step 2. -if ($action == 'add_export_model') -{ - if ($export_name) - { +if ($action == 'add_export_model') { + if ($export_name) { asort($array_selected); // Set save string $hexa = ''; - foreach ($array_selected as $key=>$val) - { - if ($hexa) $hexa .= ','; + foreach ($array_selected as $key => $val) { + if ($hexa) { + $hexa .= ','; + } $hexa .= $key; } $hexafiltervalue = ''; - if (!empty($array_filtervalue) && is_array($array_filtervalue)) - { - foreach ($array_filtervalue as $key=>$val) - { - if ($hexafiltervalue) $hexafiltervalue .= ','; + if (!empty($array_filtervalue) && is_array($array_filtervalue)) { + foreach ($array_filtervalue as $key => $val) { + if ($hexafiltervalue) { + $hexafiltervalue .= ','; + } $hexafiltervalue .= $key.'='.$val; } } @@ -342,14 +334,15 @@ if ($action == 'add_export_model') $objexport->hexafiltervalue = $hexafiltervalue; $result = $objexport->create($user); - if ($result >= 0) - { + if ($result >= 0) { setEventMessages($langs->trans("ExportModelSaved", $objexport->model_name), null, 'mesgs'); } else { $langs->load("errors"); - if ($objexport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') + if ($objexport->errno == 'DB_ERROR_RECORD_ALREADY_EXISTS') { setEventMessages($langs->trans("ErrorExportDuplicateProfil"), null, 'errors'); - else setEventMessages($objexport->error, $objexport->errors, 'errors'); + } else { + setEventMessages($objexport->error, $objexport->errors, 'errors'); + } } } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("ExportModelName")), null, 'errors'); @@ -357,8 +350,7 @@ if ($action == 'add_export_model') } // Reload a predefined export model -if ($step == 2 && $action == 'select_model') -{ +if ($step == 2 && $action == 'select_model') { $_SESSION["export_selected_fields"] = array(); $_SESSION["export_filtered_fields"] = array(); @@ -366,12 +358,10 @@ if ($step == 2 && $action == 'select_model') $array_filtervalue = array(); $result = $objexport->fetch($exportmodelid); - if ($result > 0) - { + if ($result > 0) { $fieldsarray = preg_split("/,(?! [^(]*\))/", $objexport->hexa); $i = 1; - foreach ($fieldsarray as $val) - { + foreach ($fieldsarray as $val) { $array_selected[$val] = $i; $i++; } @@ -379,8 +369,7 @@ if ($step == 2 && $action == 'select_model') $fieldsarrayvalue = explode(',', $objexport->hexafiltervalue); $i = 1; - foreach ($fieldsarrayvalue as $val) - { + foreach ($fieldsarrayvalue as $val) { $tmp = explode('=', $val); $array_filtervalue[$tmp[0]] = $tmp[1]; $i++; @@ -390,21 +379,20 @@ if ($step == 2 && $action == 'select_model') } // Get form with filters -if ($step == 4 && $action == 'submitFormField') -{ +if ($step == 4 && $action == 'submitFormField') { // on boucle sur les champs selectionne pour recuperer la valeur - if (is_array($objexport->array_export_TypeFields[0])) - { + if (is_array($objexport->array_export_TypeFields[0])) { $_SESSION["export_filtered_fields"] = array(); - foreach ($objexport->array_export_TypeFields[0] as $code => $type) // $code: s.fieldname $value: Text|Boolean|List:ccc - { + foreach ($objexport->array_export_TypeFields[0] as $code => $type) { // $code: s.fieldname $value: Text|Boolean|List:ccc $newcode = (string) preg_replace('/\./', '_', $code); //print 'xxx'.$code."=".$newcode."=".$type."=".$_POST[$newcode]."\n
    "; $filterqualified = 1; - if (!GETPOSTISSET($newcode) || GETPOST($newcode, 'restricthtml') == '') $filterqualified = 0; - elseif (preg_match('/^List/', $type) && (is_numeric(GETPOST($newcode, 'restricthtml')) && GETPOST($newcode, 'restricthtml') <= 0)) $filterqualified = 0; - if ($filterqualified) - { + if (!GETPOSTISSET($newcode) || GETPOST($newcode, 'restricthtml') == '') { + $filterqualified = 0; + } elseif (preg_match('/^List/', $type) && (is_numeric(GETPOST($newcode, 'restricthtml')) && GETPOST($newcode, 'restricthtml') <= 0)) { + $filterqualified = 0; + } + if ($filterqualified) { //print 'Filter on '.$newcode.' type='.$type.' value='.$_POST[$newcode]."\n"; $objexport->array_export_FilterValue[0][$code] = GETPOST($newcode, 'restricthtml'); } @@ -419,8 +407,7 @@ if ($step == 4 && $action == 'submitFormField') * View */ -if ($step == 1 || !$datatoexport) -{ +if ($step == 1 || !$datatoexport) { llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones'); $h = 0; @@ -443,13 +430,11 @@ if ($step == 1 || !$datatoexport) print ''; print ''; - if (count($objexport->array_export_module)) - { + if (count($objexport->array_export_module)) { asort($objexport->array_export_code_for_sort); //var_dump($objexport->array_export_code_for_sort); //$sortedarrayofmodules = dol_sort_array($objexport->array_export_module, 'module_position', 'asc', 0, 0, 1); - foreach ($objexport->array_export_code_for_sort as $key => $value) - { + foreach ($objexport->array_export_code_for_sort as $key => $value) { print ''; + print ''; } } else { print ''; @@ -477,8 +462,7 @@ if ($step == 1 || !$datatoexport) print ''; } -if ($step == 2 && $datatoexport) -{ +if ($step == 2 && $datatoexport) { llxHeader('', $langs->trans("NewExport"), 'EN:Module_Exports_En|FR:Module_Exports|ES:Módulo_Exportaciones'); $h = 0; @@ -505,14 +489,14 @@ if ($step == 2 && $datatoexport) print $objexport->array_export_module[0]->getName(); print ''; - // Lot de donnees a exporter - print ''; - print ''; + // Lot de donnees a exporter + print ''; + print ''; print '
    '; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); print "
    \n"; print $px2->show(); diff --git a/htdocs/expensereport/tpl/expensereport_addfile.tpl.php b/htdocs/expensereport/tpl/expensereport_addfile.tpl.php index 9b2cd49faec..c27136ebd38 100644 --- a/htdocs/expensereport/tpl/expensereport_addfile.tpl.php +++ b/htdocs/expensereport/tpl/expensereport_addfile.tpl.php @@ -9,11 +9,9 @@ $permission = $user->rights->expensereport->creer; // We define var to enable the feature to add prefix of uploaded files $savingdocmask = ''; -if (empty($conf->global->MAIN_DISABLE_SUGGEST_REF_AS_PREFIX)) -{ +if (empty($conf->global->MAIN_DISABLE_SUGGEST_REF_AS_PREFIX)) { //var_dump($modulepart); - if (in_array($modulepart, array('facture_fournisseur', 'commande_fournisseur', 'facture', 'commande', 'propal', 'supplier_proposal', 'ficheinter', 'contract', 'expedition', 'project', 'project_task', 'expensereport', 'tax', 'produit', 'product_batch'))) - { + if (in_array($modulepart, array('facture_fournisseur', 'commande_fournisseur', 'facture', 'commande', 'propal', 'supplier_proposal', 'ficheinter', 'contract', 'expedition', 'project', 'project_task', 'expensereport', 'tax', 'produit', 'product_batch'))) { $savingdocmask = dol_sanitizeFileName($object->ref).'-__file__'; } } @@ -35,6 +33,6 @@ $formfile->form_attach_new_file( 'accept', '', 1 - ); +); print '
    '; //print ''.$langs->trans("AttachTheNewLineToTheDocument").'
    '; $modulepart = 'expensereport'; $maxheightmini = 48; $relativepath = (!empty($object->ref) ?dol_sanitizeFileName($object->ref) : '').'/'; $filei = 0; - foreach ($arrayoffiles as $file) - { + foreach ($arrayoffiles as $file) { $urlforhref = array(); $filei++; print '
    '; $fileinfo = pathinfo($file['fullname']); - if (image_format_supported($file['name']) > 0) - { + if (image_format_supported($file['name']) > 0) { $minifile = getImageFileNameForSize($file['name'], '_mini'); // For new thumbs using same ext (in lower case however) than original //print $file['path'].'/'.$minifile.'
    '; $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); @@ -46,8 +42,7 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) $error = 0; $thumbshown = ''; - if (preg_match('/\.pdf$/i', $file['name'])) - { + if (preg_match('/\.pdf$/i', $file['name'])) { $urlforhref = getAdvancedPreviewUrl($modulepart, $relativepath.$fileinfo['filename'].'.'.strtolower($fileinfo['extension']), 1, '&entity='.(!empty($object->entity) ? $object->entity : $conf->entity)); $filepdf = $conf->expensereport->dir_output.'/'.$relativepath.$file['name']; @@ -56,27 +51,26 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) $pdfexists = file_exists($filepdf); - if ($pdfexists) - { + if ($pdfexists) { // Conversion du PDF en image png si fichier png non existant - if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) - { - if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) // If you experience trouble with pdf thumb generation and imagick, you can disable here. - { + if (!file_exists($fileimage) || (filemtime($fileimage) < filemtime($filepdf))) { + if (empty($conf->global->MAIN_DISABLE_PDF_THUMBS)) { // If you experience trouble with pdf thumb generation and imagick, you can disable here. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $ret = dol_convert_file($filepdf, 'png', $fileimage, '0'); // Convert first page of PDF into a file _preview.png - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } } } } - if ($pdfexists && !$error) - { + if ($pdfexists && !$error) { $heightforphotref = 70; - if (!empty($conf->dol_optimize_smallscreen)) $heightforphotref = 60; + if (!empty($conf->dol_optimize_smallscreen)) { + $heightforphotref = 60; + } // If the preview file is found - if (file_exists($fileimage)) - { + if (file_exists($fileimage)) { $thumbshown = ''; } } @@ -98,10 +92,8 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) //var_dump(GETPOST($file['relativename'])); var_dump($file['relativename']); var_dump($_FILES['userfile']['name']); // If a file was just uploaded, we check to preselect it if (is_array($_FILES['userfile']['name'])) { - foreach ($_FILES['userfile']['name'] as $tmpfile) - { - if ($file['relativename'] == (GETPOST('savingdocmask', 'alpha') ? dol_sanitizeFileName($object->ref.'-') : '').$tmpfile) - { + foreach ($_FILES['userfile']['name'] as $tmpfile) { + if ($file['relativename'] == (GETPOST('savingdocmask', 'alpha') ? dol_sanitizeFileName($object->ref.'-') : '').$tmpfile) { $checked = ' checked'; break; } elseif ($file['relativename'] && in_array($file['relativename'], GETPOST('attachfile', 'array'))) { @@ -111,8 +103,7 @@ if (empty($conf->global->EXPENSEREPORT_DISABLE_ATTACHMENT_ON_LINES)) } } // If we edit a line already linked, then $filenamelinked is defined to the filename (without path) of linked file - if (!empty($filenamelinked) && $filenamelinked == $file['relativename']) - { + if (!empty($filenamelinked) && $filenamelinked == $file['relativename']) { $checked = ' checked'; } print '
    '; diff --git a/htdocs/expensereport/tpl/linkedobjectblock.tpl.php b/htdocs/expensereport/tpl/linkedobjectblock.tpl.php index a0ef7c353c6..31c5526903b 100644 --- a/htdocs/expensereport/tpl/linkedobjectblock.tpl.php +++ b/htdocs/expensereport/tpl/linkedobjectblock.tpl.php @@ -18,8 +18,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -35,13 +34,12 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $var = true; $total = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { ?>
    trans("ExpenseReport"); ?>getNomUrl(1); ?>getNomUrl(1); ?> date_debut, 'day'); ?> rights->expensereport->lire) { From d6ffdfe8356933665f8d2f4bf33c6c990b5c3f8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= Date: Thu, 25 Feb 2021 22:50:40 +0100 Subject: [PATCH 41/64] code syntax exports externalsite directory --- htdocs/exports/class/export.class.php | 296 +++++++------- htdocs/exports/export.php | 431 +++++++++------------ htdocs/exports/index.php | 9 +- htdocs/externalsite/admin/externalsite.php | 13 +- htdocs/externalsite/frames.php | 31 +- 5 files changed, 364 insertions(+), 416 deletions(-) diff --git a/htdocs/exports/class/export.class.php b/htdocs/exports/class/export.class.php index e4725db3946..174a7271d25 100644 --- a/htdocs/exports/class/export.class.php +++ b/htdocs/exports/class/export.class.php @@ -96,50 +96,49 @@ class Export $modulesdir = dolGetModulesDirs(); - foreach ($modulesdir as $dir) - { + foreach ($modulesdir as $dir) { // Search available exports $handle = @opendir(dol_osencode($dir)); - if (is_resource($handle)) - { + if (is_resource($handle)) { // Search module files - while (($file = readdir($handle)) !== false) - { + while (($file = readdir($handle)) !== false) { $reg = array(); - if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) - { + if (is_readable($dir.$file) && preg_match("/^(mod.*)\.class\.php$/i", $file, $reg)) { $modulename = $reg[1]; // Defined if module is enabled $enabled = true; $part = strtolower(preg_replace('/^mod/i', '', $modulename)); - if ($part == 'propale') $part = 'propal'; - if (empty($conf->$part->enabled)) $enabled = false; + if ($part == 'propale') { + $part = 'propal'; + } + if (empty($conf->$part->enabled)) { + $enabled = false; + } - if ($enabled) - { + if ($enabled) { // Loading Class $file = $dir.$modulename.".class.php"; $classname = $modulename; require_once $file; $module = new $classname($this->db); - if (isset($module->export_code) && is_array($module->export_code)) - { - foreach ($module->export_code as $r => $value) - { + if (isset($module->export_code) && is_array($module->export_code)) { + foreach ($module->export_code as $r => $value) { //print $i.'-'.$filter.'-'.$modulename.'-'.join(',',$module->export_code).'
    '; - if ($filter && ($filter != $module->export_code[$r])) continue; + if ($filter && ($filter != $module->export_code[$r])) { + continue; + } // Test if condition to show are ok - if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) continue; + if (!empty($module->export_enabled[$r]) && !verifCond($module->export_enabled[$r])) { + continue; + } // Test if permissions are ok $bool = true; - if (isset($module->export_permission)) - { - foreach ($module->export_permission[$r] as $val) - { + if (isset($module->export_permission)) { + foreach ($module->export_permission[$r] as $val) { $perm = $val; //print_r("$perm[0]-$perm[1]-$perm[2]
    "); if (!empty($perm[2])) { @@ -147,8 +146,12 @@ class Export } else { $bool = isset($user->rights->{$perm[0]}->{$perm[1]}) ? $user->rights->{$perm[0]}->{$perm[1]} : false; } - if ($perm[0] == 'user' && $user->admin) $bool = true; - if (!$bool) break; + if ($perm[0] == 'user' && $user->admin) { + $bool = true; + } + if (!$bool) { + break; + } } } //print $bool." $perm[0]"."
    "; @@ -158,10 +161,8 @@ class Export // { // Charge fichier lang en rapport $langtoload = $module->getLangFilesArray(); - if (is_array($langtoload)) - { - foreach ($langtoload as $key) - { + if (is_array($langtoload)) { + foreach ($langtoload as $key) { $langs->load($key); } } @@ -234,12 +235,18 @@ class Export $i = 0; //print_r($array_selected); - foreach ($this->array_export_fields[$indice] as $key => $value) - { - if (!array_key_exists($key, $array_selected)) continue; // Field not selected - if (preg_match('/^none\./', $key)) continue; // A field that must not appears into SQL - if ($i > 0) $sql .= ', '; - else $i++; + foreach ($this->array_export_fields[$indice] as $key => $value) { + if (!array_key_exists($key, $array_selected)) { + continue; // Field not selected + } + if (preg_match('/^none\./', $key)) { + continue; // A field that must not appears into SQL + } + if ($i > 0) { + $sql .= ', '; + } else { + $i++; + } if (strpos($key, ' as ') === false) { $newfield = $key.' as '.str_replace(array('.', '-', '(', ')'), '_', $key); @@ -252,14 +259,16 @@ class Export $sql .= $this->array_export_sql_end[$indice]; // Add the WHERE part. Filtering into sql if a filtering array is provided - if (is_array($array_filterValue) && !empty($array_filterValue)) - { + if (is_array($array_filterValue) && !empty($array_filterValue)) { $sqlWhere = ''; // Loop on each condition to add - foreach ($array_filterValue as $key => $value) - { - if (preg_match('/GROUP_CONCAT/i', $key)) continue; - if ($value != '') $sqlWhere .= " and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + foreach ($array_filterValue as $key => $value) { + if (preg_match('/GROUP_CONCAT/i', $key)) { + continue; + } + if ($value != '') { + $sqlWhere .= " and ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + } } $sql .= $sqlWhere; } @@ -268,12 +277,12 @@ class Export $sql .= $this->array_export_sql_order[$indice]; // Add the HAVING part. - if (is_array($array_filterValue) && !empty($array_filterValue)) - { + if (is_array($array_filterValue) && !empty($array_filterValue)) { // Loop on each condition to add - foreach ($array_filterValue as $key => $value) - { - if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + foreach ($array_filterValue as $key => $value) { + if (preg_match('/GROUP_CONCAT/i', $key) and $value != '') { + $sql .= " HAVING ".$this->build_filterQuery($this->array_export_TypeFields[$indice][$key], $key, $array_filterValue[$key]); + } } } @@ -297,37 +306,41 @@ class Export // build the input field on depend of the type of file switch ($InfoFieldList[0]) { case 'Text': - if (!(strpos($ValueField, '%') === false)) + if (!(strpos($ValueField, '%') === false)) { $szFilterQuery .= " ".$NameField." LIKE '".$ValueField."'"; - else $szFilterQuery .= " ".$NameField." = '".$ValueField."'"; + } else { + $szFilterQuery .= " ".$NameField." = '".$ValueField."'"; + } break; case 'Date': - if (strpos($ValueField, "+") > 0) - { + if (strpos($ValueField, "+") > 0) { // mode plage $ValueArray = explode("+", $ValueField); $szFilterQuery = "(".$this->conditionDate($NameField, trim($ValueArray[0]), ">="); $szFilterQuery .= " AND ".$this->conditionDate($NameField, trim($ValueArray[1]), "<=").")"; } else { - if (is_numeric(substr($ValueField, 0, 1))) + if (is_numeric(substr($ValueField, 0, 1))) { $szFilterQuery = $this->conditionDate($NameField, trim($ValueField), "="); - else $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1)); + } else { + $szFilterQuery = $this->conditionDate($NameField, trim(substr($ValueField, 1)), substr($ValueField, 0, 1)); + } } break; case 'Duree': break; case 'Numeric': // si le signe - - if (strpos($ValueField, "+") > 0) - { + if (strpos($ValueField, "+") > 0) { // mode plage $ValueArray = explode("+", $ValueField); $szFilterQuery = "(".$NameField.">=".$ValueArray[0]; $szFilterQuery .= " AND ".$NameField."<=".$ValueArray[1].")"; } else { - if (is_numeric(substr($ValueField, 0, 1))) + if (is_numeric(substr($ValueField, 0, 1))) { $szFilterQuery = " ".$NameField."=".$ValueField; - else $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).substr($ValueField, 1); + } else { + $szFilterQuery = " ".$NameField.substr($ValueField, 0, 1).substr($ValueField, 1); + } } break; case 'Boolean': @@ -335,12 +348,14 @@ class Export break; case 'Status': case 'List': - if (is_numeric($ValueField)) + if (is_numeric($ValueField)) { $szFilterQuery = " ".$NameField."=".$ValueField; - else { - if (!(strpos($ValueField, '%') === false)) + } else { + if (!(strpos($ValueField, '%') === false)) { $szFilterQuery = " ".$NameField." LIKE '".$ValueField."'"; - else $szFilterQuery = " ".$NameField." = '".$ValueField."'"; + } else { + $szFilterQuery = " ".$NameField." = '".$ValueField."'"; + } } break; default: @@ -361,9 +376,13 @@ class Export public function conditionDate($Field, $Value, $Sens) { // TODO date_format is forbidden, not performant and not portable. Use instead BETWEEN - if (strlen($Value) == 4) $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$Value."'"; - elseif (strlen($Value) == 6) $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'"; - else $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value; + if (strlen($Value) == 4) { + $Condition = " date_format(".$Field.",'%Y') ".$Sens." '".$Value."'"; + } elseif (strlen($Value) == 6) { + $Condition = " date_format(".$Field.",'%Y%m') ".$Sens." '".$Value."'"; + } else { + $Condition = " date_format(".$Field.",'%Y%m%d') ".$Sens." ".$Value; + } return $Condition; } @@ -385,8 +404,7 @@ class Export $InfoFieldList = explode(":", $TypeField); // build the input field on depend of the type of file - switch ($InfoFieldList[0]) - { + switch ($InfoFieldList[0]) { case 'Text': case 'Date': $szFilterField = ''; @@ -403,15 +421,21 @@ class Export case 'Boolean': $szFilterField = '"; break; @@ -422,51 +446,50 @@ class Export // 3 : Name of field with key (if it is not "rowid"). Used this field as key for combo list. // 4 : Name of element for getEntity(). - if (!empty($InfoFieldList[3])) + if (!empty($InfoFieldList[3])) { $keyList = $InfoFieldList[3]; - else $keyList = 'rowid'; + } else { + $keyList = 'rowid'; + } $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3]) ? '' : ', '.$InfoFieldList[3].' as code'); - if ($InfoFieldList[1] == 'c_stcomm') $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3]) ? '' : ', '.$InfoFieldList[3].' as code'); - if ($InfoFieldList[1] == 'c_country') $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label, code as code'; + if ($InfoFieldList[1] == 'c_stcomm') { + $sql = 'SELECT id as id, '.$keyList.' as rowid, '.$InfoFieldList[2].' as label'.(empty($InfoFieldList[3]) ? '' : ', '.$InfoFieldList[3].' as code'); + } + if ($InfoFieldList[1] == 'c_country') { + $sql = 'SELECT '.$keyList.' as rowid, '.$InfoFieldList[2].' as label, code as code'; + } $sql .= ' FROM '.MAIN_DB_PREFIX.$InfoFieldList[1]; if (!empty($InfoFieldList[4])) { $sql .= ' WHERE entity IN ('.getEntity($InfoFieldList[4]).')'; } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $szFilterField = '"; $this->db->free($resql); - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } break; } @@ -542,8 +567,7 @@ class Export dol_syslog(__METHOD__." ".$model.", ".$datatoexport.", ".implode(",", $array_selected)); // Check parameters or context properties - if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) - { + if (empty($this->array_export_fields) || !is_array($this->array_export_fields)) { $this->error = "ErrorBadParameter"; dol_syslog($this->error, LOG_ERR); return -1; @@ -556,22 +580,20 @@ class Export require_once $dir.$file; $objmodel = new $classname($this->db); - if (!empty($sqlquery)) $sql = $sqlquery; - else { + if (!empty($sqlquery)) { + $sql = $sqlquery; + } else { // Define value for indice from $datatoexport $foundindice = 0; - foreach ($this->array_export_code as $key => $dataset) - { - if ($datatoexport == $dataset) - { + foreach ($this->array_export_code as $key => $dataset) { + if ($datatoexport == $dataset) { $indice = $key; $foundindice++; //print "Found indice = ".$indice." for dataset=".$datatoexport."\n"; break; } } - if (empty($foundindice)) - { + if (empty($foundindice)) { $this->error = "ErrorBadParameter can't find dataset ".$datatoexport." into preload arrays this->array_export_code"; return -1; } @@ -582,13 +604,11 @@ class Export $this->sqlusedforexport = $sql; dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { //$this->array_export_label[$indice] if (!empty($conf->global->EXPORT_PREFIX_SPEC)) { $filename = $conf->global->EXPORT_PREFIX_SPEC."_".$datatoexport; - } - else { + } else { $filename = "export_".$datatoexport; } $filename .= '.'.$objmodel->getDriverExtension(); @@ -600,55 +620,48 @@ class Export dol_mkdir($dirname); $result = $objmodel->open_file($dirname."/".$filename, $outputlangs); - if ($result >= 0) - { + if ($result >= 0) { // Genere en-tete $objmodel->write_header($outputlangs); // Genere ligne de titre $objmodel->write_title($this->array_export_fields[$indice], $array_selected, $outputlangs, isset($this->array_export_TypeFields[$indice]) ? $this->array_export_TypeFields[$indice] : null); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { // Process special operations - if (!empty($this->array_export_special[$indice])) - { - foreach ($this->array_export_special[$indice] as $key => $value) - { - if (!array_key_exists($key, $array_selected)) continue; // Field not selected + if (!empty($this->array_export_special[$indice])) { + foreach ($this->array_export_special[$indice] as $key => $value) { + if (!array_key_exists($key, $array_selected)) { + continue; // Field not selected + } // Operation NULLIFNEG - if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') - { + if ($this->array_export_special[$indice][$key] == 'NULLIFNEG') { //$alias=$this->array_export_alias[$indice][$key]; $alias = str_replace(array('.', '-', '(', ')'), '_', $key); - if ($obj->$alias < 0) $obj->$alias = ''; - } - // Operation ZEROIFNEG - elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') - { + if ($obj->$alias < 0) { + $obj->$alias = ''; + } + } elseif ($this->array_export_special[$indice][$key] == 'ZEROIFNEG') { + // Operation ZEROIFNEG //$alias=$this->array_export_alias[$indice][$key]; $alias = str_replace(array('.', '-', '(', ')'), '_', $key); - if ($obj->$alias < 0) $obj->$alias = '0'; - } - // Operation GETNUMOPENDAYS (for Holiday module) - elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') - { + if ($obj->$alias < 0) { + $obj->$alias = '0'; + } + } elseif ($this->array_export_special[$indice][$key] == 'getNumOpenDays') { + // Operation GETNUMOPENDAYS (for Holiday module) include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; //$alias=$this->array_export_alias[$indice][$key]; $alias = str_replace(array('.', '-', '(', ')'), '_', $key); $obj->$alias = num_open_day(dol_stringtotime($obj->d_date_debut, 1), dol_stringtotime($obj->d_date_fin, 1), 0, 1, $obj->d_halfday, $mysoc->country_code); - } - // Operation INVOICEREMAINTOPAY - elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') - { + } elseif ($this->array_export_special[$indice][$key] == 'getRemainToPay') { + // Operation INVOICEREMAINTOPAY //$alias=$this->array_export_alias[$indice][$key]; $alias = str_replace(array('.', '-', '(', ')'), '_', $key); $remaintopay = ''; - if ($obj->f_rowid > 0) - { + if ($obj->f_rowid > 0) { global $tmpobjforcomputecall; - if (!is_object($tmpobjforcomputecall)) - { + if (!is_object($tmpobjforcomputecall)) { include_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $tmpobjforcomputecall = new Facture($this->db); } @@ -725,8 +738,7 @@ class Export dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -751,11 +763,9 @@ class Export dol_syslog("Export::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $obj = $this->db->fetch_object($result); - if ($obj) - { + if ($obj) { $this->id = $obj->rowid; $this->model_name = $obj->label; $this->datatoexport = $obj->type; @@ -794,13 +804,13 @@ class Export dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -829,12 +839,10 @@ class Export $sql .= " ORDER BY rowid"; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); $keyModel = array_search($obj->type, $this->array_export_code); print "
     
    '; //print img_object($objexport->array_export_module[$key]->getName(),$export->array_export_module[$key]->picto).' '; print $objexport->array_export_module[$key]->getName(); @@ -466,7 +451,7 @@ if ($step == 1 || !$datatoexport) } else { print $langs->trans("NotEnoughPermissions"); } - print '
    '.$langs->trans("NoExportableData").'
    '.$langs->trans("DatasetToExport").''; - $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); - $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); - print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; - print $objexport->array_export_label[0]; - print '
    '.$langs->trans("DatasetToExport").''; + $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); + $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); + print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; + print $objexport->array_export_label[0]; + print '
    '; print '
    '; @@ -568,8 +552,7 @@ if ($step == 2 && $datatoexport) $i = 0; - foreach ($fieldsarray as $code=>$label) - { + foreach ($fieldsarray as $code => $label) { print ''; $i++; @@ -583,8 +566,7 @@ if ($step == 2 && $datatoexport) //print $code.'-'.$label.'-'.$entity; $tmparray = explode(':', $entityicon); - if (count($tmparray) >= 2) - { + if (count($tmparray) >= 2) { $entityicon = $tmparray[0]; $entitylang = $tmparray[1]; } @@ -595,27 +577,22 @@ if ($step == 2 && $datatoexport) $tablename = getablenamefromfield($code, $sqlmaxforexport); $htmltext = ''.$langs->trans("Name").": ".$text.'
    '; - if (!empty($objexport->array_export_special[0][$code])) - { + if (!empty($objexport->array_export_special[0][$code])) { $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]."
    "; } else { $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)."
    "; } - if (!empty($objexport->array_export_examplevalues[0][$code])) - { + if (!empty($objexport->array_export_examplevalues[0][$code])) { $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].'
    '; } - if (!empty($objexport->array_export_TypeFields[0][$code])) - { + if (!empty($objexport->array_export_TypeFields[0][$code])) { $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].'
    '; } - if (!empty($objexport->array_export_help[0][$code])) - { + if (!empty($objexport->array_export_help[0][$code])) { $htmltext .= ''.$langs->trans("Help").': '.$langs->trans($objexport->array_export_help[0][$code]).'
    '; } - if (isset($array_selected[$code]) && $array_selected[$code]) - { + if (isset($array_selected[$code]) && $array_selected[$code]) { // Selected fields print ' '; print ''.img_left('default', 0, 'style="max-width: 20px"').''; @@ -642,15 +619,13 @@ if ($step == 2 && $datatoexport) print '
    '; /* - * Barre d'action - */ + * Barre d'action + */ print '
    '; - if (count($array_selected)) - { + if (count($array_selected)) { // If filters exist - if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { print ''.$langs->trans("NextStep").''; } else { print ''.$langs->trans("NextStep").''; @@ -662,10 +637,8 @@ if ($step == 2 && $datatoexport) print '
    '; } -if ($step == 3 && $datatoexport) -{ - if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired - { +if ($step == 3 && $datatoexport) { + if (count($array_selected) < 1) { // This occurs when going back to page after sessecion expired // Switch to step 2 header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport); exit; @@ -713,8 +686,7 @@ if ($step == 3 && $datatoexport) // Nbre champs exportes print ''.$langs->trans("ExportedFields").''; $list = ''; - foreach ($array_selected as $code=>$value) - { + foreach ($array_selected as $code => $value) { $list .= (!empty($list) ? ', ' : ''); $list .= (isset($objexport->array_export_fields[0][$code]) ? $langs->trans($objexport->array_export_fields[0][$code]) : ''); } @@ -755,8 +727,7 @@ if ($step == 3 && $datatoexport) $i = 0; // on boucle sur les champs - foreach ($fieldsarray as $code => $label) - { + foreach ($fieldsarray as $code => $label) { print ''; $i++; @@ -767,8 +738,7 @@ if ($step == 3 && $datatoexport) print ''; // If value of entityicon=entitylang='icon:Label' $tmparray = explode(':', $entityicon); - if (count($tmparray) >= 2) - { + if (count($tmparray) >= 2) { $entityicon = $tmparray[0]; $entitylang = $tmparray[1]; } @@ -782,22 +752,18 @@ if ($step == 3 && $datatoexport) $tablename = getablenamefromfield($code, $sqlmaxforexport); $htmltext = ''.$langs->trans("Name").': '.$text.'
    '; - if (!empty($objexport->array_export_special[0][$code])) - { + if (!empty($objexport->array_export_special[0][$code])) { $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]."
    "; } else { $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)."
    "; } - if (!empty($objexport->array_export_examplevalues[0][$code])) - { + if (!empty($objexport->array_export_examplevalues[0][$code])) { $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].'
    '; } - if (!empty($objexport->array_export_TypeFields[0][$code])) - { + if (!empty($objexport->array_export_TypeFields[0][$code])) { $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].'
    '; } - if (!empty($objexport->array_export_help[0][$code])) - { + if (!empty($objexport->array_export_help[0][$code])) { $htmltext .= ''.$langs->trans("Help").': '.$langs->trans($objexport->array_export_help[0][$code]).'
    '; } @@ -807,11 +773,9 @@ if ($step == 3 && $datatoexport) // Filter value print ''; - if (!empty($Typefieldsarray[$code])) // Example: Text, List:c_country:label:rowid, Number, Boolean - { + if (!empty($Typefieldsarray[$code])) { // Example: Text, List:c_country:label:rowid, Number, Boolean $szInfoFiltre = $objexport->genDocFilter($Typefieldsarray[$code]); - if ($szInfoFiltre) // Is there an info help for this filter ? - { + if ($szInfoFiltre) { // Is there an info help for this filter ? $tmp = $objexport->build_filterField($Typefieldsarray[$code], $code, $ValueFilter); print $form->textwithpicto($tmp, $szInfoFiltre); } else { @@ -837,10 +801,8 @@ if ($step == 3 && $datatoexport) print '
    '; } -if ($step == 4 && $datatoexport) -{ - if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired - { +if ($step == 4 && $datatoexport) { + if (count($array_selected) < 1) { // This occurs when going back to page after sessecion expired // Switch to step 2 header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport); exit; @@ -862,8 +824,7 @@ if ($step == 4 && $datatoexport) $h++; // If filters exist - if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport; $head[$h][1] = $langs->trans("Step")." 3"; $h++; @@ -888,20 +849,19 @@ if ($step == 4 && $datatoexport) print $objexport->array_export_module[0]->getName(); print ''; - // Lot de donnees a exporter - print ''.$langs->trans("DatasetToExport").''; - print ''; + // Lot de donnees a exporter + print ''.$langs->trans("DatasetToExport").''; + print ''; $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); - print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; - print $objexport->array_export_label[0]; - print ''; + print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; + print $objexport->array_export_label[0]; + print ''; // List of exported fields print ''.$langs->trans("ExportedFields").''; $list = ''; - foreach ($array_selected as $code=>$value) - { + foreach ($array_selected as $code => $value) { $list .= (!empty($list) ? ', ' : ''); $list .= $langs->trans($objexport->array_export_fields[0][$code]); } @@ -909,19 +869,18 @@ if ($step == 4 && $datatoexport) print ''; // List of filtered fiels - if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { print ''.$langs->trans("FilteredFields").''; $list = ''; - if (!empty($array_filtervalue)) - { - foreach ($array_filtervalue as $code=>$value) - { - if (isset($objexport->array_export_fields[0][$code])) - { + if (!empty($array_filtervalue)) { + foreach ($array_filtervalue as $code => $value) { + if (isset($objexport->array_export_fields[0][$code])) { $list .= ($list ? ', ' : ''); - if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : ''); - else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'"; + if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) { + $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : ''); + } else { + $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'"; + } } } } @@ -949,8 +908,7 @@ if ($step == 4 && $datatoexport) //print ''.$langs->trans("FieldsTitle").''; print ''; - foreach ($array_selected as $code=>$value) - { + foreach ($array_selected as $code => $value) { print ''; $entity = (!empty($objexport->array_export_entities[0][$code]) ? $objexport->array_export_entities[0][$code] : $objexport->array_export_icon[0]); @@ -960,8 +918,7 @@ if ($step == 4 && $datatoexport) print ''; // If value of entityicon=entitylang='icon:Label' $tmparray = explode(':', $entityicon); - if (count($tmparray) >= 2) - { + if (count($tmparray) >= 2) { $entityicon = $tmparray[0]; $entitylang = $tmparray[1]; } @@ -974,22 +931,18 @@ if ($step == 4 && $datatoexport) $tablename = getablenamefromfield($code, $sqlmaxforexport); $htmltext = ''.$langs->trans("Name").': '.$text.'
    '; - if (!empty($objexport->array_export_special[0][$code])) - { + if (!empty($objexport->array_export_special[0][$code])) { $htmltext .= ''.$langs->trans("ComputedField")." -> ".$langs->trans("Method")." : ".$objexport->array_export_special[0][$code]."
    "; } else { $htmltext .= ''.$langs->trans("Table")." -> ".$langs->trans("Field").": ".$tablename." -> ".preg_replace('/^.*\./', '', $code)."
    "; } - if (!empty($objexport->array_export_examplevalues[0][$code])) - { + if (!empty($objexport->array_export_examplevalues[0][$code])) { $htmltext .= ''.$langs->trans("SourceExample").': '.$objexport->array_export_examplevalues[0][$code].'
    '; } - if (!empty($objexport->array_export_TypeFields[0][$code])) - { + if (!empty($objexport->array_export_TypeFields[0][$code])) { $htmltext .= ''.$langs->trans("Type").': '.$objexport->array_export_TypeFields[0][$code].'
    '; } - if (!empty($objexport->array_export_help[0][$code])) - { + if (!empty($objexport->array_export_help[0][$code])) { $htmltext .= ''.$langs->trans("Help").': '.$langs->trans($objexport->array_export_help[0][$code]).'
    '; } @@ -1001,8 +954,12 @@ if ($step == 4 && $datatoexport) print ''; print $value.' '; print ''; - if ($value < count($array_selected)) print ''.img_down().''; - if ($value > 1) print ''.img_up().''; + if ($value < count($array_selected)) { + print ''.img_down().''; + } + if ($value > 1) { + print ''.img_up().''; + } print ''; //print ' '; @@ -1017,13 +974,12 @@ if ($step == 4 && $datatoexport) print '
    '; /* - * Barre d'action - * - */ + * Barre d'action + * + */ print '
    '; - if (count($array_selected)) - { + if (count($array_selected)) { print ''.$langs->trans("NextStep").''; } @@ -1031,8 +987,7 @@ if ($step == 4 && $datatoexport) // Area for profils export - if (count($array_selected)) - { + if (count($array_selected)) { print '
    '; print '
    '; @@ -1062,15 +1017,15 @@ if ($step == 4 && $datatoexport) $sql = "SELECT rowid, label"; $sql .= " FROM ".MAIN_DB_PREFIX."export_model"; $sql .= " WHERE type = '".$db->escape($datatoexport)."'"; - if (empty($conf->global->EXPORTS_SHARE_MODELS))$sql .= " AND fk_user=".$user->id; + if (empty($conf->global->EXPORTS_SHARE_MODELS)) { + $sql .= " AND fk_user=".$user->id; + } $sql .= " ORDER BY rowid"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print ''; print $obj->label; @@ -1092,10 +1047,8 @@ if ($step == 4 && $datatoexport) } } -if ($step == 5 && $datatoexport) -{ - if (count($array_selected) < 1) // This occurs when going back to page after sessecion expired - { +if ($step == 5 && $datatoexport) { + if (count($array_selected) < 1) { // This occurs when going back to page after sessecion expired // Switch to step 2 header("Location: ".DOL_URL_ROOT.'/exports/export.php?step=2&datatoexport='.$datatoexport); exit; @@ -1117,8 +1070,7 @@ if ($step == 5 && $datatoexport) $h++; // si le filtrage est parametre pour l'export ou pas - if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if ($usefilters && isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { $head[$h][0] = DOL_URL_ROOT.'/exports/export.php?step=3&datatoexport='.$datatoexport; $head[$h][1] = $langs->trans("Step")." 3"; $h++; @@ -1137,10 +1089,9 @@ if ($step == 5 && $datatoexport) print dol_get_fiche_head($head, $hselected, '', -2); /* - * Confirmation suppression fichier - */ - if ($action == 'remove_file') - { + * Confirmation suppression fichier + */ + if ($action == 'remove_file') { print $form->formconfirm($_SERVER["PHP_SELF"].'?step=5&datatoexport='.$datatoexport.'&file='.urlencode(GETPOST("file")), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1); } @@ -1156,39 +1107,37 @@ if ($step == 5 && $datatoexport) print $objexport->array_export_module[0]->getName(); print ''; - // Dataset to export - print ''.$langs->trans("DatasetToExport").''; - print ''; - $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); - $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); - print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; - print $objexport->array_export_label[0]; - print ''; + // Dataset to export + print ''.$langs->trans("DatasetToExport").''; + print ''; + $entity = preg_replace('/:.*$/', '', $objexport->array_export_icon[0]); + $entityicon = strtolower(!empty($entitytoicon[$entity]) ? $entitytoicon[$entity] : $entity); + print img_object($objexport->array_export_module[0]->getName(), $entityicon).' '; + print $objexport->array_export_label[0]; + print ''; // List of exported fields print ''.$langs->trans("ExportedFields").''; $list = ''; - foreach ($array_selected as $code=>$label) - { + foreach ($array_selected as $code => $label) { $list .= (!empty($list) ? ', ' : ''); $list .= $langs->trans($objexport->array_export_fields[0][$code]); } print ''.$list.''; // List of filtered fields - if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) - { + if (isset($objexport->array_export_TypeFields[0]) && is_array($objexport->array_export_TypeFields[0])) { print ''.$langs->trans("FilteredFields").''; $list = ''; - if (!empty($array_filtervalue)) - { - foreach ($array_filtervalue as $code=>$value) - { - if (isset($objexport->array_export_fields[0][$code])) - { + if (!empty($array_filtervalue)) { + foreach ($array_filtervalue as $code => $value) { + if (isset($objexport->array_export_fields[0][$code])) { $list .= ($list ? ', ' : ''); - if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : ''); - else $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'"; + if (isset($array_filtervalue[$code]) && preg_match('/^\s*[<>]/', $array_filtervalue[$code])) { + $list .= $langs->trans($objexport->array_export_fields[0][$code]).(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : ''); + } else { + $list .= $langs->trans($objexport->array_export_fields[0][$code])."='".(isset($array_filtervalue[$code]) ? $array_filtervalue[$code] : '')."'"; + } } } } @@ -1211,10 +1160,8 @@ if ($step == 5 && $datatoexport) $liste = $objmodelexport->liste_modeles($db); $listeall = $liste; - foreach ($listeall as $key => $val) - { - if (preg_match('/__\(Disabled\)__/', $listeall[$key])) - { + foreach ($listeall as $key => $val) { + if (preg_match('/__\(Disabled\)__/', $listeall[$key])) { $listeall[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $listeall[$key]); unset($liste[$key]); } @@ -1237,13 +1184,14 @@ if ($step == 5 && $datatoexport) print '
    '; - if ($sqlusedforexport && $user->admin) - { + if ($sqlusedforexport && $user->admin) { print info_admin($langs->trans("SQLUsedForExport").':
    '.$sqlusedforexport, 0, 0, 1, '', 'TechnicalInformation'); } - if (!is_dir($conf->export->dir_temp)) dol_mkdir($conf->export->dir_temp); + if (!is_dir($conf->export->dir_temp)) { + dol_mkdir($conf->export->dir_temp); + } // Show existing generated documents // NB: La fonction show_documents rescanne les modules qd genallowed=1, sinon prend $liste @@ -1273,8 +1221,9 @@ function getablenamefromfield($code, $sqlmaxforexport) $newsql = preg_replace('/^(.*) FROM /i', '', $newsql); // Remove part before the FROM $newsql = preg_replace('/WHERE (.*)$/i', '', $newsql); // Remove part after the WHERE so we have now only list of table aliases in a string. We must keep the ' ' before WHERE - if (preg_match($regexstring, $newsql, $reg)) - { + if (preg_match($regexstring, $newsql, $reg)) { return $reg[1]; // The tablename - } else return ''; + } else { + return ''; + } } diff --git a/htdocs/exports/index.php b/htdocs/exports/index.php index 79655a19b2f..3bff58453ab 100644 --- a/htdocs/exports/index.php +++ b/htdocs/exports/index.php @@ -48,8 +48,7 @@ print '
    '; print '
    '; -if (count($export->array_export_code)) -{ +if (count($export->array_export_code)) { print dolGetButtonTitle($langs->trans('NewExport'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/exports/export.php?leftmenu=export', '', $user->rights->export->creer); } print '
    '; @@ -71,10 +70,8 @@ include_once DOL_DOCUMENT_ROOT.'/core/modules/export/modules_export.php'; $model = new ModeleExports($db); $liste = $model->liste_modeles($db); // This is not a static method for exports because method load non static properties -foreach ($liste as $key => $val) -{ - if (preg_match('/__\(Disabled\)__/', $liste[$key])) - { +foreach ($liste as $key => $val) { + if (preg_match('/__\(Disabled\)__/', $liste[$key])) { $liste[$key] = preg_replace('/__\(Disabled\)__/', '('.$langs->transnoentitiesnoconv("Disabled").')', $liste[$key]); } diff --git a/htdocs/externalsite/admin/externalsite.php b/htdocs/externalsite/admin/externalsite.php index 66c6d265dec..47f0a3d57be 100644 --- a/htdocs/externalsite/admin/externalsite.php +++ b/htdocs/externalsite/admin/externalsite.php @@ -26,14 +26,17 @@ * \brief Page de configuration du module externalsite */ -if (!defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check anti CSRF attack test +if (!defined('NOSCANPOSTFORINJECTION')) { + define('NOSCANPOSTFORINJECTION', '1'); // Do not check anti CSRF attack test +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php'; -if (!$user->admin) +if (!$user->admin) { accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('admin', 'other', 'externalsite')); @@ -43,8 +46,7 @@ $def = array(); $action = GETPOST('action', 'aZ09'); // Sauvegardes parametres -if ($action == 'update') -{ +if ($action == 'update') { $i = 0; $db->begin(); @@ -55,8 +57,7 @@ if ($action == 'update') $i += dolibarr_set_const($db, 'EXTERNALSITE_LABEL', trim($label), 'chaine', 0, '', $conf->entity); $i += dolibarr_set_const($db, 'EXTERNALSITE_URL', trim($exturl), 'chaine', 0, '', $conf->entity); - if ($i >= 2) - { + if ($i >= 2) { $db->commit(); setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); } else { diff --git a/htdocs/externalsite/frames.php b/htdocs/externalsite/frames.php index 4827d832af4..04b48ba3cad 100644 --- a/htdocs/externalsite/frames.php +++ b/htdocs/externalsite/frames.php @@ -44,35 +44,29 @@ $keyforcontent = GETPOST('keyforcontent', 'aZ09'); * View */ -if (empty($keyforcontent) && empty($conf->global->EXTERNALSITE_URL)) -{ +if (empty($keyforcontent) && empty($conf->global->EXTERNALSITE_URL)) { llxHeader(); print '
    '.$langs->trans('ExternalSiteModuleNotComplete').'
    '; llxFooter(); exit; } -if (!empty($keyforcontent)) -{ +if (!empty($keyforcontent)) { llxHeader(); print '
    '; if (!preg_match('/EXTERNAL_SITE_CONTENT_/', $keyforcontent) - && !preg_match('/EXTERNAL_SITE_URL_/', $keyforcontent)) - { + && !preg_match('/EXTERNAL_SITE_URL_/', $keyforcontent)) { $langs->load("errors"); print $langs->trans("ErrorBadSyntaxForParamKeyForContent", 'EXTERNAL_SITE_CONTENT_', 'EXTERNAL_SITE_URL_'); - } elseif (empty($conf->global->$keyforcontent)) - { + } elseif (empty($conf->global->$keyforcontent)) { $langs->load("errors"); print $langs->trans("ErrorVariableKeyForContentMustBeSet", 'EXTERNAL_SITE_CONTENT_'.$keyforcontent, 'EXTERNAL_SITE_URL_'.$keyforcontent); } else { - if (preg_match('/EXTERNAL_SITE_CONTENT_/', $keyforcontent)) - { + if (preg_match('/EXTERNAL_SITE_CONTENT_/', $keyforcontent)) { print $conf->global->$keyforcontent; - } elseif (preg_match('/EXTERNAL_SITE_URL_/', $keyforcontent)) - { + } elseif (preg_match('/EXTERNAL_SITE_URL_/', $keyforcontent)) { /*print " @@ -80,17 +74,17 @@ if (!empty($keyforcontent)) global->MAIN_MENU_INVERT)?"rows":"cols")."=\"".$heightforframes.",*\" border=0 framespacing=0 frameborder=0> - + "; print ''; print " - - <body> + <noframes> + <body> - </body> - + + @@ -111,8 +105,7 @@ if (!empty($keyforcontent)) print '<div>'; llxFooter(); } else { - if (preg_match('/^\//', $conf->global->EXTERNALSITE_URL) || preg_match('/^http/i', $conf->global->EXTERNALSITE_URL)) - { + if (preg_match('/^\//', $conf->global->EXTERNALSITE_URL) || preg_match('/^http/i', $conf->global->EXTERNALSITE_URL)) { print " <html> <head> From fb07484d3fe03b58af40dd758426532edd29c19d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= <frederic.france@free.fr> Date: Thu, 25 Feb 2021 23:00:32 +0100 Subject: [PATCH 42/64] code syntax fichinter directory --- .../fichinter/admin/fichinter_extrafields.php | 17 +- .../admin/fichinterdet_extrafields.php | 17 +- htdocs/fichinter/card-rec.php | 89 ++- htdocs/fichinter/card.php | 695 ++++++++---------- .../class/api_interventions.class.php | 102 +-- htdocs/fichinter/class/fichinter.class.php | 406 +++++----- htdocs/fichinter/class/fichinterrec.class.php | 57 +- .../fichinter/class/fichinterstats.class.php | 34 +- htdocs/fichinter/contact.php | 57 +- htdocs/fichinter/document.php | 28 +- htdocs/fichinter/index.php | 154 ++-- htdocs/fichinter/info.php | 16 +- htdocs/fichinter/list.php | 405 ++++++---- htdocs/fichinter/note.php | 13 +- htdocs/fichinter/stats/index.php | 70 +- .../fichinter/tpl/linkedobjectblock.tpl.php | 16 +- 16 files changed, 1138 insertions(+), 1038 deletions(-) diff --git a/htdocs/fichinter/admin/fichinter_extrafields.php b/htdocs/fichinter/admin/fichinter_extrafields.php index 0fa5a930f05..2fec51a0f5b 100644 --- a/htdocs/fichinter/admin/fichinter_extrafields.php +++ b/htdocs/fichinter/admin/fichinter_extrafields.php @@ -39,13 +39,17 @@ $form = new Form($db); // List of supported format $tmptype2label = ExtraFields::$type2label; $type2label = array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); +foreach ($tmptype2label as $key => $val) { + $type2label[$key] = $langs->transnoentitiesnoconv($val); +} $action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'fichinter'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -77,8 +81,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -91,8 +94,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -104,8 +106,7 @@ if ($action == 'create') /* Edition of an optional field */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/fichinter/admin/fichinterdet_extrafields.php b/htdocs/fichinter/admin/fichinterdet_extrafields.php index f648548c3b4..1cbdeb4cf0a 100644 --- a/htdocs/fichinter/admin/fichinterdet_extrafields.php +++ b/htdocs/fichinter/admin/fichinterdet_extrafields.php @@ -39,13 +39,17 @@ $form = new Form($db); // List of supported format $tmptype2label = ExtraFields::$type2label; $type2label = array(''); -foreach ($tmptype2label as $key => $val) $type2label[$key] = $langs->transnoentitiesnoconv($val); +foreach ($tmptype2label as $key => $val) { + $type2label[$key] = $langs->transnoentitiesnoconv($val); +} $action = GETPOST('action', 'aZ09'); $attrname = GETPOST('attrname', 'alpha'); $elementtype = 'fichinterdet'; //Must be the $element of the class that manage extrafield -if (!$user->admin) accessforbidden(); +if (!$user->admin) { + accessforbidden(); +} /* @@ -78,8 +82,7 @@ print dol_get_fiche_end(); // Buttons -if ($action != 'create' && $action != 'edit') -{ +if ($action != 'create' && $action != 'edit') { print '<div class="tabsAction">'; print "<a class=\"butAction\" href=\"".$_SERVER["PHP_SELF"]."?action=create#newattrib\">".$langs->trans("NewAttribute")."</a>"; print "</div>"; @@ -92,8 +95,7 @@ if ($action != 'create' && $action != 'edit') /* */ /* ************************************************************************** */ -if ($action == 'create') -{ +if ($action == 'create') { print '<br><div id="newattrib"></div>'; print load_fiche_titre($langs->trans('NewAttribute')); @@ -105,8 +107,7 @@ if ($action == 'create') /* Edition d'un champ optionnel */ /* */ /* ************************************************************************** */ -if ($action == 'edit' && !empty($attrname)) -{ +if ($action == 'edit' && !empty($attrname)) { print "<br>"; print load_fiche_titre($langs->trans("FieldEdition", $attrname)); diff --git a/htdocs/fichinter/card-rec.php b/htdocs/fichinter/card-rec.php index bee9ac1c9fe..775f83ef500 100644 --- a/htdocs/fichinter/card-rec.php +++ b/htdocs/fichinter/card-rec.php @@ -52,22 +52,29 @@ $langs->loadLangs(array("interventions", "admin", "compta", "bills")); // Security check $id = (GETPOST('fichinterid', 'int') ?GETPOST('fichinterid', 'int') : GETPOST('id', 'int')); $action = GETPOST('action', 'aZ09'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $objecttype = 'fichinter_rec'; -if ($action == "create" || $action == "add") $objecttype = ''; +if ($action == "create" || $action == "add") { + $objecttype = ''; +} $result = restrictedArea($user, 'ficheinter', $id, $objecttype); -if ($page == -1) +if ($page == -1) { $page = 0; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $offset = $limit * $page; -if ($sortorder == "") +if ($sortorder == "") { $sortorder = "DESC"; +} -if ($sortfield == "") +if ($sortfield == "") { $sortfield = "f.datec"; +} $object = new FichinterRec($db); $extrafields = new ExtraFields($db); @@ -212,7 +219,9 @@ if ($action == 'add') { // Set next date of execution $object->fetch($id); $date = dol_mktime(GETPOST('date_whenhour'), GETPOST('date_whenmin'), 0, GETPOST('date_whenmonth'), GETPOST('date_whenday'), GETPOST('date_whenyear')); - if (!empty($date)) $object->setNextDate($date); + if (!empty($date)) { + $object->setNextDate($date); + } } elseif ($action == 'setnb_gen_max' && $user->rights->ficheinter->creer) { // Set max period $object->fetch($id); @@ -261,8 +270,12 @@ if ($action == 'create') { print dol_get_fiche_head(); $rowspan = 4; - if (!empty($conf->projet->enabled) && $object->fk_project > 0) $rowspan++; - if (!empty($conf->contrat->enabled) && $object->fk_contrat > 0) $rowspan++; + if (!empty($conf->projet->enabled) && $object->fk_project > 0) { + $rowspan++; + } + if (!empty($conf->contrat->enabled) && $object->fk_contrat > 0) { + $rowspan++; + } print '<table class="border centpercent">'; @@ -595,9 +608,11 @@ if ($action == 'create') { print '<td class="left"><input type="submit" class="button" value="'.$langs->trans("Modify").'"></td>'; print '</tr></table></form>'; } else { - if ($object->frequency > 0) + if ($object->frequency > 0) { print $langs->trans('FrequencyPer_'.$object->unit_frequency, $object->frequency); - else print $langs->trans("NotARecurringInterventionalTemplate"); + } else { + print $langs->trans("NotARecurringInterventionalTemplate"); + } } print '</td></tr>'; @@ -619,12 +634,16 @@ if ($action == 'create') { print '<tr><td>'; if ($user->rights->ficheinter->creer && ($action == 'nb_gen_max' || $object->frequency > 0)) { print $form->editfieldkey($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max, $object, $user->rights->facture->creer); - } else print $langs->trans("MaxPeriodNumber"); + } else { + print $langs->trans("MaxPeriodNumber"); + } print '</td><td>'; if ($action == 'nb_gen_max' || $object->frequency > 0) { print $form->editfieldval($langs->trans("MaxPeriodNumber"), 'nb_gen_max', $object->nb_gen_max ? $object->nb_gen_max : '', $object, $user->rights->facture->creer); - } else print ''; + } else { + print ''; + } print '</td>'; print '</tr>'; @@ -688,13 +707,19 @@ if ($action == 'create') { $i = 0; while ($i < $num) { // Show product and description - if (isset($object->lines[$i]->product_type)) + if (isset($object->lines[$i]->product_type)) { $type = $object->lines[$i]->product_type; - else $object->lines[$i]->fk_product_type; + } else { + $object->lines[$i]->fk_product_type; + } // Try to enhance type detection using date_start and date_end for free lines when type // was not saved. - if (!empty($objp->date_start)) $type = 1; - if (!empty($objp->date_end)) $type = 1; + if (!empty($objp->date_start)) { + $type = 1; + } + if (!empty($objp->date_end)) { + $type = 1; + } // Show line print '<tr class="oddeven">'; @@ -727,7 +752,9 @@ if ($action == 'create') { print $langs->trans('Delete').'</a></div>'; } print '</div>'; - } else print $langs->trans("ErrorRecordNotFound"); + } else { + print $langs->trans("ErrorRecordNotFound"); + } } else { /* * List mode @@ -743,14 +770,24 @@ if ($action == 'create') { } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity = ".$conf->entity; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } if (!$user->rights->societe->client->voir && !$socid) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } - if ($search_ref) $sql .= natural_search('f.titre', $search_ref); - if ($search_societe) $sql .= natural_search('s.nom', $search_societe); - if ($search_frequency == '1') $sql .= ' AND f.frequency > 0'; - if ($search_frequency == '0') $sql .= ' AND (f.frequency IS NULL or f.frequency = 0)'; + if ($search_ref) { + $sql .= natural_search('f.titre', $search_ref); + } + if ($search_societe) { + $sql .= natural_search('s.nom', $search_societe); + } + if ($search_frequency == '1') { + $sql .= ' AND f.frequency > 0'; + } + if ($search_frequency == '0') { + $sql .= ' AND (f.frequency IS NULL or f.frequency = 0)'; + } //$sql .= " ORDER BY $sortfield $sortorder, rowid DESC "; @@ -855,8 +892,12 @@ if ($action == 'create') { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=createfrommodel'; print '&socid='.$objp->socid.'&id='.$objp->fich_rec.'">'; print $langs->trans("CreateFichInter").'</a>'; - } else print $langs->trans("DateIsNotEnough"); - } else print "&nbsp;"; + } else { + print $langs->trans("DateIsNotEnough"); + } + } else { + print "&nbsp;"; + } print "</td>"; diff --git a/htdocs/fichinter/card.php b/htdocs/fichinter/card.php index 6c1dd4ddeb2..d1507d52418 100644 --- a/htdocs/fichinter/card.php +++ b/htdocs/fichinter/card.php @@ -36,18 +36,15 @@ require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/modules/fichinter/modules_fichinter.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/fichinter.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; } -if ($conf->contrat->enabled) -{ +if ($conf->contrat->enabled) { require_once DOL_DOCUMENT_ROOT."/core/class/html.formcontract.class.php"; require_once DOL_DOCUMENT_ROOT."/contrat/class/contrat.class.php"; } -if (!empty($conf->global->FICHEINTER_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/fichinter/mod_".$conf->global->FICHEINTER_ADDON.".php")) -{ +if (!empty($conf->global->FICHEINTER_ADDON) && is_readable(DOL_DOCUMENT_ROOT."/core/modules/fichinter/mod_".$conf->global->FICHEINTER_ADDON.".php")) { require_once DOL_DOCUMENT_ROOT."/core/modules/fichinter/mod_".$conf->global->FICHEINTER_ADDON.'.php'; } require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -75,7 +72,9 @@ $hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($ $hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -87,11 +86,14 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Load object -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); - if ($ret > 0) $ret = $object->fetch_thirdparty(); - if ($ret < 0) dol_print_error('', $object->error); + if ($ret > 0) { + $ret = $object->fetch_thirdparty(); + } + if ($ret < 0) { + dol_print_error('', $object->error); + } } $permissionnote = $user->rights->ficheinter->creer; // Used by the include of actions_setnotes.inc.php @@ -106,14 +108,13 @@ $error = 0; $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -125,20 +126,16 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; // Must be include, not include_once // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->ficheinter->creer) - { - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { + if ($action == 'confirm_clone' && $confirm == 'yes' && $user->rights->ficheinter->creer) { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { - if ($object->id > 0) - { + if ($object->id > 0) { // Because createFromClone modifies the object, we must clone it so that we can restore it later $orig = clone $object; $result = $object->createFromClone($user, $socid); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -150,21 +147,21 @@ if (empty($reshook)) } } - if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->ficheinter->creer) - { + if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->ficheinter->creer) { $result = $object->setValid($user); - if ($result >= 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if ($result >= 0) { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $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)) - { + 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); } @@ -178,15 +175,17 @@ if (empty($reshook)) } } elseif ($action == 'confirm_modify' && $confirm == 'yes' && $user->rights->ficheinter->creer) { $result = $object->setDraft($user); - if ($result >= 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if ($result >= 0) { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { // Define output language $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 ($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); @@ -212,16 +211,13 @@ if (empty($reshook)) $object->note_private = GETPOST('note_private', 'restricthtml'); $object->note_public = GETPOST('note_public', 'restricthtml'); - if ($object->socid > 0) - { + if ($object->socid > 0) { // If creation from another object of another module (Example: origin=propal, originid=1) - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $regs = array(); $element = $subelement = GETPOST('origin', 'alphanohtml'); - if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin', 'alphanohtml'), $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin', 'alphanohtml'), $regs)) { $element = $regs[1]; $subelement = $regs[2]; } @@ -242,8 +238,7 @@ if (empty($reshook)) // Possibility to add external linked objects with hooks $object->linked_objects[$object->origin] = $object->origin_id; - if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) - { + if (is_array($_POST['other_linked_objects']) && !empty($_POST['other_linked_objects'])) { $object->linked_objects = array_merge($object->linked_objects, $_POST['other_linked_objects']); } @@ -261,8 +256,7 @@ if (empty($reshook)) $id = $object->create($user); - if ($id > 0) - { + if ($id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $classname = ucfirst($subelement); @@ -270,12 +264,10 @@ if (empty($reshook)) dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $srcobject->fetch($object->origin_id); - if ($result > 0) - { + if ($result > 0) { $srcobject->fetch_thirdparty(); $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } @@ -283,9 +275,10 @@ if (empty($reshook)) if (is_array($lines)) { $num = count($lines); - for ($i = 0; $i < $num; $i++) - { - if (!in_array($lines[$i]->id, $selectedLines)) continue; // Skip unselected lines + for ($i = 0; $i < $num; $i++) { + if (!in_array($lines[$i]->id, $selectedLines)) { + continue; // Skip unselected lines + } $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : Product::TYPE_PRODUCT); @@ -293,8 +286,7 @@ if (empty($reshook)) $duration = 3600; // Default to one hour // Predefined products & services - if ($lines[$i]->fk_product > 0) - { + if ($lines[$i]->fk_product > 0) { $prod = new Product($db); $prod->id = $lines[$i]->fk_product; @@ -305,8 +297,12 @@ if (empty($reshook)) $prod->fetch($lines[$i]->fk_product); $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) $newlang = $srcobject->thirdparty->default_lang; + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { + $newlang = GETPOST('lang_id', 'aZ09'); + } + if (empty($newlang)) { + $newlang = $srcobject->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -367,12 +363,11 @@ if (empty($reshook)) $id, $desc, $date_intervention, - $duration, - $array_options + $duration, + $array_options ); - if ($result < 0) - { + if ($result < 0) { $error++; break; } @@ -395,16 +390,14 @@ if (empty($reshook)) $action = 'create'; } - if (!$error) - { + if (!$error) { // Extrafields $array_options = $extrafields->getOptionalsFromPost($object->table_element); $object->array_options = $array_options; $result = $object->create($user); - if ($result > 0) - { + if ($result > 0) { $id = $result; // Force raffraichissement sur fiche venant d'etre cree } else { $langs->load("errors"); @@ -429,22 +422,19 @@ if (empty($reshook)) if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Set into a project - elseif ($action == 'classin' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'classin' && $user->rights->ficheinter->creer) { + // Set into a project $result = $object->setProject(GETPOST('projectid', 'int')); - if ($result < 0) dol_print_error($db, $object->error); - } - - // Set into a contract - elseif ($action == 'setcontract' && $user->rights->contrat->creer) - { + if ($result < 0) { + dol_print_error($db, $object->error); + } + } elseif ($action == 'setcontract' && $user->rights->contrat->creer) { + // Set into a contract $result = $object->set_contrat($user, GETPOST('contratid', 'int')); - if ($result < 0) dol_print_error($db, $object->error); - } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->ficheinter->supprimer) - { + if ($result < 0) { + dol_print_error($db, $object->error); + } + } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->ficheinter->supprimer) { $result = $object->delete($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -452,32 +442,26 @@ if (empty($reshook)) header('Location: '.DOL_URL_ROOT.'/fichinter/list.php?leftmenu=ficheinter&restore_lastsearch_values=1'); exit; - } elseif ($action == 'setdescription' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'setdescription' && $user->rights->ficheinter->creer) { $result = $object->set_description($user, GETPOST('description')); - if ($result < 0) dol_print_error($db, $object->error); - } - - // Add line - elseif ($action == "addline" && $user->rights->ficheinter->creer) - { - if (!GETPOST('np_desc', 'restricthtml') && empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) - { + if ($result < 0) { + dol_print_error($db, $object->error); + } + } elseif ($action == "addline" && $user->rights->ficheinter->creer) { + // Add line + if (!GETPOST('np_desc', 'restricthtml') && empty($conf->global->FICHINTER_EMPTY_LINE_DESC)) { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Description")); $error++; } - if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && !GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) - { + if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && !GETPOST('durationhour', 'int') && !GETPOST('durationmin', 'int')) { $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Duration")); $error++; } - if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && GETPOST('durationhour', 'int') >= 24 && GETPOST('durationmin', 'int') > 0) - { + if (empty($conf->global->FICHINTER_WITHOUT_DURATION) && GETPOST('durationhour', 'int') >= 24 && GETPOST('durationmin', 'int') > 0) { $mesg = $langs->trans("ErrorValueTooHigh"); $error++; } - if (!$error) - { + if (!$error) { $db->begin(); $desc = GETPOST('np_desc', 'restricthtml'); @@ -500,19 +484,23 @@ if (empty($reshook)) // Define output language $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)) - { + 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); } - if ($result >= 0) - { + if ($result >= 0) { $db->commit(); - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { @@ -520,11 +508,8 @@ if (empty($reshook)) $db->rollback(); } } - } - - // Classify Billed - elseif ($action == 'classifybilled' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'classifybilled' && $user->rights->ficheinter->creer) { + // Classify Billed $result = $object->setStatut(2); if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); @@ -532,61 +517,42 @@ if (empty($reshook)) } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Classify unbilled - elseif ($action == 'classifyunbilled' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'classifyunbilled' && $user->rights->ficheinter->creer) { + // Classify unbilled $result = $object->setStatut(1); - if ($result > 0) - { + if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { $mesg = $object->error; } - } - - // Classify Done - elseif ($action == 'classifydone' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'classifydone' && $user->rights->ficheinter->creer) { + // Classify Done $result = $object->setStatut(3); - if ($result > 0) - { + if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } - } - - // Reopen - elseif ($action == 'confirm_reopen' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'confirm_reopen' && $user->rights->ficheinter->creer) { + // Reopen $result = $object->setStatut(Fichinter::STATUS_VALIDATED); - if ($result > 0) - { + if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; - } - else { + } else { $mesg = $object->error; } - } - - /* - * Mise a jour d'une ligne d'intervention - */ - elseif ($action == 'updateline' && $user->rights->ficheinter->creer && GETPOST('save', 'alpha') == $langs->trans("Save")) { + } elseif ($action == 'updateline' && $user->rights->ficheinter->creer && GETPOST('save', 'alpha') == $langs->trans("Save")) { + // Mise a jour d'une ligne d'intervention $objectline = new FichinterLigne($db); - if ($objectline->fetch($lineid) <= 0) - { + if ($objectline->fetch($lineid) <= 0) { dol_print_error($db); exit; } - if ($object->fetch($objectline->fk_fichinter) <= 0) - { + if ($object->fetch($objectline->fk_fichinter) <= 0) { dol_print_error($db); exit; } @@ -606,8 +572,7 @@ if (empty($reshook)) $objectline->array_options = $array_options; $result = $objectline->update($user); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db); exit; } @@ -615,34 +580,32 @@ if (empty($reshook)) // Define output language $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)) - { + 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); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id); exit; - } - - /* - * Supprime une ligne d'intervention AVEC confirmation - */ - elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->ficheinter->creer) { + // Supprime une ligne d'intervention AVEC confirmation $objectline = new FichinterLigne($db); - if ($objectline->fetch($lineid) <= 0) - { + if ($objectline->fetch($lineid) <= 0) { dol_print_error($db); exit; } $result = $objectline->deleteline($user); - if ($object->fetch($objectline->fk_fichinter) <= 0) - { + if ($object->fetch($objectline->fk_fichinter) <= 0) { dol_print_error($db); exit; } @@ -650,52 +613,61 @@ if (empty($reshook)) // Define output language $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)) - { + 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); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); - } - - /* - * Set position of lines - */ - elseif ($action == 'up' && $user->rights->ficheinter->creer) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } + } elseif ($action == 'up' && $user->rights->ficheinter->creer) { + // Set position of lines $object->line_up($lineid); // Define output language $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)) - { + 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); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.$lineid); exit; - } elseif ($action == 'down' && $user->rights->ficheinter->creer) - { + } elseif ($action == 'down' && $user->rights->ficheinter->creer) { $object->line_down($lineid); // Define output language $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)) - { + 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); } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) fichinter_create($db, $object, $object->model_pdf, $outputlangs); + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { + fichinter_create($db, $object, $object->model_pdf, $outputlangs); + } header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.$lineid); exit; @@ -715,66 +687,55 @@ if (empty($reshook)) $permissiontoadd = $user->rights->ficheinter->creer; include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $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 ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields $result = $object->insertExtraFields('INTERVENTION_MODIFY'); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if ($error) $action = 'edit_extras'; + if ($error) { + $action = 'edit_extras'; + } } - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->ficheinter->creer) - { - if ($action == 'addcontact') - { - if ($result > 0 && $id > 0) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->ficheinter->creer) { + if ($action == 'addcontact') { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); $mesg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); } else { $mesg = $object->error; } } - } - - // bascule du statut d'un contact - elseif ($action == 'swapstatut') - { + } elseif ($action == 'swapstatut') { + // bascule du statut d'un contact $result = $object->swapContactStatus(GETPOST('ligne', 'int')); - } - - // Efface un contact - elseif ($action == 'deletecontact') - { + } elseif ($action == 'deletecontact') { + // Efface un contact $result = $object->delete_contact(GETPOST('lineid', 'int')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -791,13 +752,16 @@ if (empty($reshook)) $form = new Form($db); $formfile = new FormFile($db); -if ($conf->contrat->enabled) $formcontract = new FormContract($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if ($conf->contrat->enabled) { + $formcontract = new FormContract($db); +} +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} llxHeader('', $langs->trans("Intervention")); -if ($action == 'create') -{ +if ($action == 'create') { // Create new intervention $soc = new Societe($db); @@ -810,21 +774,20 @@ if ($action == 'create') dol_htmloutput_mesg($mesg); } - if ($socid) $res = $soc->fetch($socid); + if ($socid) { + $res = $soc->fetch($socid); + } - if (GETPOST('origin', 'alphanohtml') && GETPOST('originid', 'int')) - { + if (GETPOST('origin', 'alphanohtml') && GETPOST('originid', 'int')) { // Parse element/subelement (ex: project_task) $regs = array(); $element = $subelement = GETPOST('origin', 'alphanohtml'); - if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin', 'alphanohtml'), $regs)) - { + if (preg_match('/^([^_]+)_([^_]+)/i', GETPOST('origin', 'alphanohtml'), $regs)) { $element = $regs[1]; $subelement = $regs[2]; } - if ($element == 'project') - { + if ($element == 'project') { $projectid = GETPOST('originid', 'int'); } else { // For compatibility @@ -843,8 +806,7 @@ if ($action == 'create') $classname = ucfirst($subelement); $objectsrc = new $classname($db); $objectsrc->fetch(GETPOST('originid')); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) - { + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { $objectsrc->fetch_lines(); $lines = $objectsrc->lines; } @@ -864,8 +826,7 @@ if ($action == 'create') $projectid = GETPOST('projectid', 'int'); } - if (!$conf->global->FICHEINTER_ADDON) - { + if (!$conf->global->FICHEINTER_ADDON) { dol_print_error($db, $langs->trans("Error")." ".$langs->trans("Error_FICHEINTER_ADDON_NotDefined")); exit; } @@ -878,8 +839,7 @@ if ($action == 'create') //$modFicheinter = new $obj; //$numpr = $modFicheinter->getNextValue($soc, $object); - if ($socid > 0) - { + if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); @@ -904,35 +864,31 @@ if ($action == 'create') print '</td></tr>'; // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load("project"); print '<tr><td>'.$langs->trans("Project").'</td><td>'; /* 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'); - */ + 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) - { + if ($numprojet == 0) { print ' &nbsp; <a href="'.DOL_URL_ROOT.'/projet/card.php?socid='.$soc->id.'&action=create"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddProject").'"></span></a>'; } print '</td></tr>'; } // Contract - if ($conf->contrat->enabled) - { + if ($conf->contrat->enabled) { $langs->load("contracts"); print '<tr><td>'.$langs->trans("Contract").'</td><td>'; $numcontrat = $formcontract->select_contract($soc->id, GETPOST('contratid', 'int'), 'contratid', 0, 1, 1); - if ($numcontrat == 0) - { + if ($numcontrat == 0) { print ' &nbsp; <a href="'.DOL_URL_ROOT.'/contrat/card.php?socid='.$soc->id.'&action=create"><span class="fa fa-plus-circle valignmiddle paddingleft" title="'.$langs->trans("AddContract").'"></span></a>'; } print '</td></tr>'; @@ -956,8 +912,7 @@ if ($action == 'create') print '</td></tr>'; // Private note - if (empty($user->socid)) - { + if (empty($user->socid)) { print '<tr>'; print '<td class="tdtop">'.$langs->trans('NotePrivate').'</td>'; print '<td>'; @@ -971,47 +926,46 @@ if ($action == 'create') $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)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } // Show link to origin object - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { $newclassname = $classname; - if ($newclassname == 'Propal') $newclassname = 'CommercialProposal'; + if ($newclassname == 'Propal') { + $newclassname = 'CommercialProposal'; + } print '<tr><td>'.$langs->trans($newclassname).'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>'; // Amount /* Hide amount because we only copy services so amount may differ than source - print '<tr><td>' . $langs->trans('AmountHT') . '</td><td>' . price($objectsrc->total_ht) . '</td></tr>'; - print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td>' . price($objectsrc->total_tva) . "</td></tr>"; - if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE - { - print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax1) . "</td></tr>"; - } + print '<tr><td>' . $langs->trans('AmountHT') . '</td><td>' . price($objectsrc->total_ht) . '</td></tr>'; + print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td>' . price($objectsrc->total_tva) . "</td></tr>"; + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE + { + print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax1) . "</td></tr>"; + } - if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF - { - print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax2) . "</td></tr>"; - } + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF + { + print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->country_code) . '</td><td>' . price($objectsrc->total_localtax2) . "</td></tr>"; + } - print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td>' . price($objectsrc->total_ttc) . "</td></tr>"; + print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td>' . price($objectsrc->total_ttc) . "</td></tr>"; - if (!empty($conf->multicurrency->enabled)) - { - print '<tr><td>' . $langs->trans('MulticurrencyAmountHT') . '</td><td>' . price($objectsrc->multicurrency_total_ht) . '</td></tr>'; - print '<tr><td>' . $langs->trans('MulticurrencyAmountVAT') . '</td><td>' . price($objectsrc->multicurrency_total_tva) . "</td></tr>"; - print '<tr><td>' . $langs->trans('MulticurrencyAmountTTC') . '</td><td>' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>"; - } - */ + if (!empty($conf->multicurrency->enabled)) + { + print '<tr><td>' . $langs->trans('MulticurrencyAmountHT') . '</td><td>' . price($objectsrc->multicurrency_total_ht) . '</td></tr>'; + print '<tr><td>' . $langs->trans('MulticurrencyAmountVAT') . '</td><td>' . price($objectsrc->multicurrency_total_tva) . "</td></tr>"; + print '<tr><td>' . $langs->trans('MulticurrencyAmountTTC') . '</td><td>' . price($objectsrc->multicurrency_total_ttc) . "</td></tr>"; + } + */ } print '</table>'; - if (is_object($objectsrc)) - { + if (is_object($objectsrc)) { print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">'; print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">'; } elseif ($origin == 'project' && !empty($projectid)) { @@ -1045,8 +999,7 @@ if ($action == 'create') print dol_get_fiche_head(''); - if (is_object($objectsrc)) - { + if (is_object($objectsrc)) { print '<input type="hidden" name="origin" value="'.$objectsrc->element.'">'; print '<input type="hidden" name="originid" value="'.$objectsrc->id.'">'; } elseif ($origin == 'project' && !empty($projectid)) { @@ -1070,11 +1023,10 @@ if ($action == 'create') print '</form>'; } -} elseif ($id > 0 || !empty($ref)) -{ +} elseif ($id > 0 || !empty($ref)) { /* * Affichage en mode visu - */ + */ $object->fetch($id, $ref); $object->fetch_thirdparty(); @@ -1095,21 +1047,17 @@ if ($action == 'create') $formconfirm = ''; // Confirm deletion of intervention - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteIntervention'), $langs->trans('ConfirmDeleteIntervention'), 'confirm_delete', '', 0, 1); } // Confirm validation - if ($action == 'validate') - { + if ($action == 'validate') { // on verifie si l'objet est en numerotation provisoire $ref = substr($object->ref, 1, 4); - if ($ref == 'PROV') - { + if ($ref == 'PROV') { $numref = $object->getNextNumRef($soc); - if (empty($numref)) - { + if (empty($numref)) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -1122,20 +1070,17 @@ if ($action == 'create') } // Confirm back to draft - if ($action == 'modify') - { + if ($action == 'modify') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ModifyIntervention'), $langs->trans('ConfirmModifyIntervention'), 'confirm_modify', '', 0, 1); } // Confirm back to open - if ($action == 'reopen') - { + if ($action == 'reopen') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Reopen'), $langs->trans('ConfirmReopenIntervention', $object->ref), 'confirm_reopen', '', 0, 1); } // Confirm deletion of line - if ($action == 'ask_deleteline') - { + if ($action == 'ask_deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&line_id='.$lineid, $langs->trans('DeleteInterventionLine'), $langs->trans('ConfirmDeleteInterventionLine'), 'confirm_deleteline', '', 0, 1); } @@ -1153,12 +1098,14 @@ if ($action == 'create') $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneIntervention', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); } - if (!$formconfirm) - { + if (!$formconfirm) { $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } } // Print form confirm @@ -1176,12 +1123,10 @@ if ($action == 'create') // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; } @@ -1219,8 +1164,7 @@ if ($action == 'create') print '<table class="border tableforfield" width="100%">'; - if (!empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES)) - { + if (!empty($conf->global->FICHINTER_USE_PLANNED_AND_DONE_DATES)) { // Date Start print '<tr><td class="titlefield">'.$langs->trans("Dateo").'</td>'; print '<td>'; @@ -1252,8 +1196,7 @@ if ($action == 'create') print '</tr>'; // Contract - if ($conf->contrat->enabled) - { + if ($conf->contrat->enabled) { $langs->load('contracts'); print '<tr>'; print '<td>'; @@ -1261,21 +1204,18 @@ if ($action == 'create') print '<table class="nobordernopadding centpercent"><tr><td>'; print $langs->trans('Contract'); print '</td>'; - if ($action != 'contrat') - { + if ($action != 'contrat') { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=contrat&amp;id='.$object->id.'">'; print img_edit($langs->trans('SetContract'), 1); print '</a></td>'; } print '</tr></table>'; print '</td><td>'; - if ($action == 'contrat') - { + if ($action == 'contrat') { $formcontract = new Formcontract($db); $formcontract->formSelectContract($_SERVER["PHP_SELF"].'?id='.$object->id, $object->socid, $object->fk_contrat, 'contratid', 0, 1, 1); } else { - if ($object->fk_contrat) - { + if ($object->fk_contrat) { $contratstatic = new Contrat($db); $contratstatic->fetch($object->fk_contrat); //print '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$selected.'">'.$projet->title.'</a>'; @@ -1301,8 +1241,7 @@ if ($action == 'create') print '<table class="border tableforfield centpercent">'; - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) - { + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) { // Duration print '<tr><td class="titlefield">'.$langs->trans("TotalDuration").'</td>'; print '<td>'.convertSecondToTime($object->duration, 'all', $conf->global->MAIN_DURATION_OF_WORKDAY).'</td>'; @@ -1318,23 +1257,20 @@ if ($action == 'create') print '<div class="clearboth"></div><br>'; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; $title = $langs->trans('ContactsAddresses'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $blocname = 'notes'; $title = $langs->trans('Notes'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } // Line of interventions - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) - { + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) { print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" name="addinter" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="id" value="'.$object->id.'">'; @@ -1356,13 +1292,11 @@ if ($action == 'create') $sql .= ' ORDER BY ft.rang ASC, ft.date ASC, ft.rowid'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num) - { + if ($num) { print '<br>'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; @@ -1404,8 +1338,7 @@ if ($action == 'create') print "</td>\n"; // Icon to edit and delete - if ($object->statut == 0 && $user->rights->ficheinter->creer) - { + if ($object->statut == 0 && $user->rights->ficheinter->creer) { print '<td class="center">'; print '<a class="editfielda marginrightonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=editline&amp;line_id='.$objp->rowid.'#'.$objp->rowid.'">'; print img_edit(); @@ -1414,16 +1347,13 @@ if ($action == 'create') print img_delete(); print '</a></td>'; print '<td class="center">'; - if ($num > 1) - { - if ($i > 0) - { + if ($num > 1) { + if ($i > 0) { print '<a class="marginleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=up&amp;line_id='.$objp->rowid.'">'; print img_up(); print '</a>'; } - if ($i < $num - 1) - { + if ($i < $num - 1) { print '<a class="marginleftonly" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=down&amp;line_id='.$objp->rowid.'">'; print img_down(); print '</a>'; @@ -1447,8 +1377,7 @@ if ($action == 'create') } // Line in update mode - if ($object->statut == 0 && $action == 'editline' && $user->rights->ficheinter->creer && GETPOST('line_id', 'int') == $objp->rowid) - { + if ($object->statut == 0 && $action == 'editline' && $user->rights->ficheinter->creer && GETPOST('line_id', 'int') == $objp->rowid) { print '<tr class="oddeven nohover">'; // No. @@ -1478,8 +1407,9 @@ if ($action == 'create') print '<td class="right">'; if (empty($conf->global->FICHINTER_WITHOUT_DURATION)) { $selectmode = 'select'; - if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) + if (!empty($conf->global->INTERVENTION_ADDLINE_FREEDUREATION)) { $selectmode = 'text'; + } $form->select_duration('duration', $objp->duree, 0, $selectmode); } print '</td>'; @@ -1504,10 +1434,8 @@ if ($action == 'create') $db->free($resql); // Add new line - if ($object->statut == 0 && $user->rights->ficheinter->creer && $action <> 'editline' && empty($conf->global->FICHINTER_DISABLE_DETAILS)) - { - if (!$num) - { + if ($object->statut == 0 && $user->rights->ficheinter->creer && $action <> 'editline' && empty($conf->global->FICHINTER_DISABLE_DETAILS)) { + if (!$num) { print '<br>'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; @@ -1522,7 +1450,7 @@ if ($action == 'create') print $langs->trans('Description').'</td>'; print '<td class="center">'.$langs->trans('Date').'</td>'; print '<td class="right">'.(empty($conf->global->FICHINTER_WITHOUT_DURATION) ? $langs->trans('Duration') : '').'</td>'; - print '<td colspan="3">&nbsp;</td>'; + print '<td colspan="3">&nbsp;</td>'; print "</tr>\n"; } @@ -1580,16 +1508,20 @@ if ($action == 'create') print $lineadd->showOptionals($extrafields, 'edit', array('colspan'=>5)); - if (!$num) print '</table>'; + if (!$num) { + print '</table>'; + } } - if ($num) print '</table>'; + if ($num) { + print '</table>'; + } } else { dol_print_error($db); } print '</form>'."\n"; - } + } print dol_get_fiche_end(); @@ -1605,10 +1537,8 @@ if ($action == 'create') $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { - if ($user->socid == 0) - { + 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))) { @@ -1619,31 +1549,33 @@ if ($action == 'create') } // 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))) - { + 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 '<div class="inline-block divButAction"><a class="butAction" href="card.php?id='.$object->id.'&action=modify">'; - if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) print $langs->trans("Modify"); - else print $langs->trans("SetToDraft"); + if (empty($conf->global->FICHINTER_DISABLE_DETAILS)) { + print $langs->trans("Modify"); + } else { + print $langs->trans("SetToDraft"); + } print '</a></div>'; } // Reopen - if ($object->statut >= Fichinter::STATUS_CLOSED) - { - if ($user->rights->ficheinter->creer) - { + if ($object->statut >= Fichinter::STATUS_CLOSED) { + if ($user->rights->ficheinter->creer) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=reopen">'.$langs->trans('Reopen').'</a></div>'; - } else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('Reopen').'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('Reopen').'</a></div>'; + } } // Send if (empty($user->socid)) { - if ($object->statut > Fichinter::STATUS_DRAFT) - { - if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->ficheinter->ficheinter_advance->send) - { + if ($object->statut > Fichinter::STATUS_DRAFT) { + if (empty($conf->global->MAIN_USE_ADVANCED_PERMS) || $user->rights->ficheinter->ficheinter_advance->send) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'; - } else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans('SendMail').'</a></div>'; + } } } @@ -1655,30 +1587,30 @@ if ($action == 'create') } // Proposal - if ($conf->service->enabled && !empty($conf->propal->enabled) && $object->statut > Fichinter::STATUS_DRAFT) - { + if ($conf->service->enabled && !empty($conf->propal->enabled) && $object->statut > Fichinter::STATUS_DRAFT) { $langs->load("propal"); - if ($object->statut < Fichinter::STATUS_BILLED) - { - if ($user->rights->propal->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/comm/propal/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("AddProp").'</a></div>'; - else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("AddProp").'</a></div>'; + if ($object->statut < Fichinter::STATUS_BILLED) { + if ($user->rights->propal->creer) { + print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/comm/propal/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("AddProp").'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("AddProp").'</a></div>'; + } } } // Invoicing - if (!empty($conf->facture->enabled) && $object->statut > Fichinter::STATUS_DRAFT) - { + if (!empty($conf->facture->enabled) && $object->statut > Fichinter::STATUS_DRAFT) { $langs->load("bills"); - if ($object->statut < Fichinter::STATUS_BILLED) - { - if ($user->rights->facture->creer) print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("AddBill").'</a></div>'; - else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("AddBill").'</a></div>'; + if ($object->statut < Fichinter::STATUS_BILLED) { + if ($user->rights->facture->creer) { + print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/compta/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("AddBill").'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotEnoughPermissions").'">'.$langs->trans("AddBill").'</a></div>'; + } } - if (!empty($conf->global->FICHINTER_CLASSIFY_BILLED)) // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 - { - if ($object->statut != Fichinter::STATUS_BILLED) - { + if (!empty($conf->global->FICHINTER_CLASSIFY_BILLED)) { // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 + if ($object->statut != Fichinter::STATUS_BILLED) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifybilled">'.$langs->trans("InterventionClassifyBilled").'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifyunbilled">'.$langs->trans("InterventionClassifyUnBilled").'</a></div>'; @@ -1687,8 +1619,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 '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifydone">'.$langs->trans("InterventionClassifyDone").'</a></div>'; } @@ -1698,8 +1629,7 @@ if ($action == 'create') } // Delete - if (($object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer) || $user->rights->ficheinter->supprimer) - { + if (($object->statut == Fichinter::STATUS_DRAFT && $user->rights->ficheinter->creer) || $user->rights->ficheinter->supprimer) { print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'"'; print '>'.$langs->trans('Delete').'</a></div>'; } @@ -1709,8 +1639,7 @@ if ($action == 'create') print '</div>'; - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; /* diff --git a/htdocs/fichinter/class/api_interventions.class.php b/htdocs/fichinter/class/api_interventions.class.php index 7046a61e2d5..a5ba127a54d 100644 --- a/htdocs/fichinter/class/api_interventions.class.php +++ b/htdocs/fichinter/class/api_interventions.class.php @@ -32,7 +32,7 @@ class Interventions extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'socid', 'fk_project', 'description', @@ -41,7 +41,7 @@ class Interventions extends DolibarrApi /** * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDSLINE = array( + public static $FIELDSLINE = array( 'description', 'date', 'duree', @@ -117,27 +117,37 @@ class Interventions extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } $sql .= ' WHERE t.entity IN ('.getEntity('intervention').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Insert sale filter if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -146,8 +156,7 @@ class Interventions extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -158,13 +167,11 @@ class Interventions extends DolibarrApi dol_syslog("API Rest request"); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); $i = 0; - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $fichinter_static = new Fichinter($this->db); if ($fichinter_static->fetch($obj->rowid)) { @@ -216,28 +223,28 @@ class Interventions extends DolibarrApi * @return int */ /* TODO - public function getLines($id) - { - if(! DolibarrApiAccess::$user->rights->ficheinter->lire) { - throw new RestException(401); - } + public function getLines($id) + { + if(! DolibarrApiAccess::$user->rights->ficheinter->lire) { + throw new RestException(401); + } - $result = $this->fichinter->fetch($id); - if( ! $result ) { - throw new RestException(404, 'Intervention not found'); - } + $result = $this->fichinter->fetch($id); + if( ! $result ) { + throw new RestException(404, 'Intervention not found'); + } - if( ! DolibarrApi::_checkAccessToResource('fichinter',$this->fichinter->id)) { - throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); - } - $this->fichinter->getLinesArray(); - $result = array(); - foreach ($this->fichinter->lines as $line) { - array_push($result,$this->_cleanObjectDatas($line)); - } - return $result; - } - */ + if( ! DolibarrApi::_checkAccessToResource('fichinter',$this->fichinter->id)) { + throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); + } + $this->fichinter->getLinesArray(); + $result = array(); + foreach ($this->fichinter->lines as $line) { + array_push($result,$this->_cleanObjectDatas($line)); + } + return $result; + } + */ /** * Add a line to given intervention @@ -270,11 +277,11 @@ class Interventions extends DolibarrApi } $updateRes = $this->fichinter->addLine( - DolibarrApiAccess::$user, - $id, - $this->fichinter->description, - $this->fichinter->date, - $this->fichinter->duree + DolibarrApiAccess::$user, + $id, + $this->fichinter->description, + $this->fichinter->date, + $this->fichinter->duree ); if ($updateRes > 0) { @@ -369,8 +376,7 @@ class Interventions extends DolibarrApi */ public function closeFichinter($id) { - if (!DolibarrApiAccess::$user->rights->ficheinter->creer) - { + if (!DolibarrApiAccess::$user->rights->ficheinter->creer) { throw new RestException(401, "Insuffisant rights"); } $result = $this->fichinter->fetch($id); @@ -408,8 +414,9 @@ class Interventions extends DolibarrApi { $fichinter = array(); foreach (Interventions::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $fichinter[$field] = $data[$field]; } return $fichinter; @@ -447,8 +454,9 @@ class Interventions extends DolibarrApi { $fichinter = array(); foreach (Interventions::$FIELDSLINE as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $fichinter[$field] = $data[$field]; } return $fichinter; diff --git a/htdocs/fichinter/class/fichinter.class.php b/htdocs/fichinter/class/fichinter.class.php index 39ac094132a..cea1b1ca48c 100644 --- a/htdocs/fichinter/class/fichinter.class.php +++ b/htdocs/fichinter/class/fichinter.class.php @@ -204,8 +204,7 @@ class Fichinter extends CommonObject $sql = "SELECT count(fi.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as fi"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON fi.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -213,10 +212,8 @@ class Fichinter extends CommonObject $sql .= " ".$clause." fi.entity IN (".getEntity('intervention').")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["interventions"] = $obj->nb; } $this->db->free($resql); @@ -244,21 +241,20 @@ class Fichinter extends CommonObject dol_syslog(get_class($this)."::create ref=".$this->ref); // Check parameters - if (!empty($this->ref)) // We check that ref is not already used - { + if (!empty($this->ref)) { // We check that ref is not already used $result = self::isExistingObject($this->element, 0, $this->ref); // Check ref is not yet used - if ($result > 0) - { + if ($result > 0) { $this->error = 'ErrorRefAlreadyExists'; dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); $this->db->rollback(); return -1; } } - if (!is_numeric($this->duration)) $this->duration = 0; + if (!is_numeric($this->duration)) { + $this->duration = 0; + } - if ($this->socid <= 0) - { + if ($this->socid <= 0) { $this->error = 'ErrorBadParameterForFunc'; dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR); return -1; @@ -304,42 +300,42 @@ class Fichinter extends CommonObject dol_syslog(get_class($this)."::create", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."fichinter"); - if ($this->id) - { + if ($this->id) { $this->ref = '(PROV'.$this->id.')'; $sql = 'UPDATE '.MAIN_DB_PREFIX."fichinter SET ref='".$this->db->escape($this->ref)."' WHERE rowid=".$this->id; dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } // Add linked object - if (!$error && $this->origin && $this->origin_id) - { + if (!$error && $this->origin && $this->origin_id) { $ret = $this->add_object_linked(); - if (!$ret) dol_print_error($this->db); + if (!$ret) { + dol_print_error($this->db); + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('FICHINTER_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } @@ -370,14 +366,14 @@ class Fichinter extends CommonObject { global $conf; - if (!is_numeric($this->duration)) { - $this->duration = 0; - } - if (!dol_strlen($this->fk_project)) { - $this->fk_project = 0; - } + if (!is_numeric($this->duration)) { + $this->duration = 0; + } + if (!dol_strlen($this->fk_project)) { + $this->fk_project = 0; + } - $error = 0; + $error = 0; $this->db->begin(); @@ -391,22 +387,20 @@ class Fichinter extends CommonObject $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::update", LOG_DEBUG); - if ($this->db->query($sql)) - { - if (!$error) - { + if ($this->db->query($sql)) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('FICHINTER_MODIFY', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers } @@ -437,14 +431,14 @@ class Fichinter extends CommonObject if ($ref) { $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.ref='".$this->db->escape($ref)."'"; - } else $sql .= " WHERE f.rowid=".$rowid; + } else { + $sql .= " WHERE f.rowid=".$rowid; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -470,7 +464,9 @@ class Fichinter extends CommonObject $this->extraparams = (array) json_decode($obj->extraparams, true); - if ($this->statut == 0) $this->brouillon = 1; + if ($this->statut == 0) { + $this->brouillon = 1; + } // Retrieve extrafields $this->fetch_optionals(); @@ -479,8 +475,7 @@ class Fichinter extends CommonObject * Lines */ $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { return -3; } $this->db->free($resql); @@ -505,8 +500,7 @@ class Fichinter extends CommonObject $error = 0; // Protection - if ($this->statut <= self::STATUS_DRAFT) - { + if ($this->statut <= self::STATUS_DRAFT) { return 0; } @@ -519,8 +513,7 @@ class Fichinter extends CommonObject $sql .= " WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { if (!$error) { $this->oldcopy = clone $this; } @@ -528,7 +521,9 @@ class Fichinter extends CommonObject if (!$error) { // Call trigger $result = $this->call_trigger('FICHINTER_UNVALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } if (!$error) { @@ -560,15 +555,13 @@ class Fichinter extends CommonObject $error = 0; - if ($this->statut != 1) - { + if ($this->statut != 1) { $this->db->begin(); $now = dol_now(); // Define new ref - if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life - { + if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($this->thirdparty); } else { $num = $this->ref; @@ -586,51 +579,48 @@ class Fichinter extends CommonObject dol_syslog(get_class($this)."::setValid", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('FICHINTER_VALIDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'ficheinter/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'ficheinter/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->ficheinter->dir_output.'/'.$oldref; $dirdest = $conf->ficheinter->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::setValid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->ficheinter->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -643,8 +633,7 @@ class Fichinter extends CommonObject } // Set new ref and define current statut - if (!$error) - { + if (!$error) { $this->ref = $num; $this->statut = 1; $this->brouillon = 0; @@ -740,8 +729,7 @@ class Fichinter extends CommonObject { // phpcs:enable // Init/load array of translation of status - if (empty($this->statuts) || empty($this->statuts_short) || empty($this->statuts_logo)) - { + if (empty($this->statuts) || empty($this->statuts_short) || empty($this->statuts_logo)) { global $langs; $langs->load("fichinter"); @@ -785,19 +773,20 @@ class Fichinter extends CommonObject $url = DOL_URL_ROOT.'/fichinter/card.php?id='.$this->id; - if ($option !== 'nolink') - { + if ($option !== 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; - } + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } + } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowIntervention"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -817,16 +806,23 @@ class Fichinter extends CommonObject $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; global $action; $hookmanager->initHooks(array('interventiondao')); $parameters = array('id'=>$this->id, 'getnomurl'=>$result); $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook > 0) $result = $hookmanager->resPrint; - else $result .= $hookmanager->resPrint; + if ($reshook > 0) { + $result = $hookmanager->resPrint; + } else { + $result .= $hookmanager->resPrint; + } return $result; } @@ -844,8 +840,7 @@ class Fichinter extends CommonObject global $conf, $db, $langs; $langs->load("interventions"); - if (!empty($conf->global->FICHEINTER_ADDON)) - { + if (!empty($conf->global->FICHEINTER_ADDON)) { $mybool = false; $file = "mod_".$conf->global->FICHEINTER_ADDON.".php"; @@ -870,8 +865,7 @@ class Fichinter extends CommonObject $numref = ""; $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { dol_print_error($db, "Fichinter::getNextNumRef ".$obj->error); @@ -905,10 +899,8 @@ class Fichinter extends CommonObject $sql .= " WHERE f.rowid = ".$id; $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -921,14 +913,12 @@ class Fichinter extends CommonObject $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_modification) - { + if ($obj->fk_user_modification) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modification); $this->user_modification = $muser; @@ -956,27 +946,27 @@ class Fichinter extends CommonObject $this->db->begin(); - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('FICHINTER_DELETE', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers } // Delete linked object - if (!$error) - { + if (!$error) { $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } // Delete linked contacts - if (!$error) - { + if (!$error) { $res = $this->delete_linked_contact(); - if ($res < 0) - { + if ($res < 0) { $this->error = 'ErrorFailToDeleteLinkedContact'; $error++; } @@ -988,62 +978,61 @@ class Fichinter extends CommonObject $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_fichinter = ".$this->id.")"; $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet"; $sql .= " WHERE fk_fichinter = ".$this->id; $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } } - if (!$error) - { + if (!$error) { // Remove extrafields $res = $this->deleteExtraFields(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete object $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinter"; $sql .= " WHERE rowid = ".$this->id; dol_syslog("Fichinter::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive $this->deleteEcmFiles(); // Remove directory with files $fichinterref = dol_sanitizeFileName($this->ref); - if ($conf->ficheinter->dir_output) - { + if ($conf->ficheinter->dir_output) { $dir = $conf->ficheinter->dir_output."/".$fichinterref; $file = $conf->ficheinter->dir_output."/".$fichinterref."/".$fichinterref.".pdf"; - if (file_exists($file)) - { + if (file_exists($file)) { dol_delete_preview($this); - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { + if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers $langs->load("errors"); $this->error = $langs->trans("ErrorFailToDeleteFile", $file); return 0; } } - if (file_exists($dir)) - { - if (!dol_delete_dir_recursive($dir)) - { + if (file_exists($dir)) { + if (!dol_delete_dir_recursive($dir)) { $langs->load("errors"); $this->error = $langs->trans("ErrorFailToDeleteDir", $dir); return 0; @@ -1052,8 +1041,7 @@ class Fichinter extends CommonObject } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1075,15 +1063,13 @@ class Fichinter extends CommonObject // phpcs:enable global $conf; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; $sql .= " SET datei = '".$this->db->idate($date_delivery)."'"; $sql .= " WHERE rowid = ".$this->id; $sql .= " AND fk_statut = 0"; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->date_delivery = $date_delivery; return 1; } else { @@ -1107,15 +1093,13 @@ class Fichinter extends CommonObject // phpcs:enable global $conf; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; $sql .= " SET description = '".$this->db->escape($description)."',"; $sql .= " fk_user_modif = ".$user->id; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->description = $description; return 1; } else { @@ -1140,14 +1124,12 @@ class Fichinter extends CommonObject // phpcs:enable global $conf; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter "; $sql .= " SET fk_contrat = ".((int) $contractid); $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->fk_contrat = $contractid; return 1; } else { @@ -1176,19 +1158,18 @@ class Fichinter extends CommonObject $this->db->begin(); // get extrafields so they will be clone - foreach ($this->lines as $line) + foreach ($this->lines as $line) { $line->fetch_optionals(); + } // Load source object $objFrom = clone $this; // Change socid if needed - if (!empty($socid) && $socid != $this->socid) - { + if (!empty($socid) && $socid != $this->socid) { $objsoc = new Societe($this->db); - if ($objsoc->fetch($socid) > 0) - { + if ($objsoc->fetch($socid) > 0) { $this->socid = $objsoc->id; //$this->cond_reglement_id = (! empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); //$this->mode_reglement_id = (! empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); @@ -1213,31 +1194,31 @@ class Fichinter extends CommonObject // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Add lines because it is not included into create function - foreach ($this->lines as $line) - { + foreach ($this->lines as $line) { $this->addline($user, $this->id, $line->desc, $line->datei, $line->duration); } // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$objFrom); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($this->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1262,8 +1243,7 @@ class Fichinter extends CommonObject { dol_syslog(get_class($this)."::addline $fichinterid, $desc, $date_intervention, $duration"); - if ($this->statut == 0) - { + if ($this->statut == 0) { $this->db->begin(); // Insertion ligne @@ -1280,8 +1260,7 @@ class Fichinter extends CommonObject $result = $line->insert($user); - if ($result >= 0) - { + if ($result >= 0) { $this->db->commit(); return 1; } else { @@ -1317,8 +1296,7 @@ class Fichinter extends CommonObject $this->duration = 0; $nbp = 25; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new FichinterLigne($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->datei = ($now - 3600 * (1 + $xnbp)); @@ -1348,12 +1326,10 @@ class Fichinter extends CommonObject dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($resql); $line = new FichinterLigne($this->db); @@ -1466,8 +1442,7 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::fetch", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); $this->rowid = $objp->rowid; $this->id = $objp->rowid; @@ -1503,14 +1478,12 @@ class FichinterLigne extends CommonObjectLine $this->db->begin(); $rangToUse = $this->rang; - if ($rangToUse == -1) - { + if ($rangToUse == -1) { // Recupere rang max de la ligne d'intervention dans $rangmax $sql = 'SELECT max(rang) as max FROM '.MAIN_DB_PREFIX.'fichinterdet'; $sql .= ' WHERE fk_fichinter ='.$this->fk_fichinter; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $rangToUse = $obj->max + 1; } else { @@ -1532,16 +1505,13 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::insert", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'fichinterdet'); $this->rowid = $this->id; - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } @@ -1549,15 +1519,15 @@ class FichinterLigne extends CommonObjectLine $result = $this->update_total(); - if ($result > 0) - { + if ($result > 0) { $this->rang = $rangToUse; - if (!$notrigger) - { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINEFICHINTER_CREATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } @@ -1602,31 +1572,27 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::update", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$error) - { + if ($resql) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } $result = $this->update_total(); - if ($result > 0) - { - if (!$notrigger) - { + if ($result > 0) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINEFICHINTER_UPDATE', $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } } - if (!$error) - { + if (!$error) { $this->db->commit(); return $result; } else { @@ -1660,11 +1626,12 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $total_duration = 0; - if (!empty($obj->total_duration)) $total_duration = $obj->total_duration; + if (!empty($obj->total_duration)) { + $total_duration = $obj->total_duration; + } $sql = "UPDATE ".MAIN_DB_PREFIX."fichinter"; $sql .= " SET duree = ".$total_duration; @@ -1674,8 +1641,7 @@ class FichinterLigne extends CommonObjectLine dol_syslog("FichinterLigne::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -1703,8 +1669,7 @@ class FichinterLigne extends CommonObjectLine $error = 0; - if ($this->statut == 0) - { + if ($this->statut == 0) { dol_syslog(get_class($this)."::deleteline lineid=".$this->id); $this->db->begin(); @@ -1718,16 +1683,15 @@ class FichinterLigne extends CommonObjectLine $sql = "DELETE FROM ".MAIN_DB_PREFIX."fichinterdet WHERE rowid = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $result = $this->update_total(); - if ($result > 0) - { - if (!$notrigger) - { + if ($result > 0) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINEFICHINTER_DELETE', $user); - if ($result < 0) { $error++; $this->db->rollback(); return -1; } + if ($result < 0) { + $error++; $this->db->rollback(); return -1; + } // End call triggers } diff --git a/htdocs/fichinter/class/fichinterrec.class.php b/htdocs/fichinter/class/fichinterrec.class.php index 418e1232bb8..8ed842a70c9 100644 --- a/htdocs/fichinter/class/fichinterrec.class.php +++ b/htdocs/fichinter/class/fichinterrec.class.php @@ -214,8 +214,8 @@ class FichinterRec extends Fichinter $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); /* - * Lines - */ + * Lines + */ $num = count($fichintsrc->lines); for ($i = 0; $i < $num; $i++) { //var_dump($fichintsrc->lines[$i]); @@ -239,13 +239,14 @@ class FichinterRec extends Fichinter $fichintsrc->lines[$i]->fk_unit ); - if ($result_insert < 0) + if ($result_insert < 0) { $error++; + } } - if ($error) + if ($error) { $this->db->rollback(); - else { + } else { $this->db->commit(); return $this->id; } @@ -277,8 +278,11 @@ class FichinterRec extends Fichinter $sql .= ', f.frequency, f.unit_frequency, f.date_when, f.date_last_gen, f.nb_gen_done, f.nb_gen_max, f.auto_validate'; $sql .= ', f.note_private, f.note_public, f.fk_user_author'; $sql .= ' FROM '.MAIN_DB_PREFIX.'fichinter_rec as f'; - if ($rowid > 0) $sql .= ' WHERE f.rowid='.$rowid; - elseif ($ref) $sql .= " WHERE f.titre='".$this->db->escape($ref)."'"; + if ($rowid > 0) { + $sql .= ' WHERE f.rowid='.$rowid; + } elseif ($ref) { + $sql .= " WHERE f.titre='".$this->db->escape($ref)."'"; + } dol_syslog(get_class($this)."::fetch rowid=".$rowid, LOG_DEBUG); @@ -421,7 +425,9 @@ class FichinterRec extends Fichinter */ public function delete($rowid = 0, $notrigger = 0, $idwarehouse = -1) { - if (empty($rowid)) $rowid = $this->id; + if (empty($rowid)) { + $rowid = $this->id; + } dol_syslog(get_class($this)."::delete rowid=".$rowid, LOG_DEBUG); @@ -481,14 +487,20 @@ class FichinterRec extends Fichinter include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($this->brouillon) { // Clean parameters $remise_percent = price2num($remise_percent); $qty = price2num($qty); - if (!$qty) $qty = 1; - if (!$info_bits) $info_bits = 0; + if (!$qty) { + $qty = 1; + } + if (!$info_bits) { + $info_bits = 0; + } $pu_ht = price2num($pu_ht); $pu_ttc = price2num($pu_ttc); if (!preg_match('/\((.*)\)/', $txtva)) { @@ -623,7 +635,9 @@ class FichinterRec extends Fichinter $url = DOL_URL_ROOT.'/fichinter/card-rec.php?id='.$this->id; - if ($short) return $url; + if ($short) { + return $url; + } $picto = 'intervention'; @@ -709,7 +723,9 @@ class FichinterRec extends Fichinter dol_syslog(get_class($this)."::setFrequencyAndUnit", LOG_DEBUG); if ($this->db->query($sql)) { $this->frequency = $frequency; - if (!empty($unit)) $this->unit_frequency = $unit; + if (!empty($unit)) { + $this->unit_frequency = $unit; + } return 1; } else { dol_print_error($this->db); @@ -732,13 +748,17 @@ class FichinterRec extends Fichinter } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= " SET date_when = ".($date ? "'".$this->db->idate($date)."'" : "null"); - if ($increment_nb_gen_done > 0) $sql .= ', nb_gen_done = nb_gen_done + 1'; + if ($increment_nb_gen_done > 0) { + $sql .= ', nb_gen_done = nb_gen_done + 1'; + } $sql .= ' WHERE rowid = '.$this->id; dol_syslog(get_class($this)."::setNextDate", LOG_DEBUG); if ($this->db->query($sql)) { $this->date_when = $date; - if ($increment_nb_gen_done > 0) $this->nb_gen_done++; + if ($increment_nb_gen_done > 0) { + $this->nb_gen_done++; + } return 1; } else { dol_print_error($this->db); @@ -759,7 +779,9 @@ class FichinterRec extends Fichinter return -1; } - if (empty($nb)) $nb = 0; + if (empty($nb)) { + $nb = 0; + } $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element; $sql .= ' SET nb_gen_max = '.$nb; @@ -818,8 +840,9 @@ class FichinterRec extends Fichinter $sql .= ' SET nb_gen_done = nb_gen_done + 1'; $sql .= ' , date_last_gen = now()'; // si on et arrivé à la fin des génération - if ($this->nb_gen_max == $this->nb_gen_done + 1) + if ($this->nb_gen_max == $this->nb_gen_done + 1) { $sql .= ' , statut = 1'; + } $sql .= ' WHERE rowid = '.$this->id; diff --git a/htdocs/fichinter/class/fichinterstats.class.php b/htdocs/fichinter/class/fichinterstats.class.php index 5df841bf6f2..a0d22cf1e2a 100644 --- a/htdocs/fichinter/class/fichinterstats.class.php +++ b/htdocs/fichinter/class/fichinterstats.class.php @@ -64,8 +64,7 @@ class FichinterStats extends Stats $this->userid = $userid; $this->cachefilesuffix = $mode; - if ($mode == 'customer') - { + if ($mode == 'customer') { $object = new Fichinter($this->db); $this->from = MAIN_DB_PREFIX.$object->table_element." as c"; $this->from_line = MAIN_DB_PREFIX.$object->table_element_line." as tl"; @@ -73,14 +72,17 @@ class FichinterStats extends Stats $this->field_line = '0'; //$this->where.= " AND c.fk_statut > 0"; // Not draft and not cancelled } - if (!$user->rights->societe->client->voir && !$this->socid) $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$this->socid) { + $this->where .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } $this->where .= ($this->where ? ' AND ' : '')."c.entity IN (".getEntity('fichinter').')'; - if ($this->socid) - { + if ($this->socid) { $this->where .= " AND c.fk_soc = ".$this->socid; } - if ($this->userid > 0) $this->where .= ' AND c.fk_user_author = '.$this->userid; + if ($this->userid > 0) { + $this->where .= ' AND c.fk_user_author = '.$this->userid; + } } /** @@ -96,7 +98,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%m') as dm, COUNT(*) as nb"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; @@ -118,7 +122,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%Y') as dm, COUNT(*) as nb, 0"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE ".$this->where; $sql .= " GROUP BY dm"; $sql .= $this->db->order('dm', 'DESC'); @@ -139,7 +145,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%m') as dm, 0"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; @@ -161,7 +169,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%m') as dm, 0"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.date_valid BETWEEN '".$this->db->idate(dol_get_first_day($year))."' AND '".$this->db->idate(dol_get_last_day($year))."'"; $sql .= " AND ".$this->where; $sql .= " GROUP BY dm"; @@ -181,7 +191,9 @@ class FichinterStats extends Stats $sql = "SELECT date_format(c.date_valid,'%Y') as year, COUNT(*) as nb, 0 as total, 0 as avg"; $sql .= " FROM ".$this->from; - if (!$user->rights->societe->client->voir && !$this->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$this->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE ".$this->where; $sql .= " GROUP BY year"; $sql .= $this->db->order('year', 'DESC'); diff --git a/htdocs/fichinter/contact.php b/htdocs/fichinter/contact.php index bace3d10231..7957479e611 100644 --- a/htdocs/fichinter/contact.php +++ b/htdocs/fichinter/contact.php @@ -39,13 +39,14 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); $object = new Fichinter($db); $result = $object->fetch($id, $ref); -if (!$result) -{ +if (!$result) { print 'Record not found'; exit; } @@ -54,17 +55,14 @@ if (!$result) * Adding a new contact */ -if ($action == 'addcontact' && $user->rights->ficheinter->creer) -{ - if ($result > 0 && $id > 0) - { +if ($action == 'addcontact' && $user->rights->ficheinter->creer) { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -77,21 +75,14 @@ if ($action == 'addcontact' && $user->rights->ficheinter->creer) setEventMessages($mesg, null, 'errors'); } -} - -// Toggle the status of a contact -elseif ($action == 'swapstatut' && $user->rights->ficheinter->creer) -{ +} elseif ($action == 'swapstatut' && $user->rights->ficheinter->creer) { + // Toggle the status of a contact $result = $object->swapContactStatus(GETPOST('ligne', 'int')); -} - -// Deletes a contact -elseif ($action == 'deletecontact' && $user->rights->ficheinter->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->ficheinter->creer) { + // Deletes a contact $result = $object->delete_contact(GETPOST('lineid', 'int')); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -114,8 +105,7 @@ llxHeader('', $langs->trans("Intervention")); // Mode vue et edition -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = fichinter_prepare_head($object); @@ -133,12 +123,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->ficheinter->creer) - { + if ($user->rights->ficheinter->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; @@ -174,15 +162,20 @@ if ($id > 0 || !empty($ref)) print '<br>'; - if (!empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_USER)) $hideaddcontactforuser = 1; - if (!empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_THIPARTY)) $hideaddcontactforthirdparty = 1; + if (!empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_USER)) { + $hideaddcontactforuser = 1; + } + if (!empty($conf->global->FICHINTER_HIDE_ADD_CONTACT_THIPARTY)) { + $hideaddcontactforthirdparty = 1; + } // Contacts lines (modules that overwrite templates must declare this into descriptor) $dirtpls = array_merge($conf->modules_parts['tpl'], array('/core/tpl')); - foreach ($dirtpls as $reldir) - { + foreach ($dirtpls as $reldir) { $res = @include dol_buildpath($reldir.'/contacts.tpl.php'); - if ($res) break; + if ($res) { + break; + } } } diff --git a/htdocs/fichinter/document.php b/htdocs/fichinter/document.php index aaab2072013..ba1f22c122b 100644 --- a/htdocs/fichinter/document.php +++ b/htdocs/fichinter/document.php @@ -47,7 +47,9 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); @@ -56,12 +58,18 @@ $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} $object = new Fichinter($db); @@ -86,8 +94,7 @@ $form = new Form($db); llxHeader('', $langs->trans("Intervention")); -if ($object->id) -{ +if ($object->id) { $object->fetch_thirdparty(); $head = fichinter_prepare_head($object); @@ -98,8 +105,7 @@ if ($object->id) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -115,12 +121,10 @@ if ($object->id) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fichinter/index.php b/htdocs/fichinter/index.php index 3ea69f8d185..863463e8d0e 100644 --- a/htdocs/fichinter/index.php +++ b/htdocs/fichinter/index.php @@ -30,7 +30,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; -if (!$user->rights->ficheinter->lire) accessforbidden(); +if (!$user->rights->ficheinter->lire) { + accessforbidden(); +} $hookmanager = new HookManager($db); @@ -42,8 +44,7 @@ $langs->load("interventions"); // Security check $socid = GETPOST('socid', 'int'); -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -66,8 +67,7 @@ print load_fiche_titre($langs->trans("InterventionsArea"), '', 'intervention'); print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo // Search ficheinter $var = false; print '<form method="post" action="'.DOL_URL_ROOT.'/fichinter/list.php">'; @@ -88,15 +88,20 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles $sql = "SELECT count(f.rowid), f.fk_statut"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."fichinter as f"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; -if ($user->socid) $sql .= ' AND f.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND f.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY f.fk_statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -106,15 +111,15 @@ if ($resql) $vals = array(); $bool = false; // -1=Canceled, 0=Draft, 1=Validated, 2=Accepted/On process, 3=Closed (Sent/Received, billed or not) - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); - if ($row) - { + if ($row) { //if ($row[1]!=-1 && ($row[1]!=3 || $row[2]!=1)) { $bool = (!empty($row[2]) ?true:false); - if (!isset($vals[$row[1].$bool])) $vals[$row[1].$bool] = 0; + if (!isset($vals[$row[1].$bool])) { + $vals[$row[1].$bool] = 0; + } $vals[$row[1].$bool] += $row[0]; $totalinprocess += $row[0]; } @@ -131,19 +136,28 @@ if ($resql) print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("Interventions").'</th></tr>'."\n"; $listofstatus = array(0, 1, 3); $bool = false; - foreach ($listofstatus as $status) - { + foreach ($listofstatus as $status) { $dataseries[] = array($fichinterstatic->LibStatut($status, $bool, 1), (isset($vals[$status.$bool]) ? (int) $vals[$status.$bool] : 0)); - if ($status == 3 && !$bool) $bool = true; - else $bool = false; + if ($status == 3 && !$bool) { + $bool = true; + } else { + $bool = false; + } - if ($status == Fichinter::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == Fichinter::STATUS_VALIDATED) $colorseries[$status] = $badgeStatus1; - if ($status == Fichinter::STATUS_BILLED) $colorseries[$status] = $badgeStatus4; - if ($status == Fichinter::STATUS_CLOSED) $colorseries[$status] = $badgeStatus6; + if ($status == Fichinter::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == Fichinter::STATUS_VALIDATED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == Fichinter::STATUS_BILLED) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == Fichinter::STATUS_CLOSED) { + $colorseries[$status] = $badgeStatus6; + } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr class="impair"><td class="center" colspan="2">'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -160,10 +174,8 @@ if ($resql) print '</td></tr>'; } $bool = false; - foreach ($listofstatus as $status) - { - if (!$conf->use_javascript_ajax) - { + foreach ($listofstatus as $status) { + if (!$conf->use_javascript_ajax) { print '<tr class="oddeven">'; print '<td>'.$fichinterstatic->LibStatut($status, $bool, 0).'</td>'; print '<td class="right"><a href="list.php?search_status='.$status.'">'.(isset($vals[$status.$bool]) ? $vals[$status.$bool] : 0).' '; @@ -171,8 +183,11 @@ if ($resql) print '</a>'; print '</td>'; print "</tr>\n"; - if ($status == 3 && !$bool) $bool = true; - else $bool = false; + if ($status == 3 && !$bool) { + $bool = true; + } else { + $bool = false; + } } } //if ($totalinprocess != $total) @@ -187,32 +202,34 @@ if ($resql) /* * Draft orders */ -if (!empty($conf->ficheinter->enabled)) -{ +if (!empty($conf->ficheinter->enabled)) { $sql = "SELECT f.rowid, f.ref, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; $sql .= " AND f.fk_statut = 0"; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="2">'.$langs->trans("DraftFichinter").'</th></tr>'; $langs->load("fichinter"); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; print '<td class="nowrap">'; @@ -239,29 +256,32 @@ $sql = "SELECT f.rowid, f.ref, f.fk_statut, f.date_valid as datec, f.tms as date $sql .= " s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as f,"; $sql .= " ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; //$sql.= " AND c.fk_statut > 2"; -if ($socid) $sql .= " AND f.fk_soc = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY f.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="4">'.$langs->trans("LastModifiedInterventions", $max).'</th></tr>'; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -296,29 +316,35 @@ if ($resql) } } print "</table></div><br>"; -} else dol_print_error($db); +} else { + dol_print_error($db); +} /* * interventions to process */ -if (!empty($conf->ficheinter->enabled)) -{ +if (!empty($conf->ficheinter->enabled)) { $sql = "SELECT f.rowid, f.ref, f.fk_statut, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."fichinter as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; $sql .= " AND f.fk_statut = 1"; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " ORDER BY f.rowid DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '<div class="div-table-responsive-no-min">'; @@ -326,11 +352,9 @@ if (!empty($conf->ficheinter->enabled)) print '<tr class="liste_titre">'; print '<th colspan="3">'.$langs->trans("FichinterToProcess").' <a href="'.DOL_URL_ROOT.'/fichinter/list.php?search_status=1"><span class="badge">'.$num.'</span></a></th></tr>'; - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; print '<td class="nowrap" width="20%">'; @@ -366,7 +390,9 @@ if (!empty($conf->ficheinter->enabled)) } print "</table></div><br>"; - } else dol_print_error($db); + } else { + dol_print_error($db); + } } print '</div></div></div>'; diff --git a/htdocs/fichinter/info.php b/htdocs/fichinter/info.php index a53c69b77bd..39ac695f84e 100644 --- a/htdocs/fichinter/info.php +++ b/htdocs/fichinter/info.php @@ -40,13 +40,14 @@ $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); $object = new Fichinter($db); -if (!$object->fetch($id, $ref) > 0) -{ +if (!$object->fetch($id, $ref) > 0) { dol_print_error($db); exit; } @@ -77,15 +78,14 @@ $morehtmlref = '<div class="refidno">'; // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { - if ($action != 'classify') + if ($user->rights->commande->creer) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $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 .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; diff --git a/htdocs/fichinter/list.php b/htdocs/fichinter/list.php index d054f5e5bcc..8f0ae8e626f 100644 --- a/htdocs/fichinter/list.php +++ b/htdocs/fichinter/list.php @@ -32,13 +32,21 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; -if (!empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -if (!empty($conf->contrat->enabled)) require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; +if (!empty($conf->projet->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +} +if (!empty($conf->contrat->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/contrat/class/contrat.class.php'; +} // Load translation files required by the page $langs->loadLangs(array('companies', 'bills', 'interventions')); -if (!empty($conf->projet->enabled)) $langs->load("projects"); -if (!empty($conf->contrat->enabled)) $langs->load("contracts"); +if (!empty($conf->projet->enabled)) { + $langs->load("projects"); +} +if (!empty($conf->contrat->enabled)) { + $langs->load("contracts"); +} $action = GETPOST('action', 'aZ09'); $massaction = GETPOST('massaction', 'alpha'); @@ -59,7 +67,9 @@ $socid = GETPOST('socid', 'int'); // Security check $id = GETPOST('id', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); $diroutputmassaction = $conf->ficheinter->dir_output.'/temp/massgeneration/'.$user->id; @@ -68,14 +78,17 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) -{ - $sortfield = "f.ref"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "f.ref"; } // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -97,8 +110,12 @@ $fieldstosearchall = array( 'f.note_public'=>'NotePublic', 'fd.description'=>'DescriptionOfLine', ); -if (empty($user->socid)) $fieldstosearchall["f.note_private"] = "NotePrivate"; -if (!empty($conf->global->FICHINTER_DISABLE_DETAILS)) unset($fieldstosearchall['fd.description']); +if (empty($user->socid)) { + $fieldstosearchall["f.note_private"] = "NotePrivate"; +} +if (!empty($conf->global->FICHINTER_DISABLE_DETAILS)) { + unset($fieldstosearchall['fd.description']); +} // Definition of fields for list $arrayfields = array( @@ -127,21 +144,25 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { + $massaction = ''; +} $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { + 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_company = ""; $search_projet_ref = ""; @@ -187,10 +208,8 @@ $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $atleastonefieldinlines = 0; -foreach ($arrayfields as $tmpkey => $tmpval) -{ - if (preg_match('/^fd\./', $tmpkey) && !empty($arrayfields[$tmpkey]['checked'])) - { +foreach ($arrayfields as $tmpkey => $tmpval) { + if (preg_match('/^fd\./', $tmpkey) && !empty($arrayfields[$tmpkey]['checked'])) { $atleastonefieldinlines++; break; } @@ -198,7 +217,9 @@ foreach ($arrayfields as $tmpkey => $tmpval) $sql = "SELECT"; $sql .= " f.ref, f.rowid, f.fk_statut as status, f.description, f.datec as date_creation, f.tms as date_update, f.note_public, f.note_private,"; -if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) $sql .= " fd.rowid as lineid, fd.description as descriptiondetail, fd.date as dp, fd.duree,"; +if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) { + $sql .= " fd.rowid as lineid, fd.description as descriptiondetail, fd.date as dp, fd.duree,"; +} $sql .= " s.nom as name, s.rowid as socid, s.client, s.fournisseur, s.email, s.status as thirdpartystatus"; if (!empty($conf->projet->enabled)) { $sql .= ", pr.rowid as projet_id, pr.ref as projet_ref, pr.title as projet_title"; @@ -208,7 +229,9 @@ if (!empty($conf->contrat->enabled)) { } // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); @@ -221,9 +244,15 @@ if (!empty($conf->projet->enabled)) { if (!empty($conf->contrat->enabled)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."contrat as c on f.fk_contrat = c.rowid"; } -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; -if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."fichinterdet as fd ON fd.fk_fichinter = f.rowid"; -if (!$user->rights->societe->client->voir && empty($socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; +} +if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."fichinterdet as fd ON fd.fk_fichinter = f.rowid"; +} +if (!$user->rights->societe->client->voir && empty($socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= ", ".MAIN_DB_PREFIX."societe as s"; $sql .= " WHERE f.entity IN (".getEntity('intervention').")"; $sql .= " AND f.fk_soc = s.rowid"; @@ -240,16 +269,21 @@ if ($search_contrat_ref) { $sql .= natural_search('c.ref', $search_contrat_ref); } if ($search_desc) { - if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); - else $sql .= natural_search(array('f.description'), $search_desc); + if (empty($conf->global->FICHINTER_DISABLE_DETAILS) && $atleastonefieldinlines) { + $sql .= natural_search(array('f.description', 'fd.description'), $search_desc); + } else { + $sql .= natural_search(array('f.description'), $search_desc); + } } if ($search_status != '' && $search_status >= 0) { $sql .= ' AND f.fk_statut = '.urlencode($search_status); } -if (!$user->rights->societe->client->voir && empty($socid)) +if (!$user->rights->societe->client->voir && empty($socid)) { $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) +} +if ($socid) { $sql .= " AND s.rowid = ".$socid; +} if ($sall) { $sql .= natural_search(array_keys($fieldstosearchall), $sall); } @@ -263,12 +297,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -278,30 +310,50 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($socid > 0) - { + if ($socid > 0) { $soc = new Societe($db); $soc->fetch($socid); - if (empty($search_company)) $search_company = $soc->name; + if (empty($search_company)) { + $search_company = $soc->name; + } } $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sall) $param .= "&sall=".urlencode($sall); - if ($socid) $param .= "&socid=".urlencode($socid); - if ($search_ref) $param .= "&search_ref=".urlencode($search_ref); - if ($search_company) $param .= "&search_company=".urlencode($search_company); - if ($search_desc) $param .= "&search_desc=".urlencode($search_desc); - if ($search_status != '' && $search_status > -1) $param .= "&search_status=".urlencode($search_status); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($sall) { + $param .= "&sall=".urlencode($sall); + } + if ($socid) { + $param .= "&socid=".urlencode($socid); + } + if ($search_ref) { + $param .= "&search_ref=".urlencode($search_ref); + } + if ($search_company) { + $param .= "&search_company=".urlencode($search_company); + } + if ($search_desc) { + $param .= "&search_desc=".urlencode($search_desc); + } + if ($search_status != '' && $search_status > -1) { + $param .= "&search_status=".urlencode($search_status); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -311,19 +363,27 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), //'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->ficheinter->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if ($user->rights->ficheinter->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $newcardbutton = ''; $url = DOL_URL_ROOT.'/fichinter/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewIntervention'), '', 'fa fa-plus-circle', $url, '', $user->rights->ficheinter->creer); // Lines of title fields print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -339,9 +399,10 @@ if ($resql) $trackid = 'int'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } @@ -349,48 +410,47 @@ if ($resql) $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 (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; + } else { + $moreforfilter = $hookmanager->resPrint; + } - if (!empty($moreforfilter)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; } - if ($massactionbutton) $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + } print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; print '<tr class="liste_titre_filter">'; - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_ref" value="'.$search_ref.'" size="8">'; print '</td>'; } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_company" value="'.$search_company.'" size="10">'; print '</td>'; } - if (!empty($arrayfields['pr.ref']['checked'])) - { + if (!empty($arrayfields['pr.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_projet_ref" value="'.$search_projet_ref.'" size="8">'; print '</td>'; } - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_contrat_ref" value="'.$search_contrat_ref.'" size="8">'; print '</td>'; } - if (!empty($arrayfields['f.description']['checked'])) - { + if (!empty($arrayfields['f.description']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" name="search_desc" value="'.$search_desc.'" size="12">'; print '</td>'; @@ -402,51 +462,45 @@ if ($resql) $parameters = array('arrayfields'=>$arrayfields); $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { // Date creation print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { // Date modification print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['f.note_public']['checked'])) - { + if (!empty($arrayfields['f.note_public']['checked'])) { // Note public print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['f.note_private']['checked'])) - { + if (!empty($arrayfields['f.note_private']['checked'])) { // Note private print '<td class="liste_titre">'; print '</td>'; } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '<td class="liste_titre right">'; $tmp = $objectstatic->LibStatut(0); // To load $this->statuts_short $liststatus = $objectstatic->statuts_short; - if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 + if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) { + unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 + } print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 1); print '</td>'; } // Fields of detail line - if (!empty($arrayfields['fd.description']['checked'])) - { + if (!empty($arrayfields['fd.description']['checked'])) { print '<td class="liste_titre">&nbsp;</td>'; } - if (!empty($arrayfields['fd.date']['checked'])) - { + if (!empty($arrayfields['fd.date']['checked'])) { print '<td class="liste_titre">&nbsp;</td>'; } - if (!empty($arrayfields['fd.duree']['checked'])) - { + if (!empty($arrayfields['fd.duree']['checked'])) { print '<td class="liste_titre">&nbsp;</td>'; } print '<td class="liste_titre maxwidthsearch">'; @@ -457,33 +511,58 @@ if ($resql) print "</tr>\n"; print '<tr class="liste_titre">'; - if (!empty($arrayfields['f.ref']['checked'])) print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['pr.ref']['checked'])) print_liste_field_titre($arrayfields['pr.ref']['label'], $_SERVER["PHP_SELF"], "pr.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['c.ref']['checked'])) print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.description']['checked'])) print_liste_field_titre($arrayfields['f.description']['label'], $_SERVER["PHP_SELF"], "f.description", "", $param, '', $sortfield, $sortorder); + if (!empty($arrayfields['f.ref']['checked'])) { + print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER["PHP_SELF"], "f.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['pr.ref']['checked'])) { + print_liste_field_titre($arrayfields['pr.ref']['label'], $_SERVER["PHP_SELF"], "pr.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['c.ref']['checked'])) { + print_liste_field_titre($arrayfields['c.ref']['label'], $_SERVER["PHP_SELF"], "c.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.description']['checked'])) { + print_liste_field_titre($arrayfields['f.description']['label'], $_SERVER["PHP_SELF"], "f.description", "", $param, '', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.note_public']['checked'])) print_liste_field_titre($arrayfields['f.note_public']['label'], $_SERVER["PHP_SELF"], "f.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.note_private']['checked'])) print_liste_field_titre($arrayfields['f.note_private']['label'], $_SERVER["PHP_SELF"], "f.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "f.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['fd.description']['checked'])) print_liste_field_titre($arrayfields['fd.description']['label'], $_SERVER["PHP_SELF"], ''); - if (!empty($arrayfields['fd.date']['checked'])) print_liste_field_titre($arrayfields['fd.date']['label'], $_SERVER["PHP_SELF"], "fd.date", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['fd.duree']['checked'])) print_liste_field_titre($arrayfields['fd.duree']['label'], $_SERVER["PHP_SELF"], "fd.duree", "", $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['f.datec']['checked'])) { + print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.tms']['checked'])) { + print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.note_public']['checked'])) { + print_liste_field_titre($arrayfields['f.note_public']['label'], $_SERVER["PHP_SELF"], "f.note_public", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.note_private']['checked'])) { + print_liste_field_titre($arrayfields['f.note_private']['label'], $_SERVER["PHP_SELF"], "f.note_private", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "f.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['fd.description']['checked'])) { + print_liste_field_titre($arrayfields['fd.description']['label'], $_SERVER["PHP_SELF"], ''); + } + if (!empty($arrayfields['fd.date']['checked'])) { + print_liste_field_titre($arrayfields['fd.date']['label'], $_SERVER["PHP_SELF"], "fd.date", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['fd.duree']['checked'])) { + print_liste_field_titre($arrayfields['fd.duree']['label'], $_SERVER["PHP_SELF"], "fd.duree", "", $param, '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; $total = 0; $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -500,8 +579,7 @@ if ($resql) print '<tr class="oddeven">'; - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print "<td>"; print '<table class="nobordernopadding"><tr class="nocellnopadd">'; @@ -512,15 +590,13 @@ if ($resql) // Warning $warnornote = ''; //if ($obj->fk_statut == 1 && $db->jdate($obj->dfv) < ($now - $conf->fichinter->warning_delay)) $warnornote.=img_warning($langs->trans("Late")); - if (!empty($obj->note_private)) - { + if (!empty($obj->note_private)) { $warnornote .= ($warnornote ? ' ' : ''); $warnornote .= '<span class="note">'; $warnornote .= '<a href="note.php?id='.$obj->rowid.'">'.img_picto($langs->trans("ViewPrivateNote"), 'object_generic').'</a>'; $warnornote .= '</span>'; } - if ($warnornote) - { + if ($warnornote) { print '<td style="min-width: 20px" class="nobordernopadding nowrap">'; print $warnornote; print '</td>'; @@ -535,17 +611,19 @@ if ($resql) print '</td></tr></table>'; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td>'; print $companystatic->getNomUrl(1, '', 44); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['pr.ref']['checked'])) - { + if (!empty($arrayfields['pr.ref']['checked'])) { print '<td>'; $projetstatic->id = $obj->projet_id; $projetstatic->ref = $obj->projet_ref; @@ -554,10 +632,11 @@ if ($resql) print $projetstatic->getNomUrl(1, ''); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['c.ref']['checked'])) - { + if (!empty($arrayfields['c.ref']['checked'])) { print '<td>'; $contratstatic->id = $obj->contrat_id; $contratstatic->ref = $obj->contrat_ref; @@ -567,12 +646,15 @@ if ($resql) print $contratstatic->getNomUrl(1, ''); print '</td>'; } - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['f.description']['checked'])) - { + if (!empty($arrayfields['f.description']['checked'])) { print '<td>'.dol_trunc(dolGetFirstLineOfText($obj->description), 48).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -582,71 +664,84 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note public - if (!empty($arrayfields['f.note_public']['checked'])) - { + if (!empty($arrayfields['f.note_public']['checked'])) { print '<td class="center">'; print dol_escape_htmltag($obj->note_public); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Note private - if (!empty($arrayfields['f.note_private']['checked'])) - { + if (!empty($arrayfields['f.note_private']['checked'])) { print '<td class="center">'; print dol_escape_htmltag($obj->note_private); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '<td class="right">'.$objectstatic->getLibStatut(5).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Fields of detail of line - if (!empty($arrayfields['fd.description']['checked'])) - { + if (!empty($arrayfields['fd.description']['checked'])) { print '<td>'.dolGetFirstLineOfText($obj->descriptiondetail).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['fd.date']['checked'])) - { + if (!empty($arrayfields['fd.date']['checked'])) { print '<td class="center">'.dol_print_date($db->jdate($obj->dp), 'dayhour')."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['fd.duree']['checked'])) - { + if (!empty($arrayfields['fd.duree']['checked'])) { print '<td class="right">'.convertSecondToTime($obj->duree, 'allhourmin').'</td>'; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'fd.duree'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'fd.duree'; + } $totalarray['val']['fd.duree'] += $obj->duree; } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + if (in_array($obj->rowid, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; @@ -669,7 +764,9 @@ if ($resql) print "</form>\n"; $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/fichinter/note.php b/htdocs/fichinter/note.php index dddbe79e33e..fcc790bf8c2 100644 --- a/htdocs/fichinter/note.php +++ b/htdocs/fichinter/note.php @@ -39,7 +39,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'ficheinter', $id, 'fichinter'); $object = new Fichinter($db); @@ -62,8 +64,7 @@ llxHeader('', $langs->trans("Intervention")); $form = new Form($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch_thirdparty(); $head = fichinter_prepare_head($object); @@ -80,12 +81,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= $langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->commande->creer) - { + if ($user->rights->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fichinter/stats/index.php b/htdocs/fichinter/stats/index.php index 19e7f86d8a0..29a5f9976b0 100644 --- a/htdocs/fichinter/stats/index.php +++ b/htdocs/fichinter/stats/index.php @@ -30,13 +30,14 @@ $WIDTH = DolGraph::getDefaultGraphSizeForStats('width'); $HEIGHT = DolGraph::getDefaultGraphSizeForStats('height'); $mode = 'customer'; -if (!$user->rights->ficheinter->lire) accessforbidden(); +if (!$user->rights->ficheinter->lire) { + accessforbidden(); +} $userid = GETPOST('userid', 'int'); $socid = GETPOST('socid', 'int'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -70,15 +71,16 @@ print load_fiche_titre($title, '', 'intervention'); dol_mkdir($dir); $stats = new FichinterStats($db, $socid, $mode, ($userid > 0 ? $userid : 0)); -if ($object_status != '' && $object_status > -1) $stats->where .= ' AND c.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +if ($object_status != '' && $object_status > -1) { + $stats->where .= ' AND c.fk_statut IN ('.$db->sanitize($db->escape($object_status)).')'; +} // Build graphic number of object $data = $stats->getNbByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenamenb = $dir.'/interventionsnbinyear-'.$user->id.'-'.$year.'.png'; $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsnbinyear-'.$user->id.'-'.$year.'.png'; } else { @@ -88,12 +90,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px1 = new DolGraph(); $mesg = $px1->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px1->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -115,8 +115,7 @@ if (!$mesg) $data = $stats->getAmountByMonthWithPrevYear($endyear, $startyear); // $data = array(array('Lib',val1,val2,val3),...) -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filenameamount = $dir.'/interventionsamountinyear-'.$user->id.'-'.$year.'.png'; $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsamountinyear-'.$user->id.'-'.$year.'.png'; } else { @@ -126,12 +125,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px2 = new DolGraph(); $mesg = $px2->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px2->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -152,8 +149,7 @@ if (!$mesg) $data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear); -if (!$user->rights->societe->client->voir || $user->socid) -{ +if (!$user->rights->societe->client->voir || $user->socid) { $filename_avg = $dir.'/interventionsaverage-'.$user->id.'-'.$year.'.png'; $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsaverage-'.$user->id.'-'.$year.'.png'; } else { @@ -163,12 +159,10 @@ if (!$user->rights->societe->client->voir || $user->socid) $px3 = new DolGraph(); $mesg = $px3->isGraphKo(); -if (!$mesg) -{ +if (!$mesg) { $px3->SetData($data); $i = $startyear; $legend = array(); - while ($i <= $endyear) - { + while ($i <= $endyear) { $legend[] = $i; $i++; } @@ -196,7 +190,9 @@ foreach ($data as $val) { $arrayyears[$val['year']] = $val['year']; } } -if (!count($arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!count($arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} $h = 0; $head = array(); @@ -236,13 +232,19 @@ print '<div class="fichecenter"><div class="fichethirdleft">'; print '<tr><td class="left">'.$langs->trans("Status").'</td><td class="left">'; $tmp = $objectstatic->LibStatut(0); // To load $this->statuts_short $liststatus = $objectstatic->statuts_short; - if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 +if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) { + unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1 +} print $form->selectarray('object_status', $liststatus, $object_status, 1, 0, 0, '', 1); print '</td></tr>'; // Year print '<tr><td class="left">'.$langs->trans("Year").'</td><td class="left">'; - if (!in_array($year, $arrayyears)) $arrayyears[$year] = $year; - if (!in_array($nowyear, $arrayyears)) $arrayyears[$nowyear] = $nowyear; +if (!in_array($year, $arrayyears)) { + $arrayyears[$year] = $year; +} +if (!in_array($nowyear, $arrayyears)) { + $arrayyears[$nowyear] = $nowyear; +} arsort($arrayyears); print $form->selectarray('year', $arrayyears, $year, 0); print '</td></tr>'; @@ -265,11 +267,9 @@ print '<td class="right">%</td>'; print '</tr>'; $oldyear = 0; -foreach ($data as $val) -{ +foreach ($data as $val) { $year = $val['year']; - while (!empty($year) && $oldyear > $year + 1) - { + while (!empty($year) && $oldyear > $year + 1) { // If we have empty year $oldyear--; @@ -307,12 +307,14 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">'; // Show graphs print '<table class="border centpercent"><tr class="pair nohover"><td class="center">'; -if ($mesg) { print $mesg; } else { +if ($mesg) { + print $mesg; +} else { print $px1->show(); /*print "<br>\n"; - print $px2->show(); - print "<br>\n"; - print $px3->show();*/ + print $px2->show(); + print "<br>\n"; + print $px3->show();*/ } print '</td></tr></table>'; diff --git a/htdocs/fichinter/tpl/linkedobjectblock.tpl.php b/htdocs/fichinter/tpl/linkedobjectblock.tpl.php index b483e877e5e..ba754ec3321 100644 --- a/htdocs/fichinter/tpl/linkedobjectblock.tpl.php +++ b/htdocs/fichinter/tpl/linkedobjectblock.tpl.php @@ -16,8 +16,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -36,17 +35,18 @@ $langs->load("interventions"); $linkedObjectBlock = dol_sort_array($linkedObjectBlock, 'date', 'desc', 0, 0, 1); $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - <tr class="<?php echo $trclass; ?>"> + <tr class="<?php echo $trclass; ?>"> <td><?php echo $langs->trans("Intervention"); ?></td> - <td><?php echo $objectlink->getNomUrl(1); ?></td> - <td></td> + <td><?php echo $objectlink->getNomUrl(1); ?></td> + <td></td> <td class="center"><?php echo dol_print_date($objectlink->datev, 'day'); ?></td> <td></td> <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> From ed6d2376f14eeb456fe6c26a4c4ea38163cb4173 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= <frederic.france@free.fr> Date: Thu, 25 Feb 2021 23:21:30 +0100 Subject: [PATCH 43/64] code syntax fourn directory --- htdocs/fourn/ajax/getSupplierPrices.php | 42 +- htdocs/fourn/card.php | 320 ++--- .../class/api_supplier_invoices.class.php | 57 +- .../fourn/class/api_supplier_orders.class.php | 108 +- htdocs/fourn/class/fournisseur.class.php | 35 +- .../class/fournisseur.commande.class.php | 1019 +++++++-------- .../fournisseur.commande.dispatch.class.php | 239 ++-- .../fourn/class/fournisseur.facture.class.php | 962 +++++++------- .../fourn/class/fournisseur.product.class.php | 205 +-- htdocs/fourn/class/paiementfourn.class.php | 178 ++- htdocs/fourn/commande/card.php | 998 +++++++-------- htdocs/fourn/commande/contact.php | 48 +- htdocs/fourn/commande/dispatch.php | 267 ++-- htdocs/fourn/commande/document.php | 31 +- htdocs/fourn/commande/index.php | 130 +- htdocs/fourn/commande/info.php | 71 +- htdocs/fourn/commande/list.php | 934 +++++++++----- htdocs/fourn/commande/note.php | 16 +- .../commande/tpl/linkedobjectblock.tpl.php | 51 +- htdocs/fourn/contact.php | 33 +- htdocs/fourn/facture/card.php | 1135 ++++++++--------- htdocs/fourn/facture/contact.php | 83 +- htdocs/fourn/facture/document.php | 73 +- htdocs/fourn/facture/impayees.php | 131 +- htdocs/fourn/facture/index.php | 116 +- htdocs/fourn/facture/info.php | 69 +- htdocs/fourn/facture/list.php | 1060 +++++++++------ htdocs/fourn/facture/note.php | 52 +- htdocs/fourn/facture/paiement.php | 266 ++-- htdocs/fourn/facture/rapport.php | 58 +- .../facture/tpl/linkedobjectblock.tpl.php | 60 +- htdocs/fourn/index.php | 93 +- htdocs/fourn/js/lib_dispatch.js.php | 35 +- htdocs/fourn/paiement/card.php | 92 +- htdocs/fourn/paiement/info.php | 4 +- htdocs/fourn/paiement/list.php | 220 +++- htdocs/fourn/product/list.php | 132 +- htdocs/fourn/recap-fourn.php | 31 +- 38 files changed, 5080 insertions(+), 4374 deletions(-) diff --git a/htdocs/fourn/ajax/getSupplierPrices.php b/htdocs/fourn/ajax/getSupplierPrices.php index 0c0d8f42c9e..e0cd9beff0c 100644 --- a/htdocs/fourn/ajax/getSupplierPrices.php +++ b/htdocs/fourn/ajax/getSupplierPrices.php @@ -22,10 +22,18 @@ * \brief File to return an Ajax response to get list of possible prices for margin calculation */ -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', '1'); // Disables token renewal +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', '1'); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php'; @@ -46,47 +54,45 @@ top_httphead(); //print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n"; -if ($idprod > 0) -{ +if ($idprod > 0) { $producttmp = new ProductFournisseur($db); $producttmp->fetch($idprod); $sorttouse = 's.nom, pfp.quantity, pfp.price'; - if (GETPOST('bestpricefirst')) $sorttouse = 'pfp.unitprice, s.nom, pfp.quantity, pfp.price'; + if (GETPOST('bestpricefirst')) { + $sorttouse = 'pfp.unitprice, s.nom, pfp.quantity, pfp.price'; + } $productSupplierArray = $producttmp->list_product_fournisseur_price($idprod, $sorttouse); // We list all price per supplier, and then firstly with the lower quantity. So we can choose first one with enough quantity into list. - if (is_array($productSupplierArray)) - { - foreach ($productSupplierArray as $productSupplier) - { + if (is_array($productSupplierArray)) { + foreach ($productSupplierArray as $productSupplier) { $price = $productSupplier->fourn_price * (1 - $productSupplier->fourn_remise_percent / 100); $unitprice = $productSupplier->fourn_unitprice * (1 - $productSupplier->fourn_remise_percent / 100); $title = $productSupplier->fourn_name.' - '.$productSupplier->fourn_ref.' - '; - if ($productSupplier->fourn_qty == 1) - { + if ($productSupplier->fourn_qty == 1) { $title .= price($price, 0, $langs, 0, 0, -1, $conf->currency)."/"; } $title .= $productSupplier->fourn_qty.' '.($productSupplier->fourn_qty == 1 ? $langs->trans("Unit") : $langs->trans("Units")); - if ($productSupplier->fourn_qty > 1) - { + if ($productSupplier->fourn_qty > 1) { $title .= " - "; $title .= price($unitprice, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit"); $price = $unitprice; } $label = price($price, 0, $langs, 0, 0, -1, $conf->currency)."/".$langs->trans("Unit"); - if ($productSupplier->fourn_ref) $label .= ' ('.$productSupplier->fourn_ref.')'; + if ($productSupplier->fourn_ref) { + $label .= ' ('.$productSupplier->fourn_ref.')'; + } $prices[] = array("id" => $productSupplier->product_fourn_price_id, "price" => price2num($price, 0, '', 0), "label" => $label, "title" => $title); // For price field, we must use price2num(), for label or title, price() } } // After best supplier prices and before costprice - if (!empty($conf->stock->enabled)) - { + if (!empty($conf->stock->enabled)) { // Add price for pmp $price = $producttmp->pmp; $prices[] = array("id" => 'pmpprice', "price" => price2num($price), "label" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency), "title" => $langs->trans("PMPValueShort").': '.price($price, 0, $langs, 0, 0, -1, $conf->currency)); // For price field, we must use price2num(), for label or title, price() diff --git a/htdocs/fourn/card.php b/htdocs/fourn/card.php index 9794ea3cc11..d39cbf7ca0f 100644 --- a/htdocs/fourn/card.php +++ b/htdocs/fourn/card.php @@ -35,8 +35,12 @@ require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -if (!empty($conf->adherent->enabled)) require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; -if (!empty($conf->categorie->enabled)) require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +if (!empty($conf->adherent->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php'; +} +if (!empty($conf->categorie->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; +} // Load translation files required by page $langs->loadLangs(array( @@ -53,7 +57,9 @@ $cancelbutton = GETPOST('cancel', 'alpha'); // Security check $id = (GETPOST('socid', 'int') ? GETPOST('socid', 'int') : GETPOST('id', 'int')); -if ($user->socid) $id = $user->socid; +if ($user->socid) { + $id = $user->socid; +} $result = restrictedArea($user, 'societe&fournisseur', $id, '&societe', '', 'rowid'); $object = new Fournisseur($db); @@ -81,44 +87,48 @@ if ($object->id > 0) { $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if ($cancelbutton) - { +if (empty($reshook)) { + if ($cancelbutton) { $action = ""; } - if ($action == 'setsupplieraccountancycode') - { + if ($action == 'setsupplieraccountancycode') { $result = $object->fetch($id); - $object->code_compta_fournisseur = $_POST["supplieraccountancycode"]; + $object->code_compta_fournisseur = $_POST["supplieraccountancycode"]; $result = $object->update($object->id, $user, 1, 0, 1); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // terms of the settlement - if ($action == 'setconditions' && $user->rights->societe->creer) - { + if ($action == 'setconditions' && $user->rights->societe->creer) { $object->fetch($id); $result = $object->setPaymentTerms(GETPOST('cond_reglement_supplier_id', 'int')); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } } // mode de reglement - if ($action == 'setmode' && $user->rights->societe->creer) - { + if ($action == 'setmode' && $user->rights->societe->creer) { $object->fetch($id); $result = $object->setPaymentMethods(GETPOST('mode_reglement_supplier_id', 'int')); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } } // update supplier order min amount - if ($action == 'setsupplier_order_min_amount') - { + if ($action == 'setsupplier_order_min_amount') { $object->fetch($id); $object->supplier_order_min_amount = price2num(GETPOST('supplier_order_min_amount', 'alpha')); $result = $object->update($object->id, $user); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } if ($action == 'update_extras') { @@ -129,15 +139,20 @@ if (empty($reshook)) // 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) $error++; + if ($ret < 0) { + $error++; } - if ($error) $action = 'edit_extras'; + if (!$error) { + $result = $object->insertExtraFields('COMPANY_MODIFY'); + if ($result < 0) { + $error++; + } + } + + if ($error) { + $action = 'edit_extras'; + } } } @@ -149,17 +164,19 @@ if (empty($reshook)) $contactstatic = new Contact($db); $form = new Form($db); -if ($id > 0 && empty($object->id)) -{ +if ($id > 0 && empty($object->id)) { // Load data of third party $res = $object->fetch($id); - if ($object->id <= 0) dol_print_error($db, $object->error); + if ($object->id <= 0) { + dol_print_error($db, $object->error); + } } -if ($object->id > 0) -{ +if ($object->id > 0) { $title = $langs->trans("ThirdParty")." - ".$langs->trans('Supplier'); - if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->name." - ".$langs->trans('Supplier'); + if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/thirdpartynameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->name." - ".$langs->trans('Supplier'); + } $help_url = ''; llxHeader('', $title, $help_url); @@ -184,22 +201,20 @@ if ($object->id > 0) print $object->getTypeUrl(1); print '</td></tr>'; - if (!empty($conf->global->SOCIETE_USEPREFIX)) // Old not used prefix field - { + if (!empty($conf->global->SOCIETE_USEPREFIX)) { // Old not used prefix field print '<tr><td>'.$langs->trans('Prefix').'</td><td colspan="3">'.$object->prefix_comm.'</td></tr>'; } - if ($object->fournisseur) - { + if ($object->fournisseur) { print '<tr>'; - print '<td class="titlefield">'.$langs->trans("SupplierCode").'</td><td>'; - print $object->code_fournisseur; - $tmpcheck = $object->check_codefournisseur(); - if ($tmpcheck != 0 && $tmpcheck != -5) { - print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; - } - print '</td>'; - print '</tr>'; + print '<td class="titlefield">'.$langs->trans("SupplierCode").'</td><td>'; + print $object->code_fournisseur; + $tmpcheck = $object->check_codefournisseur(); + if ($tmpcheck != 0 && $tmpcheck != -5) { + print ' <font class="error">('.$langs->trans("WrongSupplierCode").')</font>'; + } + print '</td>'; + print '</tr>'; $langs->load('compta'); print '<tr>'; @@ -221,14 +236,12 @@ if ($object->id > 0) print '</tr>'; // Local Taxes - if ($mysoc->useLocalTax(1)) - { + if ($mysoc->useLocalTax(1)) { print '<tr><td>'.$langs->transcountry("LocalTax1IsUsed", $mysoc->country_code).'</td><td>'; print yn($object->localtax1_assuj); print '</td></tr>'; } - if ($mysoc->useLocalTax(2)) - { + if ($mysoc->useLocalTax(2)) { print '<tr><td>'.$langs->transcountry("LocalTax2IsUsed", $mysoc->country_code).'</td><td>'; print yn($object->localtax2_assuj); print '</td></tr>'; @@ -246,11 +259,12 @@ if ($object->id > 0) print '<table width="100%" class="nobordernopadding"><tr><td>'; print $langs->trans('PaymentConditions'); print '<td>'; - if (($action != 'editconditions') && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>'; + if (($action != 'editconditions') && $user->rights->societe->creer) { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editconditions') - { + if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->cond_reglement_supplier_id, 'cond_reglement_supplier_id', -1, 1); } else { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->cond_reglement_supplier_id, 'none'); @@ -263,11 +277,12 @@ if ($object->id > 0) print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">'; print $langs->trans('PaymentMode'); print '<td>'; - if (($action != 'editmode') && $user->rights->societe->creer) print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>'; + if (($action != 'editmode') && $user->rights->societe->creer) { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;socid='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->mode_reglement_supplier_id, 'mode_reglement_supplier_id', 'DBIT', 1, 1); } else { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?socid='.$object->id, $object->mode_reglement_supplier_id, 'none'); @@ -280,8 +295,7 @@ if ($object->id > 0) print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">'; print $langs->trans("CustomerRelativeDiscountShort"); print '<td><td class="right">'; - if ($user->rights->societe->creer && !$user->socid > 0) - { + if ($user->rights->societe->creer && !$user->socid > 0) { print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/remise.php?id='.$object->id.'">'.img_edit($langs->trans("Modify")).'</a>'; } print '</td></tr></table>'; @@ -294,22 +308,24 @@ if ($object->id > 0) print '<tr><td class="nowrap">'; print $langs->trans("CustomerAbsoluteDiscountShort"); print '<td><td class="right">'; - if ($user->rights->societe->creer && !$user->socid > 0) - { + if ($user->rights->societe->creer && !$user->socid > 0) { print '<a class="editfielda" href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.img_edit($langs->trans("Modify")).'</a>'; } print '</td></tr></table>'; print '</td>'; print '<td>'; $amount_discount = $object->getAvailableDiscounts('', '', 0, 1); - if ($amount_discount < 0) dol_print_error($db, $object->error); - if ($amount_discount > 0) print '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).'</a>'; + if ($amount_discount < 0) { + dol_print_error($db, $object->error); + } + if ($amount_discount > 0) { + print '<a href="'.DOL_URL_ROOT.'/comm/remx.php?id='.$object->id.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?socid='.$object->id).'">'.price($amount_discount, 1, $langs, 1, -1, -1, $conf->currency).'</a>'; + } //else print $langs->trans("DiscountNone"); print '</td>'; print '</tr>'; - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) && !empty($conf->global->ORDER_MANAGE_MIN_AMOUNT)) { print '<tr class="nowrap">'; print '<td>'; print $form->editfieldkey("OrderMinAmount", 'supplier_order_min_amount', $object->supplier_order_min_amount, $object, $user->rights->societe->creer); @@ -321,8 +337,7 @@ if ($object->id > 0) } // Categories - if (!empty($conf->categorie->enabled)) - { + if (!empty($conf->categorie->enabled)) { $langs->load("categories"); print '<tr><td>'.$langs->trans("SuppliersCategoriesShort").'</td>'; print '<td>'; @@ -335,16 +350,14 @@ if ($object->id > 0) include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; // Module Adherent - if (!empty($conf->adherent->enabled)) - { + if (!empty($conf->adherent->enabled)) { $langs->load("members"); $langs->load("users"); print '<tr><td>'.$langs->trans("LinkedToDolibarrMember").'</td>'; print '<td>'; $adh = new Adherent($db); $result = $adh->fetch('', '', $object->id); - if ($result > 0) - { + if ($result > 0) { $adh->ref = $adh->getFullName($langs); print $adh->getNomUrl(1); } else { @@ -371,8 +384,7 @@ if ($object->id > 0) $boxstat .= '<table summary="'.dol_escape_htmltag($langs->trans("DolibarrStateBoard")).'" class="border boxtable boxtablenobottom boxtablenotop" width="100%">'; $boxstat .= '<tr class="impair nohover"><td colspan="2" class="tdboxstats nohover">'; - if ($conf->supplier_proposal->enabled) - { + if ($conf->supplier_proposal->enabled) { // Box proposals $tmp = $object->getOutstandingProposals('supplier'); $outstandingOpened = $tmp['opened']; @@ -381,16 +393,19 @@ if ($object->id > 0) $text = $langs->trans("OverAllSupplierProposals"); $link = DOL_URL_ROOT.'/supplier_proposal/list.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } } - if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) - { + if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) { // Box proposals $tmp = $object->getOutstandingOrders('supplier'); $outstandingOpened = $tmp['opened']; @@ -399,16 +414,19 @@ if ($object->id > 0) $text = $langs->trans("OverAllOrders"); $link = DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } } - if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) - { + if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) { $tmp = $object->getOutstandingBills('supplier'); $outstandingOpened = $tmp['opened']; $outstandingTotal = $tmp['total_ht']; @@ -417,23 +435,31 @@ if ($object->id > 0) $text = $langs->trans("OverAllInvoices"); $link = DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator">'.price($outstandingTotal, 1, $langs, 1, -1, -1, $conf->currency).'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } // Box outstanding bill $text = $langs->trans("CurrentOutstandingBill"); $link = DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator'.($outstandingOpened > 0 ? ' amountremaintopay' : '').'">'.price($outstandingOpened, 1, $langs, 1, -1, -1, $conf->currency).$warn.'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } $tmp = $object->getOutstandingBills('supplier', 1); $outstandingOpenedLate = $tmp['opened']; @@ -441,12 +467,16 @@ if ($object->id > 0) $text = $langs->trans("CurrentOutstandingBillLate"); $link = DOL_URL_ROOT.'/fourn/recap-fourn.php?socid='.$object->id; $icon = 'bill'; - if ($link) $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + if ($link) { + $boxstat .= '<a href="'.$link.'" class="boxstatsindicator thumbstat nobold nounderline">'; + } $boxstat .= '<div class="boxstats" title="'.dol_escape_htmltag($text).'">'; $boxstat .= '<span class="boxstatstext">'.img_object("", $icon).' <span>'.$text.'</span></span><br>'; $boxstat .= '<span class="boxstatsindicator'.($outstandingOpenedLate > 0 ? ' amountremaintopay' : '').'">'.price($outstandingOpenedLate, 1, $langs, 1, -1, -1, $conf->currency).$warn.'</span>'; $boxstat .= '</div>'; - if ($link) $boxstat .= '</a>'; + if ($link) { + $boxstat .= '</a>'; + } } } @@ -468,13 +498,12 @@ if ($object->id > 0) print '</tr>'; print '</table>'; print '<br>'; - */ + */ /* * List of products */ - if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) - { + if (!empty($conf->product->enabled) || !empty($conf->service->enabled)) { $langs->load("products"); //Query from product/liste.php $sql = 'SELECT p.rowid, p.ref, p.label, p.fk_product_type, p.entity,'; @@ -487,7 +516,9 @@ if ($object->id > 0) $sql .= $db->plimit($MAXLIST); $query = $db->query($sql); - if (!$query) dol_print_error($db); + if (!$query) { + dol_print_error($db); + } $num = $db->num_rows($query); @@ -498,12 +529,10 @@ if ($object->id > 0) print '</a></td></tr>'; $return = array(); - if ($num > 0) - { + if ($num > 0) { $productstatic = new Product($db); - while ($objp = $db->fetch_object($query)) - { + while ($objp = $db->fetch_object($query)) { $productstatic->id = $objp->rowid; $productstatic->ref = $objp->ref; $productstatic->label = $objp->label; @@ -523,11 +552,9 @@ if ($object->id > 0) //print '<td class="right" class="nowrap">'.dol_print_date($objp->tms, 'day').'</td>'; print '<td class="right">'; //print (isset($objp->unitprice) ? price($objp->unitprice) : ''); - if (isset($objp->price)) - { + if (isset($objp->price)) { print price($objp->price); - if ($objp->quantity > 1) - { + if ($objp->quantity > 1) { print ' / '; print $objp->quantity; } @@ -546,8 +573,7 @@ if ($object->id > 0) */ $proposalstatic = new SupplierProposal($db); - if ($user->rights->supplier_proposal->lire) - { + if ($user->rights->supplier_proposal->lire) { $langs->loadLangs(array("supplier_proposal")); $sql = "SELECT p.rowid, p.ref, p.date_valid as dc, p.fk_statut, p.total_ht, p.total_tva, p.total_ttc"; @@ -558,13 +584,11 @@ if ($object->id > 0) $sql .= " ".$db->plimit($MAXLIST); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { print '<table class="noborder centpercent lastrecordtable">'; print '<tr class="liste_titre">'; @@ -576,8 +600,7 @@ if ($object->id > 0) print '</td></tr>'; } - while ($i < $num && $i <= $MAXLIST) - { + while ($i < $num && $i <= $MAXLIST) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -590,8 +613,7 @@ if ($object->id > 0) print $proposalstatic->getNomUrl(1); print '</td>'; print '<td class="center" width="80">'; - if ($obj->dc) - { + if ($obj->dc) { print dol_print_date($db->jdate($obj->dc), 'day'); } else { print "-"; @@ -603,7 +625,9 @@ if ($object->id > 0) } $db->free($resql); - if ($num > 0) print "</table>"; + if ($num > 0) { + print "</table>"; + } } else { dol_print_error($db); } @@ -614,8 +638,7 @@ if ($object->id > 0) */ $orderstatic = new CommandeFournisseur($db); - if ($user->rights->fournisseur->commande->lire) - { + if ($user->rights->fournisseur->commande->lire) { // TODO move to DAO class // Check if there are supplier orders billable $sql2 = 'SELECT s.nom, s.rowid as socid, s.client, c.rowid, c.ref, c.total_ht, c.ref_supplier,'; @@ -626,8 +649,7 @@ if ($object->id > 0) $sql2 .= " AND c.entity IN (".getEntity('commande_fournisseur').")"; $sql2 .= ' AND s.rowid = '.$object->id; // Show orders we can bill - if (empty($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS)) - { + if (empty($conf->global->SUPPLIER_ORDER_TO_INVOICE_STATUS)) { $sql2 .= " AND c.fk_statut IN (".$db->sanitize(CommandeFournisseur::STATUS_RECEIVED_COMPLETELY).")"; // Must match filter in htdocs/fourn/commande/list.php } else { // CommandeFournisseur::STATUS_ORDERSENT.", ".CommandeFournisseur::STATUS_RECEIVED_PARTIALLY.", ".CommandeFournisseur::STATUS_RECEIVED_COMPLETELY @@ -651,8 +673,7 @@ if ($object->id > 0) $sql .= " WHERE p.fk_soc =".$object->id; $sql .= " AND p.entity IN (".getEntity('commande_fournisseur').")"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $object_count = $db->fetch_object($resql); $num = $object_count->total; } @@ -664,12 +685,10 @@ if ($object->id > 0) $sql .= " ORDER BY p.date_commande DESC"; $sql .= " ".$db->plimit($MAXLIST); $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; - if ($num > 0) - { + if ($num > 0) { print '<table class="noborder centpercent lastrecordtable">'; print '<tr class="liste_titre">'; @@ -681,8 +700,7 @@ if ($object->id > 0) print '</td></tr>'; } - while ($i < $num && $i < $MAXLIST) - { + while ($i < $num && $i < $MAXLIST) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -695,8 +713,7 @@ if ($object->id > 0) print $orderstatic->getNomUrl(1); print '</td>'; print '<td class="center" width="80">'; - if ($obj->dc) - { + if ($obj->dc) { print dol_print_date($db->jdate($obj->dc), 'day'); } else { print "-"; @@ -708,7 +725,9 @@ if ($object->id > 0) } $db->free($resql); - if ($num > 0) print "</table>"; + if ($num > 0) { + print "</table>"; + } } else { dol_print_error($db); } @@ -721,8 +740,7 @@ if ($object->id > 0) $langs->load('bills'); $facturestatic = new FactureFournisseur($db); - if ($user->rights->fournisseur->facture->lire) - { + if ($user->rights->fournisseur->facture->lire) { // TODO move to DAO class $sql = 'SELECT f.rowid, f.libelle as label, f.ref, f.ref_supplier, f.fk_statut, f.datef as df, f.total_ht, f.total_tva, f.total_ttc as amount,f.paye,'; $sql .= ' SUM(pf.amount) as am'; @@ -733,12 +751,10 @@ if ($object->id > 0) $sql .= ' GROUP BY f.rowid,f.libelle,f.ref,f.ref_supplier,f.fk_statut,f.datef,f.total_ht,f.total_tva,f.total_ttc,f.paye'; $sql .= ' ORDER BY f.datef DESC'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { print '<table class="noborder centpercent lastrecordtable">'; print '<tr class="liste_titre">'; @@ -749,8 +765,7 @@ if ($object->id > 0) print '</td></tr>'; } - while ($i < min($num, $MAXLIST)) - { + while ($i < min($num, $MAXLIST)) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -777,7 +792,9 @@ if ($object->id > 0) $i++; } $db->free($resql); - if ($num > 0) print '</table>'; + if ($num > 0) { + print '</table>'; + } } else { dol_print_error($db); } @@ -797,15 +814,12 @@ if ($object->id > 0) $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { - if ($object->status != 1) - { + if (empty($reshook)) { + if ($object->status != 1) { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("ThirdPartyIsClosed")).'" href="#">'.$langs->trans("ThirdPartyIsClosed").'</a></div>'; } - if ($conf->supplier_proposal->enabled && $user->rights->supplier_proposal->creer) - { + if ($conf->supplier_proposal->enabled && $user->rights->supplier_proposal->creer) { $langs->load("supplier_proposal"); if ($object->status == 1) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/supplier_proposal/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddSupplierProposal").'</a>'; @@ -814,8 +828,7 @@ if ($object->id > 0) } } - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { $langs->load("orders"); if ($object->status == 1) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddOrder").'</a>'; @@ -824,21 +837,20 @@ if ($object->id > 0) } } - if ($user->rights->fournisseur->facture->creer) - { - if (!empty($orders2invoice) && $orders2invoice > 0) - { + if ($user->rights->fournisseur->facture->creer) { + if (!empty($orders2invoice) && $orders2invoice > 0) { if ($object->status == 1) { // Company is open print '<div class="inline-block divButAction"><a class="butAction" href="'.DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->id.'&search_billed=0&autoselectall=1">'.$langs->trans("CreateInvoiceForThisSupplier").'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>'; } - } else print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("NoOrdersToInvoice").' ('.$langs->trans("WithReceptionFinished").')').'" href="#">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>'; + } else { + print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" title="'.dol_escape_js($langs->trans("NoOrdersToInvoice").' ('.$langs->trans("WithReceptionFinished").')').'" href="#">'.$langs->trans("CreateInvoiceForThisCustomer").'</a></div>'; + } } - if ($user->rights->fournisseur->facture->creer) - { + if ($user->rights->fournisseur->facture->creer) { $langs->load("bills"); if ($object->status == 1) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddBill").'</a>'; @@ -848,10 +860,8 @@ if ($object->id > 0) } // Add action - if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1) - { - if ($user->rights->agenda->myactions->create) - { + if (!empty($conf->agenda->enabled) && !empty($conf->global->MAIN_REPEATTASKONEACHTAB) && $object->status == 1) { + if ($user->rights->agenda->myactions->create) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create&socid='.$object->id.'">'.$langs->trans("AddAction").'</a>'; } else { print '<a class="butAction" title="'.dol_escape_js($langs->trans("NotAllowed")).'" href="#">'.$langs->trans("AddAction").'</a>'; @@ -862,15 +872,13 @@ if ($object->id > 0) print '</div>'; - if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) - { + if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD)) { print '<br>'; // List of contacts show_contacts($conf, $langs, $db, $object, $_SERVER["PHP_SELF"].'?socid='.$object->id); } - if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB)) - { + if (!empty($conf->global->MAIN_REPEATTASKONEACHTAB)) { print load_fiche_titre($langs->trans("ActionsOnCompany"), '', ''); // List of todo actions diff --git a/htdocs/fourn/class/api_supplier_invoices.class.php b/htdocs/fourn/class/api_supplier_invoices.class.php index 247434be7a8..953092120e4 100644 --- a/htdocs/fourn/class/api_supplier_invoices.class.php +++ b/htdocs/fourn/class/api_supplier_invoices.class.php @@ -34,7 +34,7 @@ class SupplierInvoices extends DolibarrApi * * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'socid', ); @@ -109,20 +109,32 @@ class SupplierInvoices extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) - if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; + if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; + } $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as t"; // We need this table joined to the select in order to filter by sale - if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ' WHERE t.entity IN ('.getEntity('supplier_invoice').')'; - if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if (!DolibarrApiAccess::$user->rights->societe->client->voir || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Filter by status if ($status == 'draft') { @@ -142,10 +154,8 @@ class SupplierInvoices extends DolibarrApi $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -154,8 +164,7 @@ class SupplierInvoices extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -168,8 +177,7 @@ class SupplierInvoices extends DolibarrApi $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $invoice_static = new FactureFournisseur($this->db); if ($invoice_static->fetch($obj->rowid)) { @@ -244,12 +252,15 @@ class SupplierInvoices extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->invoice->$field = $value; } - if ($this->invoice->update($id, DolibarrApiAccess::$user)) + if ($this->invoice->update($id, DolibarrApiAccess::$user)) { return $this->get($id); + } return false; } @@ -279,8 +290,7 @@ class SupplierInvoices extends DolibarrApi throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login); } - if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) - { + if ($this->invoice->delete(DolibarrApiAccess::$user) < 0) { throw new RestException(500); } @@ -459,16 +469,14 @@ class SupplierInvoices extends DolibarrApi $paiement->note_public = $comment; $paiement_id = $paiement->create(DolibarrApiAccess::$user, ($closepaidinvoices == 'yes' ? 1 : 0)); // This include closing invoices - if ($paiement_id < 0) - { + if ($paiement_id < 0) { $this->db->rollback(); throw new RestException(400, 'Payment error : '.$paiement->error); } if (!empty($conf->banque->enabled)) { $result = $paiement->addPaymentToBank(DolibarrApiAccess::$user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, $chqemetteur, $chqbank); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); throw new RestException(400, 'Add payment to bank error : '.$paiement->error); } @@ -706,8 +714,9 @@ class SupplierInvoices extends DolibarrApi { $invoice = array(); foreach (SupplierInvoices::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $invoice[$field] = $data[$field]; } return $invoice; diff --git a/htdocs/fourn/class/api_supplier_orders.class.php b/htdocs/fourn/class/api_supplier_orders.class.php index 254e577f2f2..895902b13b2 100644 --- a/htdocs/fourn/class/api_supplier_orders.class.php +++ b/htdocs/fourn/class/api_supplier_orders.class.php @@ -32,7 +32,7 @@ class SupplierOrders extends DolibarrApi * * @var array $FIELDS Mandatory fields, checked when create and update object */ - static $FIELDS = array( + public static $FIELDS = array( 'socid' ); @@ -108,41 +108,70 @@ class SupplierOrders extends DolibarrApi // If the internal user must only see his customers, force searching by him $search_sale = 0; - if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) $search_sale = DolibarrApiAccess::$user->id; + if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) { + $search_sale = DolibarrApiAccess::$user->id; + } $sql = "SELECT t.rowid"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", sc.fk_soc, sc.fk_user"; // We need these fields in order to filter by sale (including the case where the user can only see his prospects) + } $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as t"; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; // We need this table joined to the select in order to filter by sale + } - if (!empty($product_ids)) $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product + if (!empty($product_ids)) { + $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseurdet as cd"; // We need this table joined to the select in order to filter by product + } $sql .= ' WHERE t.entity IN ('.getEntity('supplier_order').')'; - if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) $sql .= " AND t.fk_soc = sc.fk_soc"; - if (!empty($product_ids)) $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$product_ids.")"; - if ($socids) $sql .= " AND t.fk_soc IN (".$socids.")"; - if ($search_sale > 0) $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) { + $sql .= " AND t.fk_soc = sc.fk_soc"; + } + if (!empty($product_ids)) { + $sql .= " AND cd.fk_commande = t.rowid AND cd.fk_product IN (".$product_ids.")"; + } + if ($socids) { + $sql .= " AND t.fk_soc IN (".$socids.")"; + } + if ($search_sale > 0) { + $sql .= " AND t.rowid = sc.fk_soc"; // Join for the needed table to filter by sale + } // Filter by status - if ($status == 'draft') $sql .= " AND t.fk_statut IN (0)"; - if ($status == 'validated') $sql .= " AND t.fk_statut IN (1)"; - if ($status == 'approved') $sql .= " AND t.fk_statut IN (2)"; - if ($status == 'running') $sql .= " AND t.fk_statut IN (3)"; - if ($status == 'received_start') $sql .= " AND t.fk_statut IN (4)"; - if ($status == 'received_end') $sql .= " AND t.fk_statut IN (5)"; - if ($status == 'cancelled') $sql .= " AND t.fk_statut IN (6,7)"; - if ($status == 'refused') $sql .= " AND t.fk_statut IN (9)"; + if ($status == 'draft') { + $sql .= " AND t.fk_statut IN (0)"; + } + if ($status == 'validated') { + $sql .= " AND t.fk_statut IN (1)"; + } + if ($status == 'approved') { + $sql .= " AND t.fk_statut IN (2)"; + } + if ($status == 'running') { + $sql .= " AND t.fk_statut IN (3)"; + } + if ($status == 'received_start') { + $sql .= " AND t.fk_statut IN (4)"; + } + if ($status == 'received_end') { + $sql .= " AND t.fk_statut IN (5)"; + } + if ($status == 'cancelled') { + $sql .= " AND t.fk_statut IN (6,7)"; + } + if ($status == 'refused') { + $sql .= " AND t.fk_statut IN (9)"; + } // Insert sale filter - if ($search_sale > 0) - { + if ($search_sale > 0) { $sql .= " AND sc.fk_user = ".$search_sale; } // Add sql filters - if ($sqlfilters) - { - if (!DolibarrApi::_checkFilters($sqlfilters)) - { + if ($sqlfilters) { + if (!DolibarrApi::_checkFilters($sqlfilters)) { throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters); } $regexstring = '\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)'; @@ -151,8 +180,7 @@ class SupplierOrders extends DolibarrApi $sql .= $this->db->order($sortfield, $sortorder); if ($limit) { - if ($page < 0) - { + if ($page < 0) { $page = 0; } $offset = $limit * $page; @@ -161,13 +189,11 @@ class SupplierOrders extends DolibarrApi } $result = $this->db->query($sql); - if ($result) - { + if ($result) { $i = 0; $num = $this->db->num_rows($result); $min = min($num, ($limit <= 0 ? $num : $limit)); - while ($i < $min) - { + while ($i < $min) { $obj = $this->db->fetch_object($result); $order_static = new CommandeFournisseur($this->db); if ($order_static->fetch($obj->rowid)) { @@ -207,13 +233,13 @@ class SupplierOrders extends DolibarrApi $this->order->date = dol_now(); } /* We keep lines as an array - if (isset($request_data["lines"])) { - $lines = array(); - foreach ($request_data["lines"] as $line) { - array_push($lines, (object) $line); - } - $this->order->lines = $lines; - }*/ + if (isset($request_data["lines"])) { + $lines = array(); + foreach ($request_data["lines"] as $line) { + array_push($lines, (object) $line); + } + $this->order->lines = $lines; + }*/ if ($this->order->create(DolibarrApiAccess::$user) < 0) { throw new RestException(500, "Error creating order", array_merge(array($this->order->error), $this->order->errors)); @@ -244,12 +270,15 @@ class SupplierOrders extends DolibarrApi } foreach ($request_data as $field => $value) { - if ($field == 'id') continue; + if ($field == 'id') { + continue; + } $this->order->$field = $value; } - if ($this->order->update($id, DolibarrApiAccess::$user)) + if ($this->order->update($id, DolibarrApiAccess::$user)) { return $this->get($id); + } return false; } @@ -368,8 +397,9 @@ class SupplierOrders extends DolibarrApi { $order = array(); foreach (SupplierOrders::$FIELDS as $field) { - if (!isset($data[$field])) + if (!isset($data[$field])) { throw new RestException(400, "$field field missing"); + } $order[$field] = $data[$field]; } return $order; diff --git a/htdocs/fourn/class/fournisseur.class.php b/htdocs/fourn/class/fournisseur.class.php index 4ca073a38c7..57f6fa52d26 100644 --- a/htdocs/fourn/class/fournisseur.class.php +++ b/htdocs/fourn/class/fournisseur.class.php @@ -62,12 +62,10 @@ class Fournisseur extends Societe $sql .= " WHERE cf.fk_soc = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num == 1) - { + if ($num == 1) { $row = $this->db->fetch_row($resql); $this->single_open_commande = $row[0]; @@ -91,8 +89,7 @@ class Fournisseur extends Societe $sql .= " AND pfp.fk_soc = ".$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); return $obj->nb; } else { @@ -116,8 +113,7 @@ class Fournisseur extends Societe $sql = "SELECT count(s.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -126,10 +122,8 @@ class Fournisseur extends Societe $sql .= " AND s.entity IN (".getEntity('societe').")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["suppliers"] = $obj->nb; } $this->db->free($resql); @@ -158,8 +152,7 @@ class Fournisseur extends Societe dol_syslog("Fournisseur::CreateCategory", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { dol_syslog("Fournisseur::CreateCategory : Success"); return 0; } else { @@ -185,17 +178,19 @@ class Fournisseur extends Societe $sql = "SELECT s.rowid, s.nom as name"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE s.fournisseur = 1"; $sql .= " AND s.entity IN (".getEntity('societe').")"; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $arr[$obj->rowid] = $obj->name; } } else { diff --git a/htdocs/fourn/class/fournisseur.commande.class.php b/htdocs/fourn/class/fournisseur.commande.class.php index 52121d8c83d..d4e92fd8bf4 100644 --- a/htdocs/fourn/class/fournisseur.commande.class.php +++ b/htdocs/fourn/class/fournisseur.commande.class.php @@ -34,7 +34,9 @@ include_once DOL_DOCUMENT_ROOT.'/core/class/commonorder.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -if (!empty($conf->productbatch->enabled)) require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; +if (!empty($conf->productbatch->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php'; +} require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; /** @@ -303,7 +305,9 @@ class CommandeFournisseur extends CommonOrder global $conf; // Check parameters - if (empty($id) && empty($ref)) return -1; + if (empty($id) && empty($ref)) { + return -1; + } $sql = "SELECT c.rowid, c.entity, c.ref, ref_supplier, c.fk_soc, c.fk_statut, c.amount_ht, c.total_ht, c.total_ttc, c.total_tva,"; $sql .= " c.localtax1, c.localtax2, "; @@ -324,18 +328,21 @@ class CommandeFournisseur extends CommonOrder $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_input_method as cm ON cm.rowid = c.fk_input_method"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON c.fk_incoterms = i.rowid'; - if (empty($id)) $sql .= " WHERE c.entity IN (".getEntity('supplier_order').")"; - else $sql .= " WHERE c.rowid=".$id; + if (empty($id)) { + $sql .= " WHERE c.entity IN (".getEntity('supplier_order').")"; + } else { + $sql .= " WHERE c.rowid=".$id; + } - if ($ref) $sql .= " AND c.ref='".$this->db->escape($ref)."'"; + if ($ref) { + $sql .= " AND c.ref='".$this->db->escape($ref)."'"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if (!$obj) - { + if (!$obj) { $this->error = 'Bill with id '.$id.' not found'; dol_syslog(get_class($this).'::fetch '.$this->error); return 0; @@ -409,14 +416,15 @@ class CommandeFournisseur extends CommonOrder // fetch optionals attributes and labels $this->fetch_optionals(); - if ($this->statut == 0) $this->brouillon = 1; + if ($this->statut == 0) { + $this->brouillon = 1; + } /* - * Lines - */ + * Lines + */ $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { return -1; } else { return 1; @@ -449,26 +457,28 @@ class CommandeFournisseur extends CommonOrder $sql .= " l.fk_unit,"; $sql .= " l.date_start, l.date_end,"; $sql .= ' l.fk_multicurrency, l.multicurrency_code, l.multicurrency_subprice, l.multicurrency_total_ht, l.multicurrency_total_tva, l.multicurrency_total_ttc'; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $sql .= ", pfp.rowid as fk_pfp, pfp.packaging"; + } $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as l"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON l.fk_product = p.rowid'; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON l.fk_product = pfp.fk_product and l.ref = pfp.ref_fourn"; + } $sql .= " WHERE l.fk_commande = ".$this->id; - if ($only_product) $sql .= ' AND p.fk_product_type = 0'; + if ($only_product) { + $sql .= ' AND p.fk_product_type = 0'; + } $sql .= " ORDER BY l.rang, l.rowid"; //print $sql; dol_syslog(get_class($this)."::fetch get lines", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($result); $line = new CommandeFournisseurLigne($this->db); @@ -505,8 +515,7 @@ class CommandeFournisseur extends CommonOrder $line->ref_fourn = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since $line->ref_supplier = $objp->ref_supplier; // The supplier ref of price when product was added. May have change since - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) - { + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $line->fk_fournprice = $objp->fk_pfp; $line->packaging = $objp->packaging; } @@ -563,8 +572,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::valid"); $result = 0; if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->commande->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_order_advance->validate))) { $this->db->begin(); // Definition of supplier order numbering model name @@ -572,8 +580,7 @@ class CommandeFournisseur extends CommonOrder $soc->fetch($this->fourn_id); // Check if object has a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life - { + if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($soc); } else { $num = $this->ref; @@ -589,49 +596,46 @@ class CommandeFournisseur extends CommonOrder $sql .= " AND fk_statut = ".self::STATUS_DRAFT; $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($this->db); $error++; } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/commande/".$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/commande/".$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->fournisseur->commande->dir_output.'/'.$oldref; $dirdest = $conf->fournisseur->commande->dir_output.'/'.$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::valid rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->fournisseur->commande->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -643,15 +647,13 @@ class CommandeFournisseur extends CommonOrder } } - if (!$error) - { + if (!$error) { $result = 1; $this->statut = self::STATUS_VALIDATED; $this->ref = $num; } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -696,8 +698,11 @@ class CommandeFournisseur extends CommonOrder $this->statuts[0] = 'StatusSupplierOrderDraft'; $this->statuts[1] = 'StatusSupplierOrderValidated'; $this->statuts[2] = 'StatusSupplierOrderApproved'; - if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $this->statuts[3] = 'StatusSupplierOrderOnProcess'; - else $this->statuts[3] = 'StatusSupplierOrderOnProcessWithValidation'; + if (empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { + $this->statuts[3] = 'StatusSupplierOrderOnProcess'; + } else { + $this->statuts[3] = 'StatusSupplierOrderOnProcessWithValidation'; + } $this->statuts[4] = 'StatusSupplierOrderReceivedPartially'; $this->statuts[5] = 'StatusSupplierOrderReceivedAll'; $this->statuts[6] = 'StatusSupplierOrderCanceled'; // Approved->Canceled @@ -737,7 +742,9 @@ class CommandeFournisseur extends CommonOrder if ($billed) { $billedtext = ' - '.$langs->trans("Billed"); } - if ($status == 5 && $billed) $statusClass = 'status6'; + if ($status == 5 && $billed) { + $statusClass = 'status6'; + } $statusLong = $langs->transnoentitiesnoconv($this->statuts[$status]).$billedtext; $statusShort = $langs->transnoentitiesnoconv($this->statutshort[$status]); @@ -792,19 +799,20 @@ class CommandeFournisseur extends CommonOrder $picto = 'order'; $url = DOL_URL_ROOT.'/fourn/commande/card.php?id='.$this->id; - if ($option !== 'nolink') - { + if ($option !== 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowOrder"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -817,15 +825,17 @@ class CommandeFournisseur extends CommonOrder $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; - if ($addlinktonotes) - { + if ($addlinktonotes) { $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { + if ($txttoshow) { $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1); $result .= ' <span class="note inline-block">'; $result .= '<a href="'.DOL_URL_ROOT.'/fourn/commande/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">'; @@ -853,8 +863,7 @@ class CommandeFournisseur extends CommonOrder global $db, $langs, $conf; $langs->load("orders"); - if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER)) - { + if (!empty($conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER)) { $mybool = false; $file = $conf->global->COMMANDE_SUPPLIER_ADDON_NUMBER.'.php'; @@ -878,8 +887,7 @@ class CommandeFournisseur extends CommonOrder $obj = new $classname(); $numref = $obj->getNextValue($soc, $this); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -900,8 +908,7 @@ class CommandeFournisseur extends CommonOrder { $error = 0; - if ($this->billed) - { + if ($this->billed) { return 0; } @@ -910,18 +917,17 @@ class CommandeFournisseur extends CommonOrder $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur SET billed = 1'; $sql .= ' WHERE rowid = '.$this->id.' AND fk_statut > '.self::STATUS_DRAFT; - if ($this->db->query($sql)) - { - if (!$error) - { + if ($this->db->query($sql)) { + if (!$error) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_CLASSIFY_BILLED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->billed = 1; $this->db->commit(); @@ -955,8 +961,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::approve"); - if ($user->rights->fournisseur->commande->approuver) - { + if ($user->rights->fournisseur->commande->approuver) { $now = dol_now(); $this->db->begin(); @@ -966,8 +971,7 @@ class CommandeFournisseur extends CommonOrder $soc->fetch($this->fourn_id); // Check if object has a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life - { + if (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($soc); } else { $num = $this->ref; @@ -980,14 +984,11 @@ class CommandeFournisseur extends CommonOrder $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; $sql .= " SET ref='".$this->db->escape($num)."',"; - if (empty($secondlevel)) // standard or first level approval - { + if (empty($secondlevel)) { // standard or first level approval $sql .= " date_approve='".$this->db->idate($now)."',"; $sql .= " fk_user_approve = ".$user->id; - if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) - { - if (empty($this->user_approve_id2)) - { + if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $conf->global->MAIN_FEATURES_LEVEL > 0 && $this->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) { + if (empty($this->user_approve_id2)) { $movetoapprovestatus = false; // second level approval not done $comment = ' (first level)'; } @@ -996,67 +997,72 @@ class CommandeFournisseur extends CommonOrder { $sql .= " date_approve2='".$this->db->idate($now)."',"; $sql .= " fk_user_approve2 = ".$user->id; - if (empty($this->user_approve_id)) $movetoapprovestatus = false; // first level approval not done + if (empty($this->user_approve_id)) { + $movetoapprovestatus = false; // first level approval not done + } $comment = ' (second level)'; } // If double approval is required and first approval, we keep status to 1 = validated - if ($movetoapprovestatus) $sql .= ", fk_statut = ".self::STATUS_ACCEPTED; - else $sql .= ", fk_statut = ".self::STATUS_VALIDATED; + if ($movetoapprovestatus) { + $sql .= ", fk_statut = ".self::STATUS_ACCEPTED; + } else { + $sql .= ", fk_statut = ".self::STATUS_VALIDATED; + } $sql .= " WHERE rowid = ".$this->id; $sql .= " AND fk_statut = ".self::STATUS_VALIDATED; - if ($this->db->query($sql)) - { - if (!empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT)) - { + if ($this->db->query($sql)) { + if (!empty($conf->global->SUPPLIER_ORDER_AUTOADD_USER_CONTACT)) { $result = $this->add_contact($user->id, 'SALESREPFOLL', 'internal', 1); - if ($result < 0 && $result != -2) // -2 means already exists - { + if ($result < 0 && $result != -2) { // -2 means already exists $error++; } } // If stock is incremented on validate order, we must increment it - if (!$error && $movetoapprovestatus && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) - { + if (!$error && $movetoapprovestatus && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $cpt = count($this->lines); - for ($i = 0; $i < $cpt; $i++) - { + for ($i = 0; $i < $cpt; $i++) { // Product with reference - if ($this->lines[$i]->fk_product > 0) - { + if ($this->lines[$i]->fk_product > 0) { $this->line = $this->lines[$i]; $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We decrement stock of product (and sub-products) $up_ht_disc = $this->lines[$i]->subprice; - if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU'); + if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) { + $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU'); + } $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("OrderApprovedInDolibarr", $this->ref)); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } unset($this->line); } } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_APPROVE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->ref = $this->newref; - if ($movetoapprovestatus) $this->statut = self::STATUS_ACCEPTED; - else $this->statut = self::STATUS_VALIDATED; - if (empty($secondlevel)) // standard or first level approval - { + if ($movetoapprovestatus) { + $this->statut = self::STATUS_ACCEPTED; + } else { + $this->statut = self::STATUS_VALIDATED; + } + if (empty($secondlevel)) { // standard or first level approval $this->date_approve = $now; $this->user_approve_id = $user->id; } else // request a second level approval @@ -1096,26 +1102,24 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::refuse"); $result = 0; - if ($user->rights->fournisseur->commande->approuver) - { + if ($user->rights->fournisseur->commande->approuver) { $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".self::STATUS_REFUSED; $sql .= " WHERE rowid = ".$this->id; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $result = 0; - if ($error == 0) - { + if ($error == 0) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_REFUSE', $user); - if ($result < 0) - { + if ($result < 0) { $error++; $this->db->rollback(); - } else $this->db->commit(); + } else { + $this->db->commit(); + } // End call triggers } } else { @@ -1148,8 +1152,7 @@ class CommandeFournisseur extends CommonOrder //dol_syslog("CommandeFournisseur::Cancel"); $result = 0; - if ($user->rights->fournisseur->commande->commander) - { + if ($user->rights->fournisseur->commande->commander) { $statut = self::STATUS_CANCELED; $this->db->begin(); @@ -1157,17 +1160,17 @@ class CommandeFournisseur extends CommonOrder $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur SET fk_statut = ".$statut; $sql .= " WHERE rowid = ".$this->id; dol_syslog(get_class($this)."::cancel", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $result = 0; // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_CANCEL', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if ($error == 0) - { + if ($error == 0) { $this->db->commit(); return 1; } else { @@ -1200,12 +1203,13 @@ class CommandeFournisseur extends CommonOrder global $langs; dol_syslog(get_class($this)."::commande"); $error = 0; - if ($user->rights->fournisseur->commande->commander) - { + if ($user->rights->fournisseur->commande->commander) { $this->db->begin(); $newnoteprivate = $this->note_private; - if ($comment) $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment); + if ($comment) { + $newnoteprivate = dol_concatdesc($newnoteprivate, $langs->trans("Comment").': '.$comment); + } $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; $sql .= " SET fk_statut=".self::STATUS_ORDERSENT.", fk_input_method=".$methode.", date_commande='".$this->db->idate($date)."', "; @@ -1213,8 +1217,7 @@ class CommandeFournisseur extends CommonOrder $sql .= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::commande", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->statut = self::STATUS_ORDERSENT; $this->methode_commande_id = $methode; $this->date_commande = $date; @@ -1222,7 +1225,9 @@ class CommandeFournisseur extends CommonOrder // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_SUBMIT', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -1230,8 +1235,7 @@ class CommandeFournisseur extends CommonOrder $this->errors[] = $this->db->lasterror(); } - if (!$error) - { + if (!$error) { $this->db->commit(); } else { $this->db->rollback(); @@ -1264,17 +1268,23 @@ class CommandeFournisseur extends CommonOrder // set tmp vars $date = ($this->date_commande ? $this->date_commande : $this->date); // in case of date is set - if (empty($date)) $date = $now; + if (empty($date)) { + $date = $now; + } $delivery_date = empty($this->delivery_date) ? $this->date_livraison : $this->delivery_date; // Clean parameters - if (empty($this->source)) $this->source = 0; + if (empty($this->source)) { + $this->source = 0; + } // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate) - if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date); - else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $date); + } else { + $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; @@ -1330,16 +1340,14 @@ class CommandeFournisseur extends CommonOrder $sql .= ")"; dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."commande_fournisseur"); if ($this->id) { $num = count($this->lines); // insert products details into database - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $this->special_code = $this->lines[$i]->special_code; // TODO : remove this in 9.0 and add special_code param to addline() // This include test on qty if option SUPPLIER_ORDER_WITH_NOPRICEDEFINED is not set @@ -1364,8 +1372,7 @@ class CommandeFournisseur extends CommonOrder $this->lines[$i]->array_options, $this->lines[$i]->fk_unit ); - if ($result < 0) - { + if ($result < 0) { dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING); // do not use dol_print_error here as it may be a functionnal error $this->db->rollback(); return -1; @@ -1376,30 +1383,22 @@ class CommandeFournisseur extends CommonOrder $sql .= " SET ref='(PROV".$this->id.")'"; $sql .= " WHERE rowid=".$this->id; dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { // Add link with price request and supplier order - if ($this->id) - { + if ($this->id) { $this->ref = "(PROV".$this->id.")"; - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { dol_print_error($this->db); $error++; } @@ -1408,8 +1407,7 @@ class CommandeFournisseur extends CommonOrder { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { dol_print_error($this->db); $error++; } @@ -1418,18 +1416,17 @@ class CommandeFournisseur extends CommonOrder } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_CREATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -1467,19 +1464,18 @@ class CommandeFournisseur extends CommonOrder $this->db->begin(); // get extrafields so they will be clone - foreach ($this->lines as $line) + foreach ($this->lines as $line) { $line->fetch_optionals(); + } // Load source object $objFrom = clone $this; // Change socid if needed - if (!empty($socid) && $socid != $this->socid) - { + if (!empty($socid) && $socid != $this->socid) { $objsoc = new Societe($this->db); - if ($objsoc->fetch($socid) > 0) - { + if ($objsoc->fetch($socid) > 0) { $this->socid = $objsoc->id; $this->cond_reglement_id = (!empty($objsoc->cond_reglement_id) ? $objsoc->cond_reglement_id : 0); $this->mode_reglement_id = (!empty($objsoc->mode_reglement_id) ? $objsoc->mode_reglement_id : 0); @@ -1507,25 +1503,26 @@ class CommandeFournisseur extends CommonOrder // Create clone $this->context['createfromclone'] = 'createfromclone'; $result = $this->create($user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Hook of thirdparty module - if (is_object($hookmanager)) - { + if (is_object($hookmanager)) { $parameters = array('objFrom'=>$objFrom); $action = ''; $reshook = $hookmanager->executeHooks('createFrom', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks - if ($reshook < 0) $error++; + if ($reshook < 0) { + $error++; + } } } unset($this->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -1568,17 +1565,28 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::addline $desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $fk_prod_fourn_price, $ref_supplier, $remise_percent, $price_base_type, $pu_ttc, $type, $info_bits, $notrigger, $date_start, $date_end, $fk_unit, $pu_ht_devise, $origin, $origin_id"); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; // Clean parameters - if (empty($qty)) $qty = 0; - if (!$info_bits) $info_bits = 0; - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; - if (empty($remise_percent)) $remise_percent = 0; + if (empty($qty)) { + $qty = 0; + } + if (!$info_bits) { + $info_bits = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } + if (empty($remise_percent)) { + $remise_percent = 0; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -1590,8 +1598,7 @@ class CommandeFournisseur extends CommonOrder } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); - if ($price_base_type == 'HT') - { + if ($price_base_type == 'HT') { $pu = $pu_ht; } else { $pu = $pu_ttc; @@ -1599,12 +1606,13 @@ class CommandeFournisseur extends CommonOrder $desc = trim($desc); // Check parameters - if ($qty < 0 && !$fk_product) - { + if ($qty < 0 && !$fk_product) { $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Product")); return -1; } - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); $this->error = $langs->trans('ErrorStartDateGreaterEnd'); @@ -1632,15 +1640,15 @@ class CommandeFournisseur extends CommonOrder // If supplier order created from customer order, we take best supplier price // If $pu (defined previously from pu_ht or pu_ttc) is not defined at all, we also take the best supplier price - if ($result > 0 && ($origin == 'commande' || $pu === '')) - { + if ($result > 0 && ($origin == 'commande' || $pu === '')) { $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice // is remise percent not keyed but present for the product we add it - if ($remise_percent == 0 && $prod->remise_percent != 0) $remise_percent = $prod->remise_percent; + if ($remise_percent == 0 && $prod->remise_percent != 0) { + $remise_percent = $prod->remise_percent; + } } - if ($result == 0) // If result == 0, we failed to found the supplier reference price - { + if ($result == 0) { // If result == 0, we failed to found the supplier reference price $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); @@ -1649,16 +1657,14 @@ class CommandeFournisseur extends CommonOrder //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price return -1; } - if ($result == -1) - { + if ($result == -1) { $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG); return -1; } - if ($result < -1) - { + if ($result < -1) { $this->error = $prod->error; $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); @@ -1695,8 +1701,7 @@ class CommandeFournisseur extends CommonOrder // Clean vat code $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -1783,15 +1788,15 @@ class CommandeFournisseur extends CommonOrder } $result = $this->line->insert($notrigger); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour informations denormalisees au niveau de la commande meme $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // This method is designed to add line from user input so total calculation must be done using 'auto' mode. - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->line->id; } else { @@ -1833,24 +1838,23 @@ class CommandeFournisseur extends CommonOrder require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; // Check parameters (if test are wrong here, there is bug into caller) - if ($entrepot <= 0) - { + if ($entrepot <= 0) { $this->error = 'ErrorBadValueForParameterWarehouse'; return -1; } - if ($qty == 0) - { + if ($qty == 0) { $this->error = 'ErrorBadValueForParameterQty'; return -1; } $dispatchstatus = 1; - if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on + if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { + $dispatchstatus = 0; // Setting dispatch status (a validation step after receiving products) will be done manually to 1 or 2 if this option is on + } $now = dol_now(); - if (($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY || $this->statut == self::STATUS_RECEIVED_COMPLETELY)) - { + if (($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY || $this->statut == self::STATUS_RECEIVED_COMPLETELY)) { $this->db->begin(); $sql = "INSERT INTO ".MAIN_DB_PREFIX."commande_fournisseur_dispatch"; @@ -1861,15 +1865,12 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::dispatchProduct", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { + if ($resql) { + if (!$notrigger) { global $conf, $langs, $user; // Call trigger $result = $this->call_trigger('LINEORDER_SUPPLIER_DISPATCH', $user); - if ($result < 0) - { + if ($result < 0) { $error++; } // End call triggers @@ -1880,16 +1881,13 @@ class CommandeFournisseur extends CommonOrder } // If module stock is enabled and the stock increase is done on purchase order dispatching - if (!$error && $entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) - { + if (!$error && $entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { $mouv = new MouvementStock($this->db); - if ($product > 0) - { + if ($product > 0) { // $price should take into account discount (except if option STOCK_EXCLUDE_DISCOUNT_FOR_PMP is on) $mouv->origin = &$this; $result = $mouv->reception($user, $product, $entrepot, $qty, $price, $comment, $eatby, $sellby, $batch); - if ($result < 0) - { + if ($result < 0) { $this->error = $mouv->error; $this->errors = $mouv->errors; dol_syslog(get_class($this)."::dispatchProduct ".$this->error." ".join(',', $this->errors), LOG_ERR); @@ -1898,8 +1896,7 @@ class CommandeFournisseur extends CommonOrder } } - if ($error == 0) - { + if ($error == 0) { $this->db->commit(); return 1; } else { @@ -1921,17 +1918,14 @@ class CommandeFournisseur extends CommonOrder */ public function deleteline($idline, $notrigger = 0) { - if ($this->statut == 0) - { + if ($this->statut == 0) { $line = new CommandeFournisseurLigne($this->db); - if ($line->fetch($idline) <= 0) - { + if ($line->fetch($idline) <= 0) { return 0; } - if ($line->delete($notrigger) > 0) - { + if ($line->delete($notrigger) > 0) { $this->update_price(); return 1; } else { @@ -1960,12 +1954,10 @@ class CommandeFournisseur extends CommonOrder $this->db->begin(); - if (empty($notrigger)) - { + if (empty($notrigger)) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->errors[] = 'ErrorWhenRunningTrigger'; dol_syslog(get_class($this)."::delete ".$this->error, LOG_ERR); $this->db->rollback(); @@ -1978,8 +1970,7 @@ class CommandeFournisseur extends CommonOrder $ef = $main."_extrafields"; $sql = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_commande = ".$this->id.")"; dol_syslog(get_class($this)."::delete extrafields lines", LOG_DEBUG); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); $error++; @@ -1987,8 +1978,7 @@ class CommandeFournisseur extends CommonOrder $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseurdet WHERE fk_commande =".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if (!$this->db->query($sql)) - { + if (!$this->db->query($sql)) { $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); $error++; @@ -1996,10 +1986,8 @@ class CommandeFournisseur extends CommonOrder $sql = "DELETE FROM ".MAIN_DB_PREFIX."commande_fournisseur WHERE rowid =".$this->id; dol_syslog(get_class($this)."::delete", LOG_DEBUG); - if ($resql = $this->db->query($sql)) - { - if ($this->db->affected_rows($resql) < 1) - { + if ($resql = $this->db->query($sql)) { + if ($this->db->affected_rows($resql) < 1) { $this->error = $this->db->lasterror(); $this->errors[] = $this->db->lasterror(); $error++; @@ -2011,11 +1999,9 @@ class CommandeFournisseur extends CommonOrder } // Remove extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->error = 'FailToDeleteExtraFields'; $this->errors[] = 'FailToDeleteExtraFields'; $error++; @@ -2031,31 +2017,25 @@ class CommandeFournisseur extends CommonOrder $error++; } - if (!$error) - { + if (!$error) { // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive $this->deleteEcmFiles(); // We remove directory $ref = dol_sanitizeFileName($this->ref); - if ($conf->fournisseur->commande->dir_output) - { + if ($conf->fournisseur->commande->dir_output) { $dir = $conf->fournisseur->commande->dir_output."/".$ref; $file = $dir."/".$ref.".pdf"; - if (file_exists($file)) - { - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { + if (file_exists($file)) { + if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers $this->error = 'ErrorFailToDeleteFile'; $this->errors[] = 'ErrorFailToDeleteFile'; $error++; } } - if (file_exists($dir)) - { + if (file_exists($dir)) { $res = @dol_delete_dir_recursive($dir); - if (!$res) - { + if (!$res) { $this->error = 'ErrorFailToDeleteDir'; $this->errors[] = 'ErrorFailToDeleteDir'; $error++; @@ -2064,8 +2044,7 @@ class CommandeFournisseur extends CommonOrder } } - if (!$error) - { + if (!$error) { dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG); $this->db->commit(); return 1; @@ -2090,13 +2069,11 @@ class CommandeFournisseur extends CommonOrder $sql .= " WHERE active = 1"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $this->db->num_rows($resql); $this->methodes_commande = array(); - while ($i < $num) - { + while ($i < $num) { $row = $this->db->fetch_row($resql); $this->methodes_commande[$row[0]] = $row[1]; @@ -2130,20 +2107,19 @@ class CommandeFournisseur extends CommonOrder $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid"; $sql .= " WHERE cfd.fk_commande = ".$this->id; $sql .= " AND cfd.fk_product = p.rowid"; - if ($status >= 0) $sql .= " AND cfd.status = ".$status; + if ($status >= 0) { + $sql .= " AND cfd.status = ".$status; + } $sql .= " ORDER BY cfd.rowid ASC"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); $i = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $this->db->fetch_object($resql); - if ($objp) - { + if ($objp) { $ret[] = array( 'id' => $objp->dispatchedlineid, 'productid' => $objp->fk_product, @@ -2154,7 +2130,9 @@ class CommandeFournisseur extends CommonOrder $i++; } - } else dol_print_error($this->db, 'Failed to execute request to get dispatched lines'); + } else { + dol_print_error($this->db, 'Failed to execute request to get dispatched lines'); + } return $ret; } @@ -2180,39 +2158,37 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::Livraison"); - if ($user->rights->fournisseur->commande->receptionner) - { + if ($user->rights->fournisseur->commande->receptionner) { // Define the new status - if ($type == 'par') $statut = self::STATUS_RECEIVED_PARTIALLY; - elseif ($type == 'tot') $statut = self::STATUS_RECEIVED_COMPLETELY; - elseif ($type == 'nev') $statut = self::STATUS_CANCELED_AFTER_ORDER; - elseif ($type == 'can') $statut = self::STATUS_CANCELED_AFTER_ORDER; - else { + if ($type == 'par') { + $statut = self::STATUS_RECEIVED_PARTIALLY; + } elseif ($type == 'tot') { + $statut = self::STATUS_RECEIVED_COMPLETELY; + } elseif ($type == 'nev') { + $statut = self::STATUS_CANCELED_AFTER_ORDER; + } elseif ($type == 'can') { + $statut = self::STATUS_CANCELED_AFTER_ORDER; + } else { $error++; dol_syslog(get_class($this)."::Livraison Error -2", LOG_ERR); return -2; } // Some checks to accept the record - if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) - { + if (!empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS)) { // If option SUPPLIER_ORDER_USE_DISPATCH_STATUS is on, we check all reception are approved to allow status "total/done" - if (!$error && ($type == 'tot')) - { + if (!$error && ($type == 'tot')) { $dispatchedlinearray = $this->getDispachedLines(0); - if (count($dispatchedlinearray) > 0) - { + if (count($dispatchedlinearray) > 0) { $result = -1; $error++; $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionToApprove'; dol_syslog('ErrorCantSetReceptionToTotalDoneWithReceptionToApprove', LOG_DEBUG); } } - if (!$error && !empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot')) // Accept to move to reception done, only if status of all line are ok (refuse denied) - { + if (!$error && !empty($conf->global->SUPPLIER_ORDER_USE_DISPATCH_STATUS_NEED_APPROVE) && ($type == 'tot')) { // Accept to move to reception done, only if status of all line are ok (refuse denied) $dispatcheddenied = $this->getDispachedLines(2); - if (count($dispatchedlinearray) > 0) - { + if (count($dispatchedlinearray) > 0) { $result = -1; $error++; $this->errors[] = 'ErrorCantSetReceptionToTotalDoneWithReceptionDenied'; @@ -2223,8 +2199,7 @@ class CommandeFournisseur extends CommonOrder // TODO LDR01 Add a control test to accept only if ALL predefined products are received (same qty). - if (empty($error)) - { + if (empty($error)) { $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."commande_fournisseur"; @@ -2234,8 +2209,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::Livraison", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $result = 1; $old_statut = $this->statut; $this->statut = $statut; @@ -2243,11 +2217,12 @@ class CommandeFournisseur extends CommonOrder // Call trigger $result_trigger = $this->call_trigger('ORDER_SUPPLIER_RECEIVE', $user); - if ($result_trigger < 0) $error++; + if ($result_trigger < 0) { + $error++; + } // End call triggers - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); } else { $this->statut = $old_statut; @@ -2296,8 +2271,7 @@ class CommandeFournisseur extends CommonOrder */ public function setDeliveryDate($user, $delivery_date, $notrigger = 0) { - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { $error = 0; $this->db->begin(); @@ -2308,34 +2282,31 @@ class CommandeFournisseur extends CommonOrder dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->date_livraison = $delivery_date; $this->delivery_date = $delivery_date; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2359,8 +2330,7 @@ class CommandeFournisseur extends CommonOrder public function set_id_projet($user, $id_projet, $notrigger = 0) { // phpcs:enable - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { $error = 0; $this->db->begin(); @@ -2371,34 +2341,31 @@ class CommandeFournisseur extends CommonOrder dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->errors[] = $this->db->error(); $error++; } - if (!$error) - { + if (!$error) { $this->oldcopy = clone $this; $this->fk_projet = $id_projet; $this->fk_project = $id_projet; } - if (!$notrigger && empty($error)) - { + if (!$notrigger && empty($error)) { // Call trigger $result = $this->call_trigger('ORDER_SUPPLIER_MODIFY', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__.' Error: '.$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -2428,13 +2395,11 @@ class CommandeFournisseur extends CommonOrder $this->lines = array(); $num = count($comclient->lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $prod = new Product($this->db); $label = ''; $ref = ''; - if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) - { + if ($prod->fetch($comclient->lines[$i]->fk_product) > 0) { $label = $prod->label; $ref = $prod->ref; } @@ -2445,8 +2410,7 @@ class CommandeFournisseur extends CommonOrder $sql .= ",".$comclient->lines[$i]->fk_product.", ".price2num($comclient->lines[$i]->price); $sql .= ", ".$comclient->lines[$i]->qty.", ".$comclient->lines[$i]->tva_tx.", ".$comclient->lines[$i]->localtax1_tx.", ".$comclient->lines[$i]->localtax2_tx.", ".$comclient->lines[$i]->remise_percent; $sql .= ", '".price2num($comclient->lines[$i]->subprice)."','0', '".$this->db->escape($ref)."');"; - if ($this->db->query($sql)) - { + if ($this->db->query($sql)) { $this->update_price(); } } @@ -2474,8 +2438,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::setStatus", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Trigger names for each status $triggerName = array(); $triggerName[0] = 'DRAFT'; @@ -2490,7 +2453,9 @@ class CommandeFournisseur extends CommonOrder // Call trigger $result = $this->call_trigger("ORDER_SUPPLIER_STATUS_".$triggerName[$status], $user); - if ($result < 0) { $error++; } + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -2498,8 +2463,7 @@ class CommandeFournisseur extends CommonOrder dol_syslog(get_class($this)."::setStatus ".$this->error); } - if (!$error) - { + if (!$error) { $this->statut = $status; $this->db->commit(); return 1; @@ -2540,30 +2504,47 @@ class CommandeFournisseur extends CommonOrder $error = 0; - if ($this->brouillon) - { + if ($this->brouillon) { // Clean parameters - if (empty($qty)) $qty = 0; - if (empty($info_bits)) $info_bits = 0; - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; - if (empty($remise)) $remise = 0; - if (empty($remise_percent)) $remise_percent = 0; + if (empty($qty)) { + $qty = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } + if (empty($remise)) { + $remise = 0; + } + if (empty($remise_percent)) { + $remise_percent = 0; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); - if (!$qty) $qty = 1; + if (!$qty) { + $qty = 1; + } $pu = price2num($pu); $pu_ht_devise = price2num($pu_ht_devise); - if (!preg_match('/\((.*)\)/', $txtva)) { - $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' - } + if (!preg_match('/\((.*)\)/', $txtva)) { + $txtva = price2num($txtva); // $txtva can have format '5.0(XXX)' or '5' + } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); $this->error = $langs->trans('ErrorStartDateGreaterEnd'); @@ -2582,8 +2563,7 @@ class CommandeFournisseur extends CommonOrder // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -2621,14 +2601,11 @@ class CommandeFournisseur extends CommonOrder $this->line->desc = $desc; // redefine quantity according to packaging - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) - { - if ($qty < $this->line->packaging) - { + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + if ($qty < $this->line->packaging) { $qty = $this->line->packaging; } else { - if (($qty % $this->line->packaging) > 0) - { + if (($qty % $this->line->packaging) > 0) { $coeff = intval($qty / $this->line->packaging) + 1; $qty = $this->line->packaging * $coeff; setEventMessage($langs->trans('QtyRecalculatedWithPackaging'), 'mesgs'); @@ -2686,8 +2663,7 @@ class CommandeFournisseur extends CommonOrder // Mise a jour info denormalisees au niveau facture - if ($result >= 0) - { + if ($result >= 0) { $this->update_price('', 'auto'); $this->db->commit(); return $result; @@ -2730,8 +2706,7 @@ class CommandeFournisseur extends CommonOrder $sql .= $this->db->order("rowid", "ASC"); $sql .= $this->db->plimit(1); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $prodid = $obj->rowid; } @@ -2758,8 +2733,7 @@ class CommandeFournisseur extends CommonOrder // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new CommandeFournisseurLigne($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->qty = 1; @@ -2768,8 +2742,7 @@ class CommandeFournisseur extends CommonOrder $line->tva_tx = 19.6; $line->localtax1_tx = 0; $line->localtax2_tx = 0; - if ($xnbp == 2) - { + if ($xnbp == 2) { $line->total_ht = 50; $line->total_ttc = 59.8; $line->total_tva = 9.8; @@ -2806,17 +2779,25 @@ class CommandeFournisseur extends CommonOrder $sql .= ' WHERE c.rowid = '.$id; $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) $this->user_creation_id = $obj->fk_user_author; - if ($obj->fk_user_valid) $this->user_validation_id = $obj->fk_user_valid; - if ($obj->fk_user_modif) $this->user_modification_id = $obj->fk_user_modif; - if ($obj->fk_user_approve) $this->user_approve_id = $obj->fk_user_approve; - if ($obj->fk_user_approve2) $this->user_approve_id2 = $obj->fk_user_approve2; + if ($obj->fk_user_author) { + $this->user_creation_id = $obj->fk_user_author; + } + if ($obj->fk_user_valid) { + $this->user_validation_id = $obj->fk_user_valid; + } + if ($obj->fk_user_modif) { + $this->user_modification_id = $obj->fk_user_modif; + } + if ($obj->fk_user_approve) { + $this->user_approve_id = $obj->fk_user_approve; + } + if ($obj->fk_user_approve2) { + $this->user_approve_id2 = $obj->fk_user_approve2; + } $this->date_creation = $this->db->idate($obj->datec); $this->date_modification = $this->db->idate($obj->datem); @@ -2847,8 +2828,7 @@ class CommandeFournisseur extends CommonOrder $sql = "SELECT count(co.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as co"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON co.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -2856,10 +2836,8 @@ class CommandeFournisseur extends CommonOrder $sql .= " ".$clause." co.entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["supplier_orders"] = $obj->nb; } $this->db->free($resql); @@ -2888,8 +2866,7 @@ class CommandeFournisseur extends CommonOrder $sql = "SELECT c.rowid, c.date_creation as datec, c.date_commande, c.fk_statut, c.date_livraison as delivery_date"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON c.fk_soc = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = " AND"; @@ -2900,11 +2877,12 @@ class CommandeFournisseur extends CommonOrder } else { $sql .= " AND c.fk_statut IN (".self::STATUS_VALIDATED.", ".self::STATUS_ACCEPTED.")"; } - if ($user->socid) $sql .= " AND c.fk_soc = ".$user->socid; + if ($user->socid) { + $sql .= " AND c.fk_soc = ".$user->socid; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $commandestatic = new CommandeFournisseur($this->db); $response = new WorkboardResponse(); @@ -2920,8 +2898,7 @@ class CommandeFournisseur extends CommonOrder $response->url = DOL_URL_ROOT.'/fourn/commande/list.php?statut=3,4&mainmenu=commercial&leftmenu=orders_suppliers'; } - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; $commandestatic->delivery_date = $this->db->jdate($obj->delivery_date); @@ -2950,27 +2927,25 @@ class CommandeFournisseur extends CommonOrder { global $db, $langs; - if ($this->methode_commande_id > 0) - { + if ($this->methode_commande_id > 0) { $sql = "SELECT rowid, code, libelle as label"; $sql .= " FROM ".MAIN_DB_PREFIX.'c_input_method'; $sql .= " WHERE active=1 AND rowid = ".$this->db->escape($this->methode_commande_id); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $string = $langs->trans($obj->code); - if ($string == $obj->code) - { + if ($string == $obj->code) { $string = $obj->label != '-' ? $obj->label : ''; } return $string; } - } else dol_print_error($this->db); + } else { + dol_print_error($this->db); + } } return ''; @@ -3017,26 +2992,30 @@ class CommandeFournisseur extends CommonOrder */ public function getMaxDeliveryTimeDay($langs) { - if (empty($this->lines)) return ''; + if (empty($this->lines)) { + return ''; + } $obj = new ProductFournisseur($this->db); $nb = 0; - foreach ($this->lines as $line) - { - if ($line->fk_product > 0) - { + foreach ($this->lines as $line) { + if ($line->fk_product > 0) { $idp = $obj->find_min_price_product_fournisseur($line->fk_product, $line->qty); - if ($idp) - { + if ($idp) { $obj->fetch($idp); - if ($obj->delivery_time_days > $nb) $nb = $obj->delivery_time_days; + if ($obj->delivery_time_days > $nb) { + $nb = $obj->delivery_time_days; + } } } } - if ($nb === 0) return ''; - else return $nb.' '.$langs->trans('Days'); + if ($nb === 0) { + return ''; + } else { + return $nb.' '.$langs->trans('Days'); + } } /** @@ -3079,7 +3058,9 @@ class CommandeFournisseur extends CommonOrder { global $conf; - if (empty($this->delivery_date) && !empty($this->date_livraison)) $this->delivery_date = $this->date_livraison; // For backward compatibility + if (empty($this->delivery_date) && !empty($this->date_livraison)) { + $this->delivery_date = $this->date_livraison; // For backward compatibility + } if ($this->statut == self::STATUS_ORDERSENT || $this->statut == self::STATUS_RECEIVED_PARTIALLY) { $now = dol_now(); @@ -3110,7 +3091,9 @@ class CommandeFournisseur extends CommonOrder { global $conf, $langs; - if (empty($this->delivery_date) && !empty($this->date_livraison)) $this->delivery_date = $this->date_livraison; // For backward compatibility + if (empty($this->delivery_date) && !empty($this->date_livraison)) { + $this->delivery_date = $this->date_livraison; // For backward compatibility + } $text = ''; @@ -3143,8 +3126,7 @@ class CommandeFournisseur extends CommonOrder { global $conf, $langs; - if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) - { + if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) { require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class.php'; $qtydelivered = array(); @@ -3171,7 +3153,9 @@ class CommandeFournisseur extends CommonOrder } foreach ($this->lines as $line) { // Exclude lines not qualified for shipment, similar code is found into interface_20_modWrokflow for customers - if (empty($conf->global->STOCK_SUPPORTS_SERVICES) && $line->product_type > 0) continue; + if (empty($conf->global->STOCK_SUPPORTS_SERVICES) && $line->product_type > 0) { + continue; + } $qtywished[$line->fk_product] += $line->qty; } @@ -3181,16 +3165,14 @@ class CommandeFournisseur extends CommonOrder $keysindeliverednotinwished = array_diff(array_keys($qtydelivered), array_keys($qtywished)); // To check we also have same number of keys /*var_dump(array_keys($qtydelivered)); - var_dump(array_keys($qtywished)); - var_dump($diff_array); - var_dump($keysinwishednotindelivered); - var_dump($keysindeliverednotinwished); - exit;*/ + var_dump(array_keys($qtywished)); + var_dump($diff_array); + var_dump($keysinwishednotindelivered); + var_dump($keysindeliverednotinwished); + exit;*/ - if (count($diff_array) == 0 && count($keysinwishednotindelivered) == 0 && count($keysindeliverednotinwished) == 0) //No diff => mean everythings is received - { - if ($closeopenorder) - { + if (count($diff_array) == 0 && count($keysinwishednotindelivered) == 0 && count($keysindeliverednotinwished) == 0) { //No diff => mean everythings is received + if ($closeopenorder) { //$ret=$this->setStatus($user,5); $ret = $this->Livraison($user, $date_liv, 'tot', $comment); // GETPOST("type") is 'tot', 'par', 'nev', 'can' if ($ret < 0) { @@ -3211,16 +3193,13 @@ class CommandeFournisseur extends CommonOrder $close = 0; - if (count($diff_array) > 0) - { + if (count($diff_array) > 0) { //there are some difference between the two arrays //scan the array of results - foreach ($diff_array as $key => $value) - { + foreach ($diff_array as $key => $value) { //if the quantity delivered is greater or equal to wish quantity - if ($qtydelivered[$key] >= $qtywished[$key]) - { + if ($qtydelivered[$key] >= $qtywished[$key]) { $close++; } } @@ -3280,25 +3259,31 @@ class CommandeFournisseur extends CommonOrder $sql = 'SELECT cd.rowid, cd.fk_product,'; $sql .= ' sum(cfd.qty) as qty'; $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseur_dispatch as cfd,'; - if ($filtre_statut >= 0) $sql .= ' '.MAIN_DB_PREFIX.'reception as e,'; + if ($filtre_statut >= 0) { + $sql .= ' '.MAIN_DB_PREFIX.'reception as e,'; + } $sql .= ' '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; $sql .= ' WHERE'; - if ($filtre_statut >= 0) $sql .= ' cfd.fk_reception = e.rowid AND'; + if ($filtre_statut >= 0) { + $sql .= ' cfd.fk_reception = e.rowid AND'; + } $sql .= ' cfd.fk_commandefourndet = cd.rowid'; $sql .= ' AND cd.fk_commande ='.$this->id; - if ($this->fk_product > 0) $sql .= ' AND cd.fk_product = '.$this->fk_product; - if ($filtre_statut >= 0) $sql .= ' AND e.fk_statut >= '.$filtre_statut; + if ($this->fk_product > 0) { + $sql .= ' AND cd.fk_product = '.$this->fk_product; + } + if ($filtre_statut >= 0) { + $sql .= ' AND e.fk_statut >= '.$filtre_statut; + } $sql .= ' GROUP BY cd.rowid, cd.fk_product'; dol_syslog(get_class($this)."::loadReceptions", LOG_DEBUG); $result = $this->db->query($sql); - if ($result) - { + if ($result) { $num = $this->db->num_rows($result); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($result); empty($this->receptions[$obj->rowid]) ? $this->receptions[$obj->rowid] = $obj->qty : $this->receptions[$obj->rowid] += $obj->qty; $i++; @@ -3399,20 +3384,20 @@ class CommandeFournisseurLigne extends CommonOrderLine $sql .= ' p.ref as product_ref, p.label as product_label, p.description as product_desc,'; $sql .= ' cd.date_start, cd.date_end, cd.fk_unit,'; $sql .= ' cd.multicurrency_subprice, cd.multicurrency_total_ht, cd.multicurrency_total_tva, cd.multicurrency_total_ttc'; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $sql .= ", pfp.rowid as fk_pfp, pfp.packaging"; + } $sql .= ' FROM '.MAIN_DB_PREFIX.'commande_fournisseurdet as cd'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product as p ON cd.fk_product = p.rowid'; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as pfp ON cd.fk_product = pfp.fk_product and cd.ref = pfp.ref_fourn"; + } $sql .= ' WHERE cd.rowid = '.$rowid; $result = $this->db->query($sql); - if ($result) - { + if ($result) { $objp = $this->db->fetch_object($result); - if (!empty($objp)) - { + if (!empty($objp)) { $this->rowid = $objp->rowid; $this->id = $objp->rowid; $this->fk_commande = $objp->fk_commande; @@ -3443,8 +3428,7 @@ class CommandeFournisseurLigne extends CommonOrderLine $this->product_ref = $objp->product_ref; $this->product_label = $objp->product_label; $this->product_desc = $objp->product_desc; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) - { + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $this->packaging = $objp->packaging; $this->fk_fournprice = $objp->fk_pfp; } @@ -3488,32 +3472,63 @@ class CommandeFournisseurLigne extends CommonOrderLine dol_syslog(get_class($this)."::insert rang=".$this->rang); // Clean parameters - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = '0'; - if (empty($this->localtax2_type)) $this->localtax2_type = '0'; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->rang)) $this->rang = 0; - if (empty($this->remise)) $this->remise = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (empty($this->pa_ht)) $this->pa_ht = 0; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = '0'; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = '0'; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->rang)) { + $this->rang = 0; + } + if (empty($this->remise)) { + $this->remise = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } // Multicurrency - if (!empty($this->multicurrency_code)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; } // Check parameters - if ($this->product_type < 0) return -1; + if ($this->product_type < 0) { + return -1; + } $this->db->begin(); @@ -3528,7 +3543,11 @@ class CommandeFournisseurLigne extends CommonOrderLine $sql .= " VALUES (".$this->fk_commande.", '".$this->db->escape($this->label)."','".$this->db->escape($this->desc)."',"; $sql .= " ".($this->date_start ? "'".$this->db->idate($this->date_start)."'" : "null").","; $sql .= " ".($this->date_end ? "'".$this->db->idate($this->date_end)."'" : "null").","; - if ($this->fk_product) { $sql .= $this->fk_product.","; } else { $sql .= "null,"; } + if ($this->fk_product) { + $sql .= $this->fk_product.","; + } else { + $sql .= "null,"; + } $sql .= "'".$this->db->escape($this->product_type)."',"; $sql .= "'".$this->db->escape($this->special_code)."',"; $sql .= "'".$this->db->escape($this->rang)."',"; @@ -3556,25 +3575,23 @@ class CommandeFournisseurLigne extends CommonOrderLine dol_syslog(get_class($this)."::insert", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->rowid = $this->id; - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEORDER_SUPPLIER_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } @@ -3583,8 +3600,7 @@ class CommandeFournisseurLigne extends CommonOrderLine return 1; } - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->errors[] = ($this->errors ? ', '.$errmsg : $errmsg); } @@ -3647,32 +3663,26 @@ class CommandeFournisseurLigne extends CommonOrderLine dol_syslog(get_class($this)."::updateline", LOG_DEBUG); $result = $this->db->query($sql); - if ($result > 0) - { - if (!$error) - { + if ($result > 0) { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { global $user; // Call trigger $result = $this->call_trigger('LINEORDER_SUPPLIER_UPDATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -3702,8 +3712,7 @@ class CommandeFournisseurLigne extends CommonOrderLine // extrafields $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -3712,24 +3721,22 @@ class CommandeFournisseurLigne extends CommonOrderLine dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if (!$notrigger) - { + if ($resql) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('LINEORDER_SUPPLIER_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } - foreach ($this->errors as $errmsg) - { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } diff --git a/htdocs/fourn/class/fournisseur.commande.dispatch.class.php b/htdocs/fourn/class/fournisseur.commande.dispatch.class.php index a7abed27369..c79a53297f2 100644 --- a/htdocs/fourn/class/fournisseur.commande.dispatch.class.php +++ b/htdocs/fourn/class/fournisseur.commande.dispatch.class.php @@ -140,16 +140,36 @@ class CommandeFournisseurDispatch extends CommonObject // Clean parameters - if (isset($this->fk_commande)) $this->fk_commande = trim($this->fk_commande); - if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product); - if (isset($this->fk_commandefourndet)) $this->fk_commandefourndet = trim($this->fk_commandefourndet); - if (isset($this->qty)) $this->qty = trim($this->qty); - if (isset($this->fk_entrepot)) $this->fk_entrepot = trim($this->fk_entrepot); - if (isset($this->fk_user)) $this->fk_user = trim($this->fk_user); - if (isset($this->comment)) $this->comment = trim($this->comment); - if (isset($this->status)) $this->status = trim($this->status); - if (isset($this->batch)) $this->batch = trim($this->batch); - if (empty($this->datec)) $this->datec = dol_now(); + if (isset($this->fk_commande)) { + $this->fk_commande = trim($this->fk_commande); + } + if (isset($this->fk_product)) { + $this->fk_product = trim($this->fk_product); + } + if (isset($this->fk_commandefourndet)) { + $this->fk_commandefourndet = trim($this->fk_commandefourndet); + } + if (isset($this->qty)) { + $this->qty = trim($this->qty); + } + if (isset($this->fk_entrepot)) { + $this->fk_entrepot = trim($this->fk_entrepot); + } + if (isset($this->fk_user)) { + $this->fk_user = trim($this->fk_user); + } + if (isset($this->comment)) { + $this->comment = trim($this->comment); + } + if (isset($this->status)) { + $this->status = trim($this->status); + } + if (isset($this->batch)) { + $this->batch = trim($this->batch); + } + if (empty($this->datec)) { + $this->datec = dol_now(); + } // Check parameters @@ -190,16 +210,16 @@ class CommandeFournisseurDispatch extends CommonObject $this->db->begin(); - dol_syslog(__METHOD__, LOG_DEBUG); + dol_syslog(__METHOD__, LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { + if (!$error) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); - if (!$notrigger) - { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -211,17 +231,16 @@ class CommandeFournisseurDispatch extends CommonObject } // Create extrafields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -264,15 +283,16 @@ class CommandeFournisseurDispatch extends CommonObject $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t"; - if ($ref) $sql .= " WHERE t.ref = '".$ref."'"; - else $sql .= " WHERE t.rowid = ".$id; + if ($ref) { + $sql .= " WHERE t.ref = '".$ref."'"; + } else { + $sql .= " WHERE t.rowid = ".$id; + } dol_syslog(get_class($this)."::fetch"); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -318,15 +338,33 @@ class CommandeFournisseurDispatch extends CommonObject // Clean parameters - if (isset($this->fk_commande)) $this->fk_commande = trim($this->fk_commande); - if (isset($this->fk_product)) $this->fk_product = trim($this->fk_product); - if (isset($this->fk_commandefourndet)) $this->fk_commandefourndet = trim($this->fk_commandefourndet); - if (isset($this->qty)) $this->qty = trim($this->qty); - if (isset($this->fk_entrepot)) $this->fk_entrepot = trim($this->fk_entrepot); - if (isset($this->fk_user)) $this->fk_user = trim($this->fk_user); - if (isset($this->comment)) $this->comment = trim($this->comment); - if (isset($this->status)) $this->status = trim($this->status); - if (isset($this->batch)) $this->batch = trim($this->batch); + if (isset($this->fk_commande)) { + $this->fk_commande = trim($this->fk_commande); + } + if (isset($this->fk_product)) { + $this->fk_product = trim($this->fk_product); + } + if (isset($this->fk_commandefourndet)) { + $this->fk_commandefourndet = trim($this->fk_commandefourndet); + } + if (isset($this->qty)) { + $this->qty = trim($this->qty); + } + if (isset($this->fk_entrepot)) { + $this->fk_entrepot = trim($this->fk_entrepot); + } + if (isset($this->fk_user)) { + $this->fk_user = trim($this->fk_user); + } + if (isset($this->comment)) { + $this->comment = trim($this->comment); + } + if (isset($this->status)) { + $this->status = trim($this->status); + } + if (isset($this->batch)) { + $this->batch = trim($this->batch); + } @@ -357,34 +395,34 @@ class CommandeFournisseurDispatch extends CommonObject dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } - if (!$error) - { - if (!$error) - { - if (empty($this->id) && !empty($this->rowid))$this->id = $this->rowid; + if (!$error) { + if (!$error) { + if (empty($this->id) && !empty($this->rowid)) { + $this->id = $this->rowid; + } $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$notrigger) - { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you $result = $this->call_trigger('LINERECEPTION_UPDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } //// End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -397,13 +435,13 @@ class CommandeFournisseurDispatch extends CommonObject } - /** - * Delete object in database - * - * @param User $user User that deletes - * @param int $notrigger 0=launch triggers after, 1=disable triggers - * @return int <0 if KO, >0 if OK - */ + /** + * Delete object in database + * + * @param User $user User that deletes + * @param int $notrigger 0=launch triggers after, 1=disable triggers + * @return int <0 if KO, >0 if OK + */ public function delete($user, $notrigger = 0) { global $conf, $langs; @@ -411,10 +449,8 @@ class CommandeFournisseurDispatch extends CommonObject $this->db->begin(); - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Uncomment this and change MYOBJECT to your own tag if you // want this action calls a trigger. @@ -428,28 +464,26 @@ class CommandeFournisseurDispatch extends CommonObject // Remove extrafields if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error deleteExtraFields ".$this->error, LOG_ERR); } } - if (!$error) - { + if (!$error) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element; $sql .= " WHERE rowid=".$this->id; dol_syslog(__METHOD__); $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); } + if (!$resql) { + $error++; $this->errors[] = "Error ".$this->db->lasterror(); + } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(__METHOD__." ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -491,21 +525,18 @@ class CommandeFournisseurDispatch extends CommonObject $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $error++; } - if (!$error) - { + if (!$error) { } unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -541,30 +572,36 @@ class CommandeFournisseurDispatch extends CommonObject global $langs; $langs->load('orders'); - if ($mode == 0) - { + if ($mode == 0) { return $langs->trans($this->statuts[$status]); - } elseif ($mode == 1) - { + } elseif ($mode == 1) { return $langs->trans($this->statutshort[$status]); - } elseif ($mode == 2) - { + } elseif ($mode == 2) { return $langs->trans($this->statuts[$status]); - } elseif ($mode == 3) - { - if ($status == 0) return img_picto($langs->trans($this->statuts[$status]), 'statut0'); - elseif ($status == 1) return img_picto($langs->trans($this->statuts[$status]), 'statut4'); - elseif ($status == 2) return img_picto($langs->trans($this->statuts[$status]), 'statut8'); - } elseif ($mode == 4) - { - if ($status == 0) return img_picto($langs->trans($this->statuts[$status]), 'statut0').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 1) return img_picto($langs->trans($this->statuts[$status]), 'statut4').' '.$langs->trans($this->statuts[$status]); - elseif ($status == 2) return img_picto($langs->trans($this->statuts[$status]), 'statut8').' '.$langs->trans($this->statuts[$status]); - } elseif ($mode == 5) - { - if ($status == 0) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut0'); - elseif ($status == 1) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut4'); - elseif ($status == 2) return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut8'); + } elseif ($mode == 3) { + if ($status == 0) { + return img_picto($langs->trans($this->statuts[$status]), 'statut0'); + } elseif ($status == 1) { + return img_picto($langs->trans($this->statuts[$status]), 'statut4'); + } elseif ($status == 2) { + return img_picto($langs->trans($this->statuts[$status]), 'statut8'); + } + } elseif ($mode == 4) { + if ($status == 0) { + return img_picto($langs->trans($this->statuts[$status]), 'statut0').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 1) { + return img_picto($langs->trans($this->statuts[$status]), 'statut4').' '.$langs->trans($this->statuts[$status]); + } elseif ($status == 2) { + return img_picto($langs->trans($this->statuts[$status]), 'statut8').' '.$langs->trans($this->statuts[$status]); + } + } elseif ($mode == 5) { + if ($status == 0) { + return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut0'); + } elseif ($status == 1) { + return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut4'); + } elseif ($status == 2) { + return '<span class="hideonsmartphone">'.$langs->trans($this->statutshort[$status]).' </span>'.img_picto($langs->trans($this->statuts[$status]), 'statut8'); + } } } @@ -610,7 +647,7 @@ class CommandeFournisseurDispatch extends CommonObject { dol_syslog(__METHOD__, LOG_DEBUG); - $sql = "SELECT"; + $sql = "SELECT"; $sql .= " t.rowid,"; $sql .= " t.fk_commande,"; diff --git a/htdocs/fourn/class/fournisseur.facture.class.php b/htdocs/fourn/class/fournisseur.facture.class.php index 0157dbd0eec..2336b22a366 100644 --- a/htdocs/fourn/class/fournisseur.facture.class.php +++ b/htdocs/fourn/class/fournisseur.facture.class.php @@ -38,8 +38,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/commoninvoice.class.php'; require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formaccounting.class.php'; +} +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingaccount.class.php'; +} /** * Class to manage suppliers invoices @@ -350,9 +354,15 @@ class FactureFournisseur extends CommonInvoice $now = dol_now(); // Clean parameters - if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier); - if (empty($this->type)) $this->type = self::TYPE_STANDARD; - if (empty($this->date)) $this->date = $now; + if (isset($this->ref_supplier)) { + $this->ref_supplier = trim($this->ref_supplier); + } + if (empty($this->type)) { + $this->type = self::TYPE_STANDARD; + } + if (empty($this->date)) { + $this->date = $now; + } $socid = $this->socid; $ref_supplier = $this->ref_supplier; @@ -360,10 +370,12 @@ class FactureFournisseur extends CommonInvoice $remise = $this->remise; // Multicurrency (test on $this->multicurrency_tx because we should take the default rate only if not using origin rate) - if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); - else $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); - if (empty($this->fk_multicurrency)) - { + if (!empty($this->multicurrency_code) && empty($this->multicurrency_tx)) { + list($this->fk_multicurrency, $this->multicurrency_tx) = MultiCurrency::getIdAndTxFromCode($this->db, $this->multicurrency_code, $this->date); + } else { + $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code); + } + if (empty($this->fk_multicurrency)) { $this->multicurrency_code = $conf->currency; $this->fk_multicurrency = 0; $this->multicurrency_tx = 1; @@ -371,7 +383,9 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); - if (!$remise) $remise = 0; + if (!$remise) { + $remise = 0; + } $sql = "INSERT INTO ".MAIN_DB_PREFIX."facture_fourn ("; $sql .= "ref"; @@ -423,8 +437,7 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn'); // Update ref with new one @@ -433,25 +446,21 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::create", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) $error++; + if (!$resql) { + $error++; + } - if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) // To use new linkedObjectsIds instead of old linked_objects - { + if (!empty($this->linkedObjectsIds) && empty($this->linked_objects)) { // To use new linkedObjectsIds instead of old linked_objects $this->linked_objects = $this->linkedObjectsIds; // TODO Replace linked_objects with linkedObjectsIds } // Add object linked - if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) - { - foreach ($this->linked_objects as $origin => $tmp_origin_id) - { - if (is_array($tmp_origin_id)) // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) - { - foreach ($tmp_origin_id as $origin_id) - { + if (!$error && $this->id && !empty($this->linked_objects) && is_array($this->linked_objects)) { + foreach ($this->linked_objects as $origin => $tmp_origin_id) { + if (is_array($tmp_origin_id)) { // New behaviour, if linked_object can have several links per type, so is something like array('contract'=>array(id1, id2, ...)) + foreach ($tmp_origin_id as $origin_id) { $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { dol_print_error($this->db); $error++; } @@ -460,8 +469,7 @@ class FactureFournisseur extends CommonInvoice { $origin_id = $tmp_origin_id; $ret = $this->add_object_linked($origin, $origin_id); - if (!$ret) - { + if (!$ret) { dol_print_error($this->db); $error++; } @@ -469,17 +477,14 @@ class FactureFournisseur extends CommonInvoice } } - if (count($this->lines) && is_object($this->lines[0])) // If this->lines is array of InvoiceLines (preferred mode) - { + if (count($this->lines) && is_object($this->lines[0])) { // If this->lines is array of InvoiceLines (preferred mode) dol_syslog("There is ".count($this->lines)." lines that are invoice lines objects"); - foreach ($this->lines as $i => $val) - { + foreach ($this->lines as $i => $val) { $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)'; $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')'; $resql_insert = $this->db->query($sql); - if ($resql_insert) - { + if ($resql_insert) { $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); $this->updateline( @@ -511,20 +516,20 @@ class FactureFournisseur extends CommonInvoice } else // If this->lines is an array of invoice line arrays { dol_syslog("There is ".count($this->lines)." lines that are array lines"); - foreach ($this->lines as $i => $val) - { + foreach ($this->lines as $i => $val) { $line = $this->lines[$i]; // Test and convert into object this->lines[$i]. When coming from REST API, we may still have an array //if (! is_object($line)) $line=json_decode(json_encode($line), false); // convert recursively array into object. - if (!is_object($line)) $line = (object) $line; + if (!is_object($line)) { + $line = (object) $line; + } $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'facture_fourn_det (fk_facture_fourn, special_code)'; $sql .= ' VALUES ('.$this->id.','.intval($this->lines[$i]->special_code).')'; $resql_insert = $this->db->query($sql); - if ($resql_insert) - { + if ($resql_insert) { $idligne = $this->db->last_insert_id(MAIN_DB_PREFIX.'facture_fourn_det'); $this->updateline( @@ -539,7 +544,7 @@ class FactureFournisseur extends CommonInvoice 'HT', (!empty($line->info_bits) ? $line->info_bits : ''), $line->product_type - ); + ); } else { $this->error = $this->db->lasterror(); $this->db->rollback(); @@ -550,28 +555,25 @@ class FactureFournisseur extends CommonInvoice // Update total price $result = $this->update_price(); - if ($result > 0) - { + if ($result > 0) { // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); // This also set $this->error or $this->errors if errors are found - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->db->commit(); return $this->id; } else { @@ -584,8 +586,7 @@ class FactureFournisseur extends CommonInvoice return -3; } } else { - if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $this->error = $langs->trans('ErrorRefAlreadyExists'); $this->db->rollback(); return -1; @@ -655,15 +656,17 @@ class FactureFournisseur extends CommonInvoice $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_payment_term as cr ON t.fk_cond_reglement = cr.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as p ON t.fk_mode_reglement = p.id"; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON t.fk_incoterms = i.rowid'; - if ($id) $sql .= " WHERE t.rowid=".$id; - if ($ref) $sql .= " WHERE t.ref='".$this->db->escape($ref)."' AND t.entity IN (".getEntity('supplier_invoice').")"; + if ($id) { + $sql .= " WHERE t.rowid=".$id; + } + if ($ref) { + $sql .= " WHERE t.ref='".$this->db->escape($ref)."' AND t.entity IN (".getEntity('supplier_invoice').")"; + } dol_syslog(get_class($this)."::fetch", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - if ($this->db->num_rows($resql)) - { + if ($resql) { + if ($this->db->num_rows($resql)) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -737,11 +740,12 @@ class FactureFournisseur extends CommonInvoice // fetch optionals attributes and labels $this->fetch_optionals(); - if ($this->statut == self::STATUS_DRAFT) $this->brouillon = 1; + if ($this->statut == self::STATUS_DRAFT) { + $this->brouillon = 1; + } $result = $this->fetch_lines(); - if ($result < 0) - { + if ($result < 0) { $this->error = $this->db->lasterror(); return -3; } @@ -783,14 +787,11 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::fetch_lines", LOG_DEBUG); $resql_rows = $this->db->query($sql); - if ($resql_rows) - { + if ($resql_rows) { $num_rows = $this->db->num_rows($resql_rows); - if ($num_rows) - { + if ($num_rows) { $i = 0; - while ($i < $num_rows) - { + while ($i < $num_rows) { $obj = $this->db->fetch_object($resql_rows); $line = new SupplierInvoiceLine($this->db); @@ -877,37 +878,95 @@ class FactureFournisseur extends CommonInvoice $error = 0; // Clean parameters - if (empty($this->type)) $this->type = self::TYPE_STANDARD; - if (isset($this->ref)) $this->ref = trim($this->ref); - if (isset($this->ref_supplier)) $this->ref_supplier = trim($this->ref_supplier); - if (isset($this->entity)) $this->entity = trim($this->entity); - if (isset($this->type)) $this->type = trim($this->type); - if (isset($this->fk_soc)) $this->fk_soc = trim($this->fk_soc); - if (isset($this->label)) $this->label = trim($this->label); - if (isset($this->libelle)) $this->libelle = trim($this->libelle); // deprecated - if (isset($this->paye)) $this->paye = trim($this->paye); - if (isset($this->amount)) $this->amount = trim($this->amount); - if (isset($this->remise)) $this->remise = trim($this->remise); - if (isset($this->close_code)) $this->close_code = trim($this->close_code); - if (isset($this->close_note)) $this->close_note = trim($this->close_note); - if (isset($this->tva)) $this->tva = trim($this->tva); - if (isset($this->localtax1)) $this->localtax1 = trim($this->localtax1); - if (isset($this->localtax2)) $this->localtax2 = trim($this->localtax2); - if (empty($this->total_ht)) $this->total_ht = 0; - if (empty($this->total_tva)) $this->total_tva = 0; + if (empty($this->type)) { + $this->type = self::TYPE_STANDARD; + } + if (isset($this->ref)) { + $this->ref = trim($this->ref); + } + if (isset($this->ref_supplier)) { + $this->ref_supplier = trim($this->ref_supplier); + } + if (isset($this->entity)) { + $this->entity = trim($this->entity); + } + if (isset($this->type)) { + $this->type = trim($this->type); + } + if (isset($this->fk_soc)) { + $this->fk_soc = trim($this->fk_soc); + } + if (isset($this->label)) { + $this->label = trim($this->label); + } + if (isset($this->libelle)) { + $this->libelle = trim($this->libelle); // deprecated + } + if (isset($this->paye)) { + $this->paye = trim($this->paye); + } + if (isset($this->amount)) { + $this->amount = trim($this->amount); + } + if (isset($this->remise)) { + $this->remise = trim($this->remise); + } + if (isset($this->close_code)) { + $this->close_code = trim($this->close_code); + } + if (isset($this->close_note)) { + $this->close_note = trim($this->close_note); + } + if (isset($this->tva)) { + $this->tva = trim($this->tva); + } + if (isset($this->localtax1)) { + $this->localtax1 = trim($this->localtax1); + } + if (isset($this->localtax2)) { + $this->localtax2 = trim($this->localtax2); + } + if (empty($this->total_ht)) { + $this->total_ht = 0; + } + if (empty($this->total_tva)) { + $this->total_tva = 0; + } // if (isset($this->total_localtax1)) $this->total_localtax1=trim($this->total_localtax1); // if (isset($this->total_localtax2)) $this->total_localtax2=trim($this->total_localtax2); - if (isset($this->total_ttc)) $this->total_ttc = trim($this->total_ttc); - if (isset($this->statut)) $this->statut = (int) $this->statut; - if (isset($this->author)) $this->author = trim($this->author); - if (isset($this->fk_user_valid)) $this->fk_user_valid = trim($this->fk_user_valid); - if (isset($this->fk_facture_source)) $this->fk_facture_source = trim($this->fk_facture_source); - if (isset($this->fk_project)) $this->fk_project = trim($this->fk_project); - if (isset($this->cond_reglement_id)) $this->cond_reglement_id = trim($this->cond_reglement_id); - if (isset($this->note_private)) $this->note = trim($this->note_private); - if (isset($this->note_public)) $this->note_public = trim($this->note_public); - if (isset($this->model_pdf)) $this->model_pdf = trim($this->model_pdf); - if (isset($this->import_key)) $this->import_key = trim($this->import_key); + if (isset($this->total_ttc)) { + $this->total_ttc = trim($this->total_ttc); + } + if (isset($this->statut)) { + $this->statut = (int) $this->statut; + } + if (isset($this->author)) { + $this->author = trim($this->author); + } + if (isset($this->fk_user_valid)) { + $this->fk_user_valid = trim($this->fk_user_valid); + } + if (isset($this->fk_facture_source)) { + $this->fk_facture_source = trim($this->fk_facture_source); + } + if (isset($this->fk_project)) { + $this->fk_project = trim($this->fk_project); + } + if (isset($this->cond_reglement_id)) { + $this->cond_reglement_id = trim($this->cond_reglement_id); + } + if (isset($this->note_private)) { + $this->note = trim($this->note_private); + } + if (isset($this->note_public)) { + $this->note_public = trim($this->note_public); + } + if (isset($this->model_pdf)) { + $this->model_pdf = trim($this->model_pdf); + } + if (isset($this->import_key)) { + $this->import_key = trim($this->import_key); + } // Check parameters @@ -922,7 +981,9 @@ class FactureFournisseur extends CommonInvoice $sql .= " fk_soc=".(isset($this->fk_soc) ? $this->fk_soc : "null").","; $sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').","; $sql .= " datef=".(dol_strlen($this->date) != 0 ? "'".$this->db->idate($this->date)."'" : 'null').","; - if (dol_strlen($this->tms) != 0) $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; + if (dol_strlen($this->tms) != 0) { + $sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').","; + } $sql .= " libelle=".(isset($this->label) ? "'".$this->db->escape($this->label)."'" : "null").","; $sql .= " paye=".(isset($this->paye) ? $this->paye : "null").","; $sql .= " amount=".(isset($this->amount) ? $this->amount : "null").","; @@ -963,31 +1024,27 @@ class FactureFournisseur extends CommonInvoice } } - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error) - { - if (!$notrigger) - { + if (!$error) { + if (!$notrigger) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_UPDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } // Commit or rollback - if ($error) - { - foreach ($this->errors as $errmsg) - { + if ($error) { + foreach ($this->errors as $errmsg) { dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR); $this->error .= ($this->error ? ', '.$errmsg : $errmsg); } @@ -1019,10 +1076,8 @@ class FactureFournisseur extends CommonInvoice $remise = new DiscountAbsolute($this->db); $result = $remise->fetch($idremise); - if ($result > 0) - { - if ($remise->fk_invoice_supplier) // Protection against multiple submission - { + if ($result > 0) { + if ($remise->fk_invoice_supplier) { // Protection against multiple submission $this->error = $langs->trans("ErrorDiscountAlreadyUsed"); $this->db->rollback(); return -5; @@ -1043,8 +1098,7 @@ class FactureFournisseur extends CommonInvoice $facligne->info_bits = 2; // Get buy/cost price of invoice that is source of discount - if ($remise->fk_invoice_supplier_source > 0) - { + if ($remise->fk_invoice_supplier_source > 0) { $srcinvoice = new FactureFournisseur($this->db); $srcinvoice->fetch($remise->fk_invoice_supplier_source); $totalcostpriceofinvoice = 0; @@ -1064,15 +1118,12 @@ class FactureFournisseur extends CommonInvoice $facligne->multicurrency_total_ttc = -$remise->multicurrency_total_ttc; $lineid = $facligne->insert(); - if ($lineid > 0) - { + if ($lineid > 0) { $result = $this->update_price(1); - if ($result > 0) - { + if ($result > 0) { // Create link between discount and invoice line $result = $remise->link_to_invoice($lineid, 0, 'supplier'); - if ($result < 0) - { + if ($result < 0) { $this->error = $remise->error; $this->db->rollback(); return -4; @@ -1117,12 +1168,10 @@ class FactureFournisseur extends CommonInvoice $error = 0; $this->db->begin(); - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -1156,8 +1205,7 @@ class FactureFournisseur extends CommonInvoice } } - if (!$error) - { + if (!$error) { $main = MAIN_DB_PREFIX.'facture_fourn_det'; $ef = $main."_extrafields"; $sqlef = "DELETE FROM $ef WHERE fk_object IN (SELECT rowid FROM $main WHERE fk_facture_fourn = $rowid)"; @@ -1165,8 +1213,7 @@ class FactureFournisseur extends CommonInvoice $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn_det WHERE fk_facture_fourn = '.$rowid.';'; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resqlef && $resql) - { + if ($resqlef && $resql) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'facture_fourn WHERE rowid = '.$rowid; dol_syslog(get_class($this)."::delete", LOG_DEBUG); $resql2 = $this->db->query($sql); @@ -1178,47 +1225,43 @@ class FactureFournisseur extends CommonInvoice } } - if (!$error) - { + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete linked object $res = $this->deleteObjectLinked(); - if ($res < 0) $error++; + if ($res < 0) { + $error++; + } } - if (!$error) - { + if (!$error) { // Delete record into ECM index (Note that delete is also done when deleting files with the dol_delete_dir_recursive $this->deleteEcmFiles(); // We remove directory - if ($conf->fournisseur->facture->dir_output) - { + if ($conf->fournisseur->facture->dir_output) { include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $ref = dol_sanitizeFileName($this->ref); $dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoive_supplier').$ref; $file = $dir."/".$ref.".pdf"; - if (file_exists($file)) - { - if (!dol_delete_file($file, 0, 0, 0, $this)) // For triggers - { + if (file_exists($file)) { + if (!dol_delete_file($file, 0, 0, 0, $this)) { // For triggers $this->error = 'ErrorFailToDeleteFile'; $error++; } } - if (file_exists($dir)) - { + if (file_exists($dir)) { $res = @dol_delete_dir_recursive($dir); - if (!$res) - { + if (!$res) { $this->error = 'ErrorFailToDeleteDir'; $error++; } @@ -1227,18 +1270,15 @@ class FactureFournisseur extends CommonInvoice } // Remove extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } } - if (!$error) - { + if (!$error) { dol_syslog(get_class($this)."::delete $this->id by $user->id", LOG_DEBUG); $this->db->commit(); return 1; @@ -1289,11 +1329,12 @@ class FactureFournisseur extends CommonInvoice dol_syslog("FactureFournisseur::set_paid", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_PAYED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -1301,8 +1342,7 @@ class FactureFournisseur extends CommonInvoice dol_print_error($this->db); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1350,11 +1390,12 @@ class FactureFournisseur extends CommonInvoice dol_syslog("FactureFournisseur::set_unpaid", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_UNPAYED', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } else { $error++; @@ -1362,8 +1403,7 @@ class FactureFournisseur extends CommonInvoice dol_syslog("FactureFournisseur::set_unpaid ".$this->error); } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1397,19 +1437,16 @@ class FactureFournisseur extends CommonInvoice $this->fetch_lines(); // Check parameters - if ($this->statut > self::STATUS_DRAFT) // This is to avoid to validate twice (avoid errors on logs and stock management) - { + if ($this->statut > self::STATUS_DRAFT) { // This is to avoid to validate twice (avoid errors on logs and stock management) dol_syslog(get_class($this)."::validate no draft status", LOG_WARNING); return 0; } - if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier)) - { + if (preg_match('/^'.preg_quote($langs->trans("CopyOf").' ').'/', $this->ref_supplier)) { $langs->load("errors"); $this->error = $langs->trans("ErrorFieldFormat", $langs->transnoentities("RefSupplier")).'. '.$langs->trans('RemoveString', $langs->transnoentitiesnoconv("CopyOf")); return -1; } - if (count($this->lines) <= 0) - { + if (count($this->lines) <= 0) { $langs->load("errors"); $this->error = $langs->trans("ErrorObjectMustHaveLinesToBeValidated", $this->ref); return -1; @@ -1418,11 +1455,9 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); // Define new ref - if ($force_number) - { + if ($force_number) { $num = $force_number; - } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) // empty should not happened, but when it occurs, the test save life - { + } elseif (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life $num = $this->getNextNumRef($this->thirdparty); } else { $num = $this->ref; @@ -1435,71 +1470,72 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::validate", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Si on incrémente le produit principal et ses composants à la validation de facture fournisseur - if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) - { + if (!$error && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $cpt = count($this->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($this->lines[$i]->fk_product > 0) { $this->line = $this->lines[$i]; $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We increase stock for product $up_ht_disc = $this->lines[$i]->pu_ht; - if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU'); - if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num)); - else $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num)); - if ($result < 0) { $error++; } + if (!empty($this->lines[$i]->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) { + $up_ht_disc = price2num($up_ht_disc * (100 - $this->lines[$i]->remise_percent) / 100, 'MU'); + } + if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num)); + } else { + $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $up_ht_disc, $langs->trans("InvoiceValidatedInDolibarr", $num)); + } + if ($result < 0) { + $error++; + } unset($this->line); } } } // Triggers call - if (!$error && empty($notrigger)) - { + if (!$error && empty($notrigger)) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_VALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if (!$error) - { + if (!$error) { $this->oldref = $this->ref; // Rename directory if dir was a temporary ref - if (preg_match('/^[\(]?PROV/i', $this->ref)) - { + if (preg_match('/^[\(]?PROV/i', $this->ref)) { // Now we rename also files into index $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->newref)."'"; $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'fournisseur/facture/".get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$this->db->escape($this->ref)."' and entity = ".$conf->entity; $resql = $this->db->query($sql); - if (!$resql) { $error++; $this->error = $this->db->lasterror(); } + if (!$resql) { + $error++; $this->error = $this->db->lasterror(); + } // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments $oldref = dol_sanitizeFileName($this->ref); $newref = dol_sanitizeFileName($num); $dirsource = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$oldref; $dirdest = $conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref; - if (!$error && file_exists($dirsource)) - { + if (!$error && file_exists($dirsource)) { dol_syslog(get_class($this)."::validate rename dir ".$dirsource." into ".$dirdest); - if (@rename($dirsource, $dirdest)) - { + if (@rename($dirsource, $dirdest)) { dol_syslog("Rename ok"); // Rename docs starting with $oldref with $newref $listoffiles = dol_dir_list($conf->fournisseur->facture->dir_output.'/'.get_exdir($this->id, 2, 0, 0, $this, 'invoice_supplier').$newref, 'files', 1, '^'.preg_quote($oldref, '/')); - foreach ($listoffiles as $fileentry) - { + foreach ($listoffiles as $fileentry) { $dirsource = $fileentry['name']; $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource); $dirsource = $fileentry['path'].'/'.$dirsource; @@ -1512,15 +1548,13 @@ class FactureFournisseur extends CommonInvoice } // Set new ref and define current statut - if (!$error) - { + if (!$error) { $this->ref = $num; $this->statut = self::STATUS_VALIDATED; //$this->date_validation=$now; this is stored into log table } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -1548,8 +1582,7 @@ class FactureFournisseur extends CommonInvoice $error = 0; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { dol_syslog(__METHOD__." already draft status", LOG_WARNING); return 0; } @@ -1563,42 +1596,40 @@ class FactureFournisseur extends CommonInvoice $sql .= " WHERE rowid = ".$this->id; $result = $this->db->query($sql); - if ($result) - { - if (!$error) - { + if ($result) { + if (!$error) { $this->oldcopy = clone $this; } // Si on incremente le produit principal et ses composants a la validation de facture fournisseur, on decremente - if ($result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) - { + if ($result >= 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) { require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; $langs->load("agenda"); $cpt = count($this->lines); - for ($i = 0; $i < $cpt; $i++) - { - if ($this->lines[$i]->fk_product > 0) - { + for ($i = 0; $i < $cpt; $i++) { + if ($this->lines[$i]->fk_product > 0) { $mouvP = new MouvementStock($this->db); $mouvP->origin = &$this; // We increase stock for product - if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); - else $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); + if ($this->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $result = $mouvP->reception($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); + } else { + $result = $mouvP->livraison($user, $this->lines[$i]->fk_product, $idwarehouse, $this->lines[$i]->qty, $this->lines[$i]->subprice, $langs->trans("InvoiceBackToDraftInDolibarr", $this->ref)); + } } } } // Triggers call - if (!$error && empty($notrigger)) - { + if (!$error && empty($notrigger)) { // Call trigger $result = $this->call_trigger('BILL_SUPPLIER_UNVALIDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } - if ($error == 0) - { + if ($error == 0) { $this->db->commit(); return 1; } else { @@ -1652,17 +1683,32 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::addline $desc,$pu,$qty,$txtva,$fk_product,$remise_percent,$date_start,$date_end,$ventil,$info_bits,$price_base_type,$type,$fk_unit", LOG_DEBUG); include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php'; - if ($this->statut == self::STATUS_DRAFT) - { + if ($this->statut == self::STATUS_DRAFT) { // Clean parameters - if (empty($remise_percent)) $remise_percent = 0; - if (empty($qty)) $qty = 0; - if (empty($info_bits)) $info_bits = 0; - if (empty($rang)) $rang = 0; - if (empty($ventil)) $ventil = 0; - if (empty($txtva)) $txtva = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; + if (empty($remise_percent)) { + $remise_percent = 0; + } + if (empty($qty)) { + $qty = 0; + } + if (empty($info_bits)) { + $info_bits = 0; + } + if (empty($rang)) { + $rang = 0; + } + if (empty($ventil)) { + $ventil = 0; + } + if (empty($txtva)) { + $txtva = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } $remise_percent = price2num($remise_percent); $qty = price2num($qty); @@ -1681,15 +1727,12 @@ class FactureFournisseur extends CommonInvoice $this->db->begin(); - if ($fk_product > 0) - { - if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) - { + if ($fk_product > 0) { + if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) { // Check quantity is enough dol_syslog(get_class($this)."::addline we check supplier prices fk_product=".$fk_product." qty=".$qty." ref_supplier=".$ref_supplier); $prod = new Product($this->db, $fk_product); - if ($prod->fetch($fk_product) > 0) - { + if ($prod->fetch($fk_product) > 0) { $product_type = $prod->type; $label = $prod->label; $fk_prod_fourn_price = 0; @@ -1697,16 +1740,17 @@ class FactureFournisseur extends CommonInvoice // We use 'none' instead of $ref_supplier, because $ref_supplier may not exists anymore. So we will take the first supplier price ok. // If we want a dedicated supplier price, we must provide $fk_prod_fourn_price. $result = $prod->get_buyprice($fk_prod_fourn_price, $qty, $fk_product, 'none', ($this->fk_soc ? $this->fk_soc : $this->socid)); // Search on couple $fk_prod_fourn_price/$qty first, then on triplet $qty/$fk_product/$ref_supplier/$this->fk_soc - if ($result > 0) - { - if (empty($pu)) $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice + if ($result > 0) { + if (empty($pu)) { + $pu = $prod->fourn_pu; // Unit price supplier price set by get_buyprice + } $ref_supplier = $prod->ref_supplier; // Ref supplier price set by get_buyprice // is remise percent not keyed but present for the product we add it - if ($remise_percent == 0 && $prod->remise_percent != 0) + if ($remise_percent == 0 && $prod->remise_percent != 0) { $remise_percent = $prod->remise_percent; + } } - if ($result == 0) // If result == 0, we failed to found the supplier reference price - { + if ($result == 0) { // If result == 0, we failed to found the supplier reference price $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); @@ -1715,16 +1759,14 @@ class FactureFournisseur extends CommonInvoice //$ref = $prod->ref_fourn; // We do not overwrite ref supplier price return -1; } - if ($result == -1) - { + if ($result == -1) { $langs->load("errors"); $this->error = "Ref ".$prod->ref." ".$langs->trans("ErrorQtyTooLowForThisSupplier"); $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_DEBUG); return -1; } - if ($result < -1) - { + if ($result < -1) { $this->error = $prod->error; $this->db->rollback(); dol_syslog(get_class($this)."::addline result=".$result." - ".$this->error, LOG_ERR); @@ -1749,8 +1791,7 @@ class FactureFournisseur extends CommonInvoice // Clean vat code $reg = array(); $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $txtva, $reg)) - { + if (preg_match('/\((.*)\)/', $txtva, $reg)) { $vat_src_code = $reg[1]; $txtva = preg_replace('/\s*\(.*\)/', '', $txtva); // Remove code into vatrate. } @@ -1775,10 +1816,11 @@ class FactureFournisseur extends CommonInvoice $pu_ht_devise = $tabprice[19]; // Check parameters - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } - if ($rang < 0) - { + if ($rang < 0) { $rangmax = $this->line_max(); $rang = $rangmax + 1; } @@ -1837,15 +1879,15 @@ class FactureFournisseur extends CommonInvoice } $result = $this->line->insert($notrigger); - if ($result > 0) - { + if ($result > 0) { // Reorder if child line - if (!empty($fk_parent_line)) $this->line_order(true, 'DESC'); + if (!empty($fk_parent_line)) { + $this->line_order(true, 'DESC'); + } // Mise a jour informations denormalisees au niveau de la facture meme $result = $this->update_price(1, 'auto', 0, $this->thirdparty); // The addline method is designed to add line from user input so total calculation with update_price must be done using 'auto' mode. - if ($result > 0) - { + if ($result > 0) { $this->db->commit(); return $this->line->id; } else { @@ -1902,7 +1944,9 @@ class FactureFournisseur extends CommonInvoice // Check parameters //if (! is_numeric($pu) || ! is_numeric($qty)) return -1; - if ($type < 0) return -1; + if ($type < 0) { + return -1; + } if ($date_start && $date_end && $date_start > $date_end) { $langs->load("errors"); @@ -1911,9 +1955,15 @@ class FactureFournisseur extends CommonInvoice } // Clean parameters - if (empty($vatrate)) $vatrate = 0; - if (empty($txlocaltax1)) $txlocaltax1 = 0; - if (empty($txlocaltax2)) $txlocaltax2 = 0; + if (empty($vatrate)) { + $vatrate = 0; + } + if (empty($txlocaltax1)) { + $txlocaltax1 = 0; + } + if (empty($txlocaltax2)) { + $txlocaltax2 = 0; + } $txlocaltax1 = price2num($txlocaltax1); $txlocaltax2 = price2num($txlocaltax2); @@ -1929,8 +1979,7 @@ class FactureFournisseur extends CommonInvoice // Clean vat code $vat_src_code = ''; - if (preg_match('/\((.*)\)/', $vatrate, $reg)) - { + if (preg_match('/\((.*)\)/', $vatrate, $reg)) { $vat_src_code = $reg[1]; $vatrate = preg_replace('/\s*\(.*\)/', '', $vatrate); // Remove code into vatrate. } @@ -1951,10 +2000,11 @@ class FactureFournisseur extends CommonInvoice $multicurrency_total_ttc = $tabprice[18]; $pu_ht_devise = $tabprice[19]; - if (empty($info_bits)) $info_bits = 0; + if (empty($info_bits)) { + $info_bits = 0; + } - if ($idproduct) - { + if ($idproduct) { $product = new Product($this->db); $result = $product->fetch($idproduct); $product_type = $product->type; @@ -2046,8 +2096,7 @@ class FactureFournisseur extends CommonInvoice dol_syslog(get_class($this)."::deleteline", LOG_DEBUG); $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->error = $this->db->error(); $this->db->rollback(); return -2; @@ -2068,8 +2117,7 @@ class FactureFournisseur extends CommonInvoice } else { $res = $this->update_price(); - if ($res > 0) - { + if ($res > 0) { $this->db->commit(); return 1; } else { @@ -2095,26 +2143,21 @@ class FactureFournisseur extends CommonInvoice $sql .= ' WHERE c.rowid = '.$id; $result = $this->db->query($sql); - if ($result) - { - if ($this->db->num_rows($result)) - { + if ($result) { + if ($this->db->num_rows($result)) { $obj = $this->db->fetch_object($result); $this->id = $obj->rowid; - if ($obj->fk_user_author) - { + if ($obj->fk_user_author) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_author); $this->user_creation = $cuser; } - if ($obj->fk_user_valid) - { + if ($obj->fk_user_valid) { $vuser = new User($this->db); $vuser->fetch($obj->fk_user_valid); $this->user_validation = $vuser; } - if ($obj->fk_user_modif) - { + if ($obj->fk_user_modif) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modif); $this->user_modification = $muser; @@ -2155,15 +2198,15 @@ class FactureFournisseur extends CommonInvoice $sql .= " AND f.paye = 0"; // Pas classee payee completement $sql .= " AND pf.fk_paiementfourn IS NULL"; // Aucun paiement deja fait $sql .= " AND ff.fk_statut IS NULL"; // Renvoi vrai si pas facture de remplacement - if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; + if ($socid > 0) { + $sql .= " AND f.fk_soc = ".$socid; + } $sql .= " ORDER BY f.ref"; dol_syslog(get_class($this)."::list_replacable_supplier_invoices", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $return[$obj->rowid] = array( 'id' => $obj->rowid, 'ref' => $obj->ref, @@ -2203,20 +2246,23 @@ class FactureFournisseur extends CommonInvoice $sql .= " AND NOT EXISTS (SELECT rowid from ".MAIN_DB_PREFIX."facture_fourn as ff WHERE f.rowid = ff.fk_facture_source"; $sql .= " AND ff.type=".self::TYPE_REPLACEMENT.")"; $sql .= " AND f.type != ".self::TYPE_CREDIT_NOTE; // Type non 2 si facture non avoir - if ($socid > 0) $sql .= " AND f.fk_soc = ".$socid; + if ($socid > 0) { + $sql .= " AND f.fk_soc = ".$socid; + } $sql .= " ORDER BY f.ref"; dol_syslog(get_class($this)."::list_qualified_avoir_supplier_invoices", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $qualified = 0; - if ($obj->fk_statut == self::STATUS_VALIDATED) $qualified = 1; - if ($obj->fk_statut == self::STATUS_CLOSED) $qualified = 1; - if ($qualified) - { + if ($obj->fk_statut == self::STATUS_VALIDATED) { + $qualified = 1; + } + if ($obj->fk_statut == self::STATUS_CLOSED) { + $qualified = 1; + } + if ($qualified) { $paymentornot = ($obj->fk_paiementfourn ? 1 : 0); $return[$obj->rowid] = array('ref'=>$obj->ref, 'status'=>$obj->fk_statut, 'type'=>$obj->type, 'paye'=>$obj->paye, 'paymentornot'=>$paymentornot); } @@ -2243,16 +2289,21 @@ class FactureFournisseur extends CommonInvoice $sql = 'SELECT ff.rowid, ff.date_lim_reglement as datefin, ff.fk_statut'; $sql .= ' FROM '.MAIN_DB_PREFIX.'facture_fourn as ff'; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ' WHERE ff.paye=0'; $sql .= ' AND ff.fk_statut > 0'; $sql .= " AND ff.entity = ".$conf->entity; - if ($user->socid) $sql .= ' AND ff.fk_soc = '.$user->socid; - if (!$user->rights->societe->client->voir && !$user->socid) $sql .= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) { + $sql .= ' AND ff.fk_soc = '.$user->socid; + } + if (!$user->rights->societe->client->voir && !$user->socid) { + $sql .= " AND ff.fk_soc = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $langs->load("bills"); $now = dol_now(); @@ -2266,8 +2317,7 @@ class FactureFournisseur extends CommonInvoice $facturestatic = new FactureFournisseur($this->db); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $response->nbtodo++; $facturestatic->date_echeance = $this->db->jdate($obj->datefin); @@ -2307,56 +2357,84 @@ class FactureFournisseur extends CommonInvoice $result = ''; - if ($option == 'withdraw') $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id.'&type=bank-transfer'; - elseif ($option == 'document') $url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id; - else $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id; + if ($option == 'withdraw') { + $url = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$this->id.'&type=bank-transfer'; + } elseif ($option == 'document') { + $url = DOL_URL_ROOT.'/fourn/facture/document.php?facid='.$this->id; + } else { + $url = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$this->id; + } - if ($short) return $url; + if ($short) { + return $url; + } - if ($option !== 'nolink') - { + if ($option !== 'nolink') { // Add param to save lastsearch_values or not $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0); - if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1; - if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1'; + if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) { + $add_save_lastsearch_values = 1; + } + if ($add_save_lastsearch_values) { + $url .= '&save_lastsearch_values=1'; + } } $picto = $this->picto; - if ($this->type == self::TYPE_REPLACEMENT) $picto .= 'r'; // Replacement invoice - if ($this->type == self::TYPE_CREDIT_NOTE) $picto .= 'a'; // Credit note - if ($this->type == self::TYPE_DEPOSIT) $picto .= 'd'; // Deposit invoice + if ($this->type == self::TYPE_REPLACEMENT) { + $picto .= 'r'; // Replacement invoice + } + if ($this->type == self::TYPE_CREDIT_NOTE) { + $picto .= 'a'; // Credit note + } + if ($this->type == self::TYPE_DEPOSIT) { + $picto .= 'd'; // Deposit invoice + } $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("SupplierInvoice").'</u>'; - if ($this->type == self::TYPE_REPLACEMENT) $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceReplace").'</u>'; - elseif ($this->type == self::TYPE_CREDIT_NOTE) $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>'; - elseif ($this->type == self::TYPE_DEPOSIT) $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>'; - if (!empty($this->ref)) + if ($this->type == self::TYPE_REPLACEMENT) { + $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("InvoiceReplace").'</u>'; + } elseif ($this->type == self::TYPE_CREDIT_NOTE) { + $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("CreditNote").'</u>'; + } elseif ($this->type == self::TYPE_DEPOSIT) { + $label = '<u class="paddingrightonly">'.$langs->transnoentitiesnoconv("Deposit").'</u>'; + } + if (!empty($this->ref)) { $label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref; - if (!empty($this->ref_supplier)) + } + if (!empty($this->ref_supplier)) { $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier; - if (!empty($this->label)) + } + if (!empty($this->label)) { $label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label; - if (!empty($this->date)) + } + if (!empty($this->date)) { $label .= '<br><b>'.$langs->trans('Date').':</b> '.dol_print_date($this->date, 'day'); - if (!empty($this->total_ht)) + } + if (!empty($this->total_ht)) { $label .= '<br><b>'.$langs->trans('AmountHT').':</b> '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_tva)) + } + if (!empty($this->total_tva)) { $label .= '<br><b>'.$langs->trans('AmountVAT').':</b> '.price($this->total_tva, 0, $langs, 0, -1, -1, $conf->currency); - if (!empty($this->total_ttc)) + } + if (!empty($this->total_ttc)) { $label .= '<br><b>'.$langs->trans('AmountTTC').':</b> '.price($this->total_ttc, 0, $langs, 0, -1, -1, $conf->currency); - if ($moretitle) $label .= ' - '.$moretitle; + } + if ($moretitle) { + $label .= ' - '.$moretitle; + } if (isset($this->statut) && isset($this->alreadypaid)) { $label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5, $this->alreadypaid); } $ref = $this->ref; - if (empty($ref)) $ref = $this->id; + if (empty($ref)) { + $ref = $this->id; + } $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowSupplierInvoice"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } @@ -2369,15 +2447,17 @@ class FactureFournisseur extends CommonInvoice $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= ($max ?dol_trunc($ref, $max) : $ref); + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), $picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= ($max ?dol_trunc($ref, $max) : $ref); + } $result .= $linkend; - if ($addlinktonotes) - { + if ($addlinktonotes) { $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private); - if ($txttoshow) - { + if ($txttoshow) { $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1); $result .= ' <span class="note inline-block">'; $result .= '<a href="'.DOL_URL_ROOT.'/fourn/facture/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">'; @@ -2406,7 +2486,9 @@ class FactureFournisseur extends CommonInvoice $langs->load("orders"); // Clean parameters (if not defined or using deprecated value) - if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER = 'mod_facture_fournisseur_cactus'; + if (empty($conf->global->INVOICE_SUPPLIER_ADDON_NUMBER)) { + $conf->global->INVOICE_SUPPLIER_ADDON_NUMBER = 'mod_facture_fournisseur_cactus'; + } $mybool = false; @@ -2432,8 +2514,7 @@ class FactureFournisseur extends CommonInvoice $numref = ""; $numref = $obj->getNumRef($soc, $this, $mode); - if ($numref != "") - { + if ($numref != "") { return $numref; } else { $this->error = $obj->error; @@ -2467,12 +2548,10 @@ class FactureFournisseur extends CommonInvoice $sql .= $this->db->plimit(100); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num_prods = $this->db->num_rows($resql); $i = 0; - while ($i < $num_prods) - { + while ($i < $num_prods) { $i++; $row = $this->db->fetch_row($resql); $prodids[$i] = $row[0]; @@ -2496,13 +2575,11 @@ class FactureFournisseur extends CommonInvoice $this->multicurrency_tx = 1; $this->multicurrency_code = $conf->currency; - if (empty($option) || $option != 'nolines') - { + if (empty($option) || $option != 'nolines') { // Lines $nbp = 5; $xnbp = 0; - while ($xnbp < $nbp) - { + while ($xnbp < $nbp) { $line = new SupplierInvoiceLine($this->db); $line->desc = $langs->trans("Description")." ".$xnbp; $line->qty = 1; @@ -2512,8 +2589,7 @@ class FactureFournisseur extends CommonInvoice $line->tva_tx = 19.6; $line->localtax1_tx = 0; $line->localtax2_tx = 0; - if ($xnbp == 2) - { + if ($xnbp == 2) { $line->total_ht = 50; $line->total_ttc = 59.8; $line->total_tva = 9.8; @@ -2525,8 +2601,7 @@ class FactureFournisseur extends CommonInvoice $line->remise_percent = 0; } - if ($num_prods > 0) - { + if ($num_prods > 0) { $prodid = mt_rand(1, $num_prods); $line->fk_product = $prodids[$prodid]; } @@ -2566,8 +2641,7 @@ class FactureFournisseur extends CommonInvoice $sql = "SELECT count(f.rowid) as nb"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON f.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$user->socid) - { + if (!$user->rights->societe->client->voir && !$user->socid) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; $sql .= " WHERE sc.fk_user = ".$user->id; $clause = "AND"; @@ -2575,10 +2649,8 @@ class FactureFournisseur extends CommonInvoice $sql .= " ".$clause." f.entity = ".$conf->entity; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $this->nb["supplier_invoices"] = $obj->nb; } $this->db->free($resql); @@ -2629,10 +2701,8 @@ class FactureFournisseur extends CommonInvoice $object->close_note = ''; // Loop on each line of new invoice - foreach ($object->lines as $i => $line) - { - if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) // We do not clone line of discounts - { + foreach ($object->lines as $i => $line) { + if (isset($object->lines[$i]->info_bits) && ($object->lines[$i]->info_bits & 0x02) == 0x02) { // We do not clone line of discounts unset($object->lines[$i]); } } @@ -2642,22 +2712,19 @@ class FactureFournisseur extends CommonInvoice $result = $object->create($user); // Other options - if ($result < 0) - { + if ($result < 0) { $this->error = $object->error; $this->errors = $object->errors; $error++; } - if (!$error) - { + if (!$error) { } unset($object->context['createfromclone']); // End - if (!$error) - { + if (!$error) { $this->db->commit(); return $object->id; } else { @@ -2685,18 +2752,15 @@ class FactureFournisseur extends CommonInvoice $outputlangs->load("products"); // Set the model on the model name to use - if (empty($modele)) - { - if (!empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) - { + if (empty($modele)) { + if (!empty($conf->global->INVOICE_SUPPLIER_ADDON_PDF)) { $modele = $conf->global->INVOICE_SUPPLIER_ADDON_PDF; } else { $modele = ''; // No default value. For supplier invoice, we allow to disable all PDF generation } } - if (empty($modele)) - { + if (empty($modele)) { return 0; } else { $modelpath = "core/modules/supplier_invoice/doc/"; @@ -2764,7 +2828,9 @@ class FactureFournisseur extends CommonInvoice $resql = $this->db->query($sql); if (!empty($resql)) { $obj = $this->db->fetch_object($resql); - if (!empty($obj->fk_invoice_supplier)) $isUsed = true; + if (!empty($obj->fk_invoice_supplier)) { + $isUsed = true; + } } return $isUsed; @@ -3111,11 +3177,9 @@ class SupplierInvoiceLine extends CommonObjectLine $this->deleteObjectLinked(); // Remove extrafields - if (!$error) - { + if (!$error) { $result = $this->deleteExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR); } @@ -3133,8 +3197,7 @@ class SupplierInvoiceLine extends CommonObjectLine } } - if (!$error) - { + if (!$error) { $this->db->commit(); return 1; } else { @@ -3157,22 +3220,31 @@ class SupplierInvoiceLine extends CommonObjectLine $qty = price2num($this->qty); // Check parameters - if (empty($this->qty)) $this->qty = 0; + if (empty($this->qty)) { + $this->qty = 0; + } if ($this->product_type < 0) { return -1; } // Clean parameters - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } $this->db->begin(); - if (empty($this->fk_product)) - { + if (empty($this->fk_product)) { $fk_product = "null"; } else { $fk_product = $this->fk_product; @@ -3229,17 +3301,14 @@ class SupplierInvoiceLine extends CommonObjectLine $this->rowid = $this->id; $error = 0; - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { global $langs, $user; // Call trigger @@ -3275,41 +3344,78 @@ class SupplierInvoiceLine extends CommonObjectLine // Clean parameters $this->desc = trim($this->desc); - if (empty($this->tva_tx)) $this->tva_tx = 0; - if (empty($this->localtax1_tx)) $this->localtax1_tx = 0; - if (empty($this->localtax2_tx)) $this->localtax2_tx = 0; - if (empty($this->localtax1_type)) $this->localtax1_type = '0'; - if (empty($this->localtax2_type)) $this->localtax2_type = '0'; - if (empty($this->total_tva)) $this->total_tva = 0; - if (empty($this->total_localtax1)) $this->total_localtax1 = 0; - if (empty($this->total_localtax2)) $this->total_localtax2 = 0; - if (empty($this->rang)) $this->rang = 0; - if (empty($this->remise_percent)) $this->remise_percent = 0; - if (empty($this->info_bits)) $this->info_bits = 0; - if (empty($this->subprice)) $this->subprice = 0; - if (empty($this->special_code)) $this->special_code = 0; - if (empty($this->fk_parent_line)) $this->fk_parent_line = 0; - if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') $this->situation_percent = 100; + if (empty($this->tva_tx)) { + $this->tva_tx = 0; + } + if (empty($this->localtax1_tx)) { + $this->localtax1_tx = 0; + } + if (empty($this->localtax2_tx)) { + $this->localtax2_tx = 0; + } + if (empty($this->localtax1_type)) { + $this->localtax1_type = '0'; + } + if (empty($this->localtax2_type)) { + $this->localtax2_type = '0'; + } + if (empty($this->total_tva)) { + $this->total_tva = 0; + } + if (empty($this->total_localtax1)) { + $this->total_localtax1 = 0; + } + if (empty($this->total_localtax2)) { + $this->total_localtax2 = 0; + } + if (empty($this->rang)) { + $this->rang = 0; + } + if (empty($this->remise_percent)) { + $this->remise_percent = 0; + } + if (empty($this->info_bits)) { + $this->info_bits = 0; + } + if (empty($this->subprice)) { + $this->subprice = 0; + } + if (empty($this->special_code)) { + $this->special_code = 0; + } + if (empty($this->fk_parent_line)) { + $this->fk_parent_line = 0; + } + if (!isset($this->situation_percent) || $this->situation_percent > 100 || (string) $this->situation_percent == '') { + $this->situation_percent = 100; + } - if (empty($this->pa_ht)) $this->pa_ht = 0; - if (empty($this->multicurrency_subprice)) $this->multicurrency_subprice = 0; - if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht = 0; - if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva = 0; - if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc = 0; + if (empty($this->pa_ht)) { + $this->pa_ht = 0; + } + if (empty($this->multicurrency_subprice)) { + $this->multicurrency_subprice = 0; + } + if (empty($this->multicurrency_total_ht)) { + $this->multicurrency_total_ht = 0; + } + if (empty($this->multicurrency_total_tva)) { + $this->multicurrency_total_tva = 0; + } + if (empty($this->multicurrency_total_ttc)) { + $this->multicurrency_total_ttc = 0; + } // Check parameters - if ($this->product_type < 0) - { + if ($this->product_type < 0) { $this->error = 'ErrorProductTypeMustBe0orMore'; return -1; } - if (!empty($this->fk_product)) - { + if (!empty($this->fk_product)) { // Check product exists $result = Product::isExistingObject('product', $this->fk_product); - if ($result <= 0) - { + if ($result <= 0) { $this->error = 'ErrorProductIdDoesNotExists'; return -1; } @@ -3365,26 +3471,21 @@ class SupplierInvoiceLine extends CommonObjectLine $sql .= ')'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element); $this->rowid = $this->id; // backward compatibility - if (!$error) - { + if (!$error) { $result = $this->insertExtraFields(); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if (!$error && !$notrigger) - { + if (!$error && !$notrigger) { // Call trigger $result = $this->call_trigger('LINEBILL_SUPPLIER_CREATE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -2; } @@ -3423,8 +3524,7 @@ class SupplierInvoiceLine extends CommonObjectLine dol_syslog("FactureFournisseurLigne.class.php::update_total", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { diff --git a/htdocs/fourn/class/fournisseur.product.class.php b/htdocs/fourn/class/fournisseur.product.class.php index 6ae9a3491ab..e0eea961b9e 100644 --- a/htdocs/fourn/class/fournisseur.product.class.php +++ b/htdocs/fourn/class/fournisseur.product.class.php @@ -168,14 +168,12 @@ class ProductFournisseur extends Product dol_syslog(get_class($this)."::remove_fournisseur", LOG_DEBUG); $resql2 = $this->db->query($sql); - if (!$resql2) - { + if (!$resql2) { $this->error = $this->db->lasterror(); $ok = 0; } - if ($ok) - { + if ($ok) { $this->db->commit(); return 1; } else { @@ -203,18 +201,18 @@ class ProductFournisseur extends Product // Call trigger $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_DELETE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if (empty($error)) - { + if (empty($error)) { $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price"; $sql .= " WHERE rowid = ".$rowid; dol_syslog(get_class($this)."::remove_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); - if (!$resql) - { + if (!$resql) { $this->error = $this->db->lasterror(); $error++; } @@ -266,15 +264,28 @@ class ProductFournisseur extends Product //global $mysoc; // Clean parameter - if (empty($qty)) $qty = 0; - if (empty($buyprice)) $buyprice = 0; - if (empty($charges)) $charges = 0; - if (empty($availability)) $availability = 0; - if (empty($remise_percent)) $remise_percent = 0; - if (empty($supplier_reputation) || $supplier_reputation == -1) $supplier_reputation = ''; - if ($delivery_time_days != '' && !is_numeric($delivery_time_days)) $delivery_time_days = ''; - if ($price_base_type == 'TTC') - { + if (empty($qty)) { + $qty = 0; + } + if (empty($buyprice)) { + $buyprice = 0; + } + if (empty($charges)) { + $charges = 0; + } + if (empty($availability)) { + $availability = 0; + } + if (empty($remise_percent)) { + $remise_percent = 0; + } + if (empty($supplier_reputation) || $supplier_reputation == -1) { + $supplier_reputation = ''; + } + if ($delivery_time_days != '' && !is_numeric($delivery_time_days)) { + $delivery_time_days = ''; + } + if ($price_base_type == 'TTC') { $ttx = $tva_tx; $buyprice = $buyprice / (1 + ($ttx / 100)); } @@ -283,10 +294,13 @@ class ProductFournisseur extends Product $multicurrency_unitBuyPrice = null; $fk_multicurrency = null; if (!empty($conf->multicurrency->enabled)) { - if (empty($multicurrency_tx)) $multicurrency_tx = 1; - if (empty($multicurrency_buyprice)) $multicurrency_buyprice = 0; - if ($multicurrency_price_base_type == 'TTC') - { + if (empty($multicurrency_tx)) { + $multicurrency_tx = 1; + } + if (empty($multicurrency_buyprice)) { + $multicurrency_buyprice = 0; + } + if ($multicurrency_price_base_type == 'TTC') { $ttx = $tva_tx; $multicurrency_buyprice = $multicurrency_buyprice / (1 + ($ttx / 100)); } @@ -309,8 +323,7 @@ class ProductFournisseur extends Product $newvat = $tva_tx; - if (count($localtaxes_array) > 0) - { + if (count($localtaxes_array) > 0) { $localtaxtype1 = $localtaxes_array['0']; $localtax1 = $localtaxes_array['1']; $localtaxtype2 = $localtaxes_array['2']; @@ -321,26 +334,26 @@ class ProductFournisseur extends Product $localtaxtype2 = '0'; $localtax2 = get_localtax($newvat, 2); } - if (empty($localtax1)) $localtax1 = 0; // If = '' then = 0 - if (empty($localtax2)) $localtax2 = 0; // If = '' then = 0 + if (empty($localtax1)) { + $localtax1 = 0; // If = '' then = 0 + } + if (empty($localtax2)) { + $localtax2 = 0; // If = '' then = 0 + } // Check parameters - if ($buyprice != '' && !is_numeric($buyprice)) - { + if ($buyprice != '' && !is_numeric($buyprice)) { } $this->db->begin(); - if ($this->product_fourn_price_id > 0) - { + if ($this->product_fourn_price_id > 0) { // check if price already logged, if not first log current price $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id); - if (is_array($logPrices) && count($logPrices) == 0) - { + if (is_array($logPrices) && count($logPrices) == 0) { $currentPfp = new self($this->db); $result = $currentPfp->fetch_product_fournisseur_price($this->product_fourn_price_id); - if ($result > 0 && $currentPfp->fourn_price != 0) - { + if ($result > 0 && $currentPfp->fourn_price != 0) { $currentPfpUser = new User($this->db); $result = $currentPfpUser->fetch($currentPfp->user_id); if ($result > 0) { @@ -387,27 +400,28 @@ class ProductFournisseur extends Product $sql .= " supplier_reputation = ".(empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").","; $sql .= " barcode = ".(empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").","; $sql .= " fk_barcode_type = ".(empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'"); - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", packaging = ".(empty($packaging) ? 1 : $packaging); + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $sql .= ", packaging = ".(empty($packaging) ? 1 : $packaging); + } $sql .= " WHERE rowid = ".$this->product_fourn_price_id; // TODO Add price_base_type and price_ttc dol_syslog(get_class($this).'::update_buyprice update knowing id of line = product_fourn_price_id = '.$this->product_fourn_price_id, LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { // Call trigger $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_UPDATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers - if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) - { + if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) { $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code); if ($result < 0) { $error++; } } - if (empty($error)) - { + if (empty($error)) { $this->db->commit(); return $this->product_fourn_price_id; } else { @@ -431,7 +445,9 @@ class ProductFournisseur extends Product $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price("; $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,"; $sql .= "datec, fk_product, fk_soc, ref_fourn, desc_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, fk_availability, default_vat_code, info_bits, entity, delivery_time_days, supplier_reputation, barcode, fk_barcode_type)"; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", packaging"; + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $sql .= ", packaging"; + } $sql .= " values("; $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').","; $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').","; @@ -459,7 +475,9 @@ class ProductFournisseur extends Product $sql .= (empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").","; $sql .= (empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").","; $sql .= (empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'"); - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", ".(empty($this->packaging) ? 1 : $this->db->escape($this->packaging)); + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $sql .= ", ".(empty($this->packaging) ? 1 : $this->db->escape($this->packaging)); + } $sql .= ")"; $this->product_fourn_price_id = 0; @@ -483,8 +501,9 @@ class ProductFournisseur extends Product if (!$error) { // Call trigger $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_CREATE', $user); - if ($result < 0) + if ($result < 0) { $error++; + } // End call triggers if (empty($error)) { @@ -532,11 +551,9 @@ class ProductFournisseur extends Product dol_syslog(get_class($this)."::fetch_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); - if ($obj) - { + if ($obj) { $this->product_fourn_price_id = $rowid; $this->id = $obj->fk_product; @@ -578,18 +595,18 @@ class ProductFournisseur extends Product if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $this->packaging = $obj->packaging; - if ($this->packaging < $this->fourn_qty) $this->packaging = $this->fourn_qty; + if ($this->packaging < $this->fourn_qty) { + $this->packaging = $this->fourn_qty; + } } - if (empty($ignore_expression) && !empty($this->fk_supplier_price_expression)) - { + if (empty($ignore_expression) && !empty($this->fk_supplier_price_expression)) { $priceparser = new PriceParser($this->db); $price_result = $priceparser->parseProductSupplier($this); if ($price_result >= 0) { $this->fourn_price = $price_result; //recalculation of unitprice, as probably the price changed... - if ($this->fourn_qty != 0) - { + if ($this->fourn_qty != 0) { $this->fourn_unitprice = price2num($this->fourn_price / $this->fourn_qty, 'MU'); } else { $this->fourn_unitprice = ""; @@ -629,24 +646,27 @@ class ProductFournisseur extends Product $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.fk_availability, pfp.charges, pfp.info_bits, pfp.delivery_time_days, pfp.supplier_reputation,"; $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code, pfp.datec, pfp.tms,"; $sql .= " pfp.barcode, pfp.fk_barcode_type"; - if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) $sql .= ", pfp.packaging"; + if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { + $sql .= ", pfp.packaging"; + } $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp, ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."societe as s"; $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")"; $sql .= " AND pfp.fk_soc = s.rowid AND pfp.fk_product = p.rowid"; $sql .= " AND s.status=1"; // only enabled company selected $sql .= " AND pfp.fk_product = ".$prodid; - if (empty($sortfield)) $sql .= " ORDER BY s.nom, pfp.quantity, pfp.price"; - else $sql .= $this->db->order($sortfield, $sortorder); + if (empty($sortfield)) { + $sql .= " ORDER BY s.nom, pfp.quantity, pfp.price"; + } else { + $sql .= $this->db->order($sortfield, $sortorder); + } $sql .= $this->db->plimit($limit, $offset); dol_syslog(get_class($this)."::list_product_fournisseur_price", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $retarray = array(); - while ($record = $this->db->fetch_array($resql)) - { + while ($record = $this->db->fetch_array($resql)) { //define base attribute $prodfourn = new ProductFournisseur($this->db); @@ -683,7 +703,9 @@ class ProductFournisseur extends Product if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) { $prodfourn->packaging = $record["packaging"]; - if ($prodfourn->packaging < $prodfourn->fourn_qty) $prodfourn->packaging = $prodfourn->fourn_qty; + if ($prodfourn->packaging < $prodfourn->fourn_qty) { + $prodfourn->packaging = $prodfourn->fourn_qty; + } } if (!empty($conf->barcode->enabled)) { @@ -700,10 +722,8 @@ class ProductFournisseur extends Product } } - if (!isset($prodfourn->fourn_unitprice)) - { - if ($prodfourn->fourn_qty != 0) - { + if (!isset($prodfourn->fourn_unitprice)) { + if ($prodfourn->fourn_qty != 0) { $prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price / $prodfourn->fourn_qty, 'MU'); } else { $prodfourn->fourn_unitprice = ""; @@ -735,8 +755,7 @@ class ProductFournisseur extends Product // phpcs:enable global $conf; - if (empty($prodid)) - { + if (empty($prodid)) { dol_syslog("Warning function find_min_price_product_fournisseur were called with prodid empty. May be a bug.", LOG_WARNING); return 0; } @@ -771,30 +790,30 @@ class ProductFournisseur extends Product $sql .= " AND pfp.fk_product = ".$prodid; $sql .= " AND pfp.fk_soc = s.rowid"; $sql .= " AND s.status = 1"; // only enabled society - if ($qty > 0) $sql .= " AND pfp.quantity <= ".$qty; - if ($socid > 0) $sql .= ' AND pfp.fk_soc = '.$socid; + if ($qty > 0) { + $sql .= " AND pfp.quantity <= ".$qty; + } + if ($socid > 0) { + $sql .= ' AND pfp.fk_soc = '.$socid; + } dol_syslog(get_class($this)."::find_min_price_product_fournisseur", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $record_array = array(); //Store each record to array for later search of min - while ($record = $this->db->fetch_array($resql)) - { + while ($record = $this->db->fetch_array($resql)) { $record_array[] = $record; } - if (count($record_array) == 0) - { + if (count($record_array) == 0) { $this->db->free($resql); return 0; } else { $min = -1; - foreach ($record_array as $record) - { + foreach ($record_array as $record) { $fourn_price = $record["price"]; // discount calculated buy price $fourn_unitprice = $record["unitprice"] * (1 - $record["remise_percent"] / 100) - $record["remise"]; @@ -809,16 +828,14 @@ class ProductFournisseur extends Product $price_result = $priceparser->parseProductSupplier($prod_supplier); if ($price_result >= 0) { $fourn_price = price2num($price_result, 'MU'); - if ($record["quantity"] != 0) - { + if ($record["quantity"] != 0) { $fourn_unitprice = price2num($fourn_price / $record["quantity"], 'MU'); } else { $fourn_unitprice = $fourn_price; } } } - if ($fourn_unitprice < $min || $min == -1) - { + if ($fourn_unitprice < $min || $min == -1) { $this->product_fourn_price_id = $record["product_fourn_price_id"]; $this->ref_supplier = $record["ref_fourn"]; $this->ref_fourn = $record["ref_fourn"]; // deprecated @@ -874,8 +891,7 @@ class ProductFournisseur extends Product dol_syslog(get_class($this)."::setSupplierPriceExpression", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->db->commit(); return 1; } else { @@ -982,18 +998,19 @@ class ProductFournisseur extends Product $sql .= " AND pfpl.fk_user = u.rowid"; $sql .= " AND pfp.rowid = pfpl.fk_product_fournisseur"; $sql .= " AND pfpl.fk_product_fournisseur = ".$product_fourn_price_id; - if (empty($sortfield)) $sql .= " ORDER BY pfpl.datec"; - else $sql .= $this->db->order($sortfield, $sortorder); + if (empty($sortfield)) { + $sql .= " ORDER BY pfpl.datec"; + } else { + $sql .= $this->db->order($sortfield, $sortorder); + } $sql .= $this->db->plimit($limit, $offset); dol_syslog(get_class($this)."::list_product_fournisseur_price_log", LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $retarray = array(); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $tmparray = array(); $tmparray['rowid'] = $obj->rowid; $tmparray['supplier_ref'] = $obj->supplier_ref; @@ -1126,7 +1143,9 @@ class ProductFournisseur extends Product if ($this->height) { $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units); } - if ($labelsize) $label .= "<br>".$labelsize; + if ($labelsize) { + $label .= "<br>".$labelsize; + } $labelsurfacevolume = ""; if ($this->surface) { @@ -1135,7 +1154,9 @@ class ProductFournisseur extends Product if ($this->volume) { $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units); } - if ($labelsurfacevolume) $label .= "<br>".$labelsurfacevolume; + if ($labelsurfacevolume) { + $label .= "<br>".$labelsurfacevolume; + } } if (!empty($conf->accounting->enabled) && $this->status) { diff --git a/htdocs/fourn/class/paiementfourn.class.php b/htdocs/fourn/class/paiementfourn.class.php index cd172d08345..ceb7bb835ef 100644 --- a/htdocs/fourn/class/paiementfourn.class.php +++ b/htdocs/fourn/class/paiementfourn.class.php @@ -98,20 +98,19 @@ class PaiementFourn extends Paiement $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_paiement as c ON p.fk_paiement = c.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON p.fk_bank = b.rowid'; $sql .= ' WHERE p.entity IN ('.getEntity('facture_fourn').')'; - if ($id > 0) + if ($id > 0) { $sql .= ' AND p.rowid = '.$id; - elseif ($ref) + } elseif ($ref) { $sql .= ' AND p.rowid = '.$ref; - elseif ($fk_bank) + } elseif ($fk_bank) { $sql .= ' AND p.fk_bank = '.$fk_bank; + } //print $sql; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; @@ -166,8 +165,7 @@ class PaiementFourn extends Paiement dol_syslog(get_class($this)."::create", LOG_DEBUG); - if ($way == 'dolibarr') - { + if ($way == 'dolibarr') { $amounts = &$this->amounts; $amounts_to_update = &$this->multicurrency_amounts; } else { @@ -175,8 +173,7 @@ class PaiementFourn extends Paiement $amounts_to_update = &$this->amounts; } - foreach ($amounts as $key => $value) - { + foreach ($amounts as $key => $value) { $value_converted = Multicurrency::getAmountConversionFromInvoiceRate($key, $value ? $value : 0, $way, 'facture_fourn'); $totalamount_converted += $value_converted; $amounts_to_update[$key] = price2num($value_converted, 'MT'); @@ -190,13 +187,11 @@ class PaiementFourn extends Paiement $this->db->begin(); - if ($totalamount <> 0) // On accepte les montants negatifs - { + if ($totalamount <> 0) { // On accepte les montants negatifs $ref = $this->getNextNumRef(is_object($thirdparty) ? $thirdparty : ''); $now = dol_now(); - if ($way == 'dolibarr') - { + if ($way == 'dolibarr') { $total = $totalamount; $mtotal = $totalamount_converted; // Maybe use price2num with MT for the converted value } else { @@ -210,28 +205,23 @@ class PaiementFourn extends Paiement $sql .= " '".$this->db->idate($this->datepaye)."', '".$total."', '".$mtotal."', ".$this->paiementid.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_private)."', ".$user->id.", 0)"; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'paiementfourn'); // Insere tableau des montants / factures - foreach ($this->amounts as $key => $amount) - { + foreach ($this->amounts as $key => $amount) { $facid = $key; - if (is_numeric($amount) && $amount <> 0) - { + if (is_numeric($amount) && $amount <> 0) { $amount = price2num($amount); $sql = 'INSERT INTO '.MAIN_DB_PREFIX.'paiementfourn_facturefourn (fk_facturefourn, fk_paiementfourn, amount, multicurrency_amount)'; $sql .= ' VALUES ('.$facid.','.$this->id.',\''.$amount.'\', \''.$this->multicurrency_amounts[$key].'\')'; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $invoice = new FactureFournisseur($this->db); $invoice->fetch($facid); // If we want to closed paid invoices - if ($closepaidinvoices) - { + if ($closepaidinvoices) { $paiement = $invoice->getSommePaiement(); //$creditnotes=$invoice->getSumCreditNotesUsed(); $creditnotes = 0; @@ -239,18 +229,20 @@ class PaiementFourn extends Paiement $deposits = 0; $alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT'); $remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT'); - if ($remaintopay == 0) - { + if ($remaintopay == 0) { $result = $invoice->setPaid($user, '', ''); - } else dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing."); + } else { + dol_syslog("Remain to pay for invoice ".$facid." not null. We do nothing."); + } } // Regenerate documents of invoices - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $newlang = ''; $outputlangs = $langs; - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $invoice->thirdparty->default_lang; + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { + $newlang = $invoice->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -271,11 +263,12 @@ class PaiementFourn extends Paiement } } - if (!$error) - { + if (!$error) { // Call trigger $result = $this->call_trigger('PAYMENT_SUPPLIER_CREATE', $user); - if ($result < 0) $error++; + if ($result < 0) { + $error++; + } // End call triggers } } else { @@ -288,8 +281,7 @@ class PaiementFourn extends Paiement $error++; } - if ($totalamount <> 0 && $error == 0) // On accepte les montants negatifs - { + if ($totalamount <> 0 && $error == 0) { // On accepte les montants negatifs $this->amount = $total; $this->total = $total; $this->multicurrency_amount = $mtotal; @@ -322,10 +314,8 @@ class PaiementFourn extends Paiement // Verifier si paiement porte pas sur une facture a l'etat payee // Si c'est le cas, on refuse la suppression $billsarray = $this->getBillsArray('paye=1'); - if (is_array($billsarray)) - { - if (count($billsarray)) - { + if (is_array($billsarray)) { + if (count($billsarray)) { $this->error = "ErrorCantDeletePaymentSharedWithPayedInvoice"; $this->db->rollback(); return -1; @@ -337,12 +327,10 @@ class PaiementFourn extends Paiement // Verifier si paiement ne porte pas sur ecriture bancaire rapprochee // Si c'est le cas, on refuse le delete - if ($bank_line_id) - { + if ($bank_line_id) { $accline = new AccountLine($this->db); $accline->fetch($bank_line_id); - if ($accline->rappro) - { + if ($accline->rappro) { $this->error = "ErrorCantDeletePaymentReconciliated"; $this->db->rollback(); return -3; @@ -353,41 +341,34 @@ class PaiementFourn extends Paiement $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn'; $sql .= ' WHERE fk_paiementfourn = '.$this->id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'paiementfourn'; $sql .= ' WHERE rowid = '.$this->id; $result = $this->db->query($sql); - if (!$result) - { + if (!$result) { $this->error = $this->db->error(); $this->db->rollback(); return -3; } // Supprimer l'ecriture bancaire si paiement lie a ecriture - if ($bank_line_id) - { + if ($bank_line_id) { $accline = new AccountLine($this->db); $result = $accline->fetch($bank_line_id); - if ($result > 0) // If result = 0, record not found, we don't try to delete - { + if ($result > 0) { // If result = 0, record not found, we don't try to delete $result = $accline->delete($user); } - if ($result < 0) - { + if ($result < 0) { $this->error = $accline->error; $this->db->rollback(); return -4; } } - if (!$notrigger) - { + if (!$notrigger) { // Appel des triggers $result = $this->call_trigger('PAYMENT_SUPPLIER_DELETE', $user); - if ($result < 0) - { + if ($result < 0) { $this->db->rollback(); return -1; } @@ -416,22 +397,18 @@ class PaiementFourn extends Paiement $sql .= ' WHERE c.rowid = '.$id; $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $num = $this->db->num_rows($resql); - if ($num) - { + if ($num) { $obj = $this->db->fetch_object($resql); $this->id = $obj->rowid; - if ($obj->fk_user_creat) - { + if ($obj->fk_user_creat) { $cuser = new User($this->db); $cuser->fetch($obj->fk_user_creat); $this->user_creation = $cuser; } - if ($obj->fk_user_modif) - { + if ($obj->fk_user_modif) { $muser = new User($this->db); $muser->fetch($obj->fk_user_modif); $this->user_modification = $muser; @@ -456,18 +433,18 @@ class PaiementFourn extends Paiement $sql = 'SELECT fk_facturefourn'; $sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf, '.MAIN_DB_PREFIX.'facture_fourn as f'; $sql .= ' WHERE pf.fk_facturefourn = f.rowid AND fk_paiementfourn = '.$this->id; - if ($filter) $sql .= ' AND '.$filter; + if ($filter) { + $sql .= ' AND '.$filter; + } dol_syslog(get_class($this).'::getBillsArray', LOG_DEBUG); $resql = $this->db->query($sql); - if ($resql) - { + if ($resql) { $i = 0; $num = $this->db->num_rows($resql); $billsarray = array(); - while ($i < $num) - { + while ($i < $num) { $obj = $this->db->fetch_object($resql); $billsarray[$i] = $obj->fk_facturefourn; $i++; @@ -564,20 +541,28 @@ class PaiementFourn extends Paiement $reg = array(); if (preg_match('/^\((.*)\)$/i', $text, $reg)) { // Label generique car entre parentheses. On l'affiche en le traduisant - if ($reg[1] == 'paiement') $reg[1] = 'Payment'; + if ($reg[1] == 'paiement') { + $reg[1] = 'Payment'; + } $text = $langs->trans($reg[1]); } $label = '<u>'.$langs->trans("Payment").'</u><br>'; $label .= '<strong>'.$langs->trans("Ref").':</strong> '.$text; - if ($this->datepaye ? $this->datepaye : $this->date) $label .= '<br><strong>'.$langs->trans("Date").':</strong> '.dol_print_date($this->datepaye ? $this->datepaye : $this->date, 'dayhour'); + if ($this->datepaye ? $this->datepaye : $this->date) { + $label .= '<br><strong>'.$langs->trans("Date").':</strong> '.dol_print_date($this->datepaye ? $this->datepaye : $this->date, 'dayhour'); + } $linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/paiement/card.php?id='.$this->id.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">'; $linkend = '</a>'; $result .= $linkstart; - if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; return $result; @@ -622,12 +607,15 @@ class PaiementFourn extends Paiement $langs->load("bills"); // Clean parameters (if not defined or using deprecated value) - if (empty($conf->global->SUPPLIER_PAYMENT_ADDON)) $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_bronan'; - elseif ($conf->global->SUPPLIER_PAYMENT_ADDON == 'brodator') $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_brodator'; - elseif ($conf->global->SUPPLIER_PAYMENT_ADDON == 'bronan') $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_bronan'; + if (empty($conf->global->SUPPLIER_PAYMENT_ADDON)) { + $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_bronan'; + } elseif ($conf->global->SUPPLIER_PAYMENT_ADDON == 'brodator') { + $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_brodator'; + } elseif ($conf->global->SUPPLIER_PAYMENT_ADDON == 'bronan') { + $conf->global->SUPPLIER_PAYMENT_ADDON = 'mod_supplier_payment_bronan'; + } - if (!empty($conf->global->SUPPLIER_PAYMENT_ADDON)) - { + if (!empty($conf->global->SUPPLIER_PAYMENT_ADDON)) { $mybool = false; $file = $conf->global->SUPPLIER_PAYMENT_ADDON.".php"; @@ -640,8 +628,7 @@ class PaiementFourn extends Paiement $dir = dol_buildpath($reldir."core/modules/supplier_payment/"); // Load file with numbering class (if found) - if (is_file($dir.$file) && is_readable($dir.$file)) - { + if (is_file($dir.$file) && is_readable($dir.$file)) { $mybool |= include_once $dir.$file; } } @@ -706,18 +693,15 @@ class PaiementFourn extends Paiement $langs->load("suppliers"); // Set the model on the model name to use - if (empty($modele)) - { - if (!empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF)) - { + if (empty($modele)) { + if (!empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF)) { $modele = $conf->global->SUPPLIER_PAYMENT_ADDON_PDF; } else { $modele = ''; // No default value. For supplier invoice, we allow to disable all PDF generation } } - if (empty($modele)) - { + if (empty($modele)) { return 0; } else { $modelpath = "core/modules/supplier_payment/doc/"; @@ -738,12 +722,9 @@ class PaiementFourn extends Paiement global $conf; $way = 'dolibarr'; - if (!empty($conf->multicurrency->enabled)) - { - foreach ($this->multicurrency_amounts as $value) - { - if (!empty($value)) // one value found then payment is in invoice currency - { + if (!empty($conf->multicurrency->enabled)) { + foreach ($this->multicurrency_amounts as $value) { + if (!empty($value)) { // one value found then payment is in invoice currency $way = 'customer'; break; } @@ -766,14 +747,11 @@ class PaiementFourn extends Paiement // phpcs:enable require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; - if (empty($force_thirdparty_id)) - { + if (empty($force_thirdparty_id)) { $billsarray = $this->getBillsArray(); // From payment, the fk_soc isn't available, we should load the first supplier invoice to get him - if (!empty($billsarray)) - { + if (!empty($billsarray)) { $supplier_invoice = new FactureFournisseur($this->db); - if ($supplier_invoice->fetch($billsarray[0]) > 0) - { + if ($supplier_invoice->fetch($billsarray[0]) > 0) { $force_thirdparty_id = $supplier_invoice->fk_soc; } } diff --git a/htdocs/fourn/commande/card.php b/htdocs/fourn/commande/card.php index 0aea652de68..76ef5de8af0 100644 --- a/htdocs/fourn/commande/card.php +++ b/htdocs/fourn/commande/card.php @@ -41,10 +41,12 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; -if (!empty($conf->supplier_proposal->enabled)) +if (!empty($conf->supplier_proposal->enabled)) { require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php'; -if (!empty($conf->product->enabled)) +} +if (!empty($conf->product->enabled)) { require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php'; +} if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; @@ -56,7 +58,9 @@ if (!empty($conf->variants->enabled)) { } $langs->loadLangs(array('admin', 'orders', 'sendings', 'companies', 'bills', 'propal', 'receptions', 'supplier_proposal', 'deliveries', 'products', 'stocks', 'productbatch')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); @@ -80,7 +84,9 @@ $datelivraison = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int' // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context @@ -93,20 +99,26 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Load object -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } $ret = $object->fetch_thirdparty(); - if ($ret < 0) dol_print_error($db, $object->error); -} elseif (!empty($socid) && $socid > 0) -{ + if ($ret < 0) { + dol_print_error($db, $object->error); + } +} elseif (!empty($socid) && $socid > 0) { $fourn = new Fournisseur($db); $ret = $fourn->fetch($socid); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } $object->socid = $fourn->id; $ret = $object->fetch_thirdparty(); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } } // Common permissions @@ -136,14 +148,13 @@ $permissiontoadd = $usercancreate; // Used by the include of actions_addupdated $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -156,67 +167,69 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once - if ($action == 'setref_supplier' && $usercancreate) - { + if ($action == 'setref_supplier' && $usercancreate) { $result = $object->setValueFrom('ref_supplier', GETPOST('ref_supplier', 'alpha'), '', null, 'text', '', $user, 'ORDER_SUPPLIER_MODIFY'); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Set incoterm - if ($action == 'set_incoterms' && $usercancreate) - { + if ($action == 'set_incoterms' && $usercancreate) { $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // payment conditions - if ($action == 'setconditions' && $usercancreate) - { + if ($action == 'setconditions' && $usercancreate) { $result = $object->setPaymentTerms(GETPOST('cond_reglement_id', 'int')); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // payment mode - if ($action == 'setmode' && $usercancreate) - { + if ($action == 'setmode' && $usercancreate) { $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); - } - - // Multicurrency Code - elseif ($action == 'setmulticurrencycode' && $usercancreate) { + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } elseif ($action == 'setmulticurrencycode' && $usercancreate) { + // Multicurrency Code $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha')); - } - - // Multicurrency rate - elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + // Multicurrency rate $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx'))); } // bank account - if ($action == 'setbankaccount' && $usercancreate) - { + if ($action == 'setbankaccount' && $usercancreate) { $result = $object->setBankAccount(GETPOST('fk_account', 'int')); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // date of delivery - if ($action == 'setdate_livraison' && $usercancreate) - { + if ($action == 'setdate_livraison' && $usercancreate) { $result = $object->setDeliveryDate($user, $datelivraison); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Set project - if ($action == 'classin' && $usercancreate) - { + if ($action == 'classin' && $usercancreate) { $result = $object->setProject($projectid); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } // Edit Thirdparty - if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $action == 'set_thirdparty' && $usercancreate && $object->statut == CommandeFournisseur::STATUS_DRAFT) - { + if (!empty($conf->global->MAIN_CAN_EDIT_SUPPLIER_ON_SUPPLIER_ORDER) && $action == 'set_thirdparty' && $usercancreate && $object->statut == CommandeFournisseur::STATUS_DRAFT) { $new_socid = GETPOST('new_socid', 'int'); if (!empty($new_socid) && $new_socid != $object->thirdparty->id) { $db->begin(); @@ -229,8 +242,9 @@ if (empty($reshook)) $res = $db->query($sql); - if (!$res) $db->rollback(); - else { + if (!$res) { + $db->rollback(); + } else { $db->commit(); // Replace prices for each lines by new supplier prices @@ -275,38 +289,44 @@ if (empty($reshook)) exit; } - if ($action == 'setremisepercent' && $usercancreate) - { + if ($action == 'setremisepercent' && $usercancreate) { $result = $object->set_remise($user, $_POST['remise_percent']); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } - if ($action == 'reopen') // no test on permission here, permission to use will depends on status - { - if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9))) - { - if ($object->statut == 1) $newstatus = 0; // Validated->Draft - elseif ($object->statut == 2) $newstatus = 0; // Approved->Draft - elseif ($object->statut == 3) $newstatus = 2; // Ordered->Approved - elseif ($object->statut == 4) $newstatus = 3; - elseif ($object->statut == 5) - { + if ($action == 'reopen') { // no test on permission here, permission to use will depends on status + if (in_array($object->statut, array(1, 2, 3, 4, 5, 6, 7, 9))) { + if ($object->statut == 1) { + $newstatus = 0; // Validated->Draft + } elseif ($object->statut == 2) { + $newstatus = 0; // Approved->Draft + } elseif ($object->statut == 3) { + $newstatus = 2; // Ordered->Approved + } elseif ($object->statut == 4) { + $newstatus = 3; + } elseif ($object->statut == 5) { //$newstatus=2; // Ordered // TODO Can we set it to submited ? //$newstatus=3; // Submited // TODO If there is at least one reception, we can set to Received->Received partially $newstatus = 4; // Received partially - } elseif ($object->statut == 6) $newstatus = 2; // Canceled->Approved - elseif ($object->statut == 7) $newstatus = 3; // Canceled->Process running - elseif ($object->statut == 9) $newstatus = 1; // Refused->Validated - else $newstatus = 2; + } elseif ($object->statut == 6) { + $newstatus = 2; // Canceled->Approved + } elseif ($object->statut == 7) { + $newstatus = 3; // Canceled->Process running + } elseif ($object->statut == 9) { + $newstatus = 1; // Refused->Validated + } else { + $newstatus = 2; + } //print "old status = ".$object->statut.' new status = '.$newstatus; $db->begin(); $result = $object->setStatus($user, $newstatus); - if ($result > 0) - { + if ($result > 0) { // Currently the "Re-open" also remove the billed flag because there is no button "Set unpaid" yet. $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; $sql .= ' SET billed = 0'; @@ -314,8 +334,7 @@ if (empty($reshook)) $resql = $db->query($sql); - if ($newstatus == 0) - { + if ($newstatus == 0) { $sql = 'UPDATE '.MAIN_DB_PREFIX.'commande_fournisseur'; $sql .= ' SET fk_user_approve = null, fk_user_approve2 = null, date_approve = null, date_approve2 = null'; $sql .= ' WHERE rowid = '.$object->id; @@ -338,8 +357,7 @@ if (empty($reshook)) /* * Classify supplier order as billed */ - if ($action == 'classifybilled' && $usercancreate) - { + if ($action == 'classifybilled' && $usercancreate) { $ret = $object->classifyBilled($user); if ($ret < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -347,8 +365,7 @@ if (empty($reshook)) } // Add a product line - if ($action == 'addline' && $usercancreate) - { + if ($action == 'addline' && $usercancreate) { $db->begin(); $langs->load('errors'); @@ -360,8 +377,7 @@ if (empty($reshook)) $date_start = dol_mktime(GETPOST('date_start'.$predef.'hour'), GETPOST('date_start'.$predef.'min'), GETPOST('date_start'.$predef.'sec'), GETPOST('date_start'.$predef.'month'), GETPOST('date_start'.$predef.'day'), GETPOST('date_start'.$predef.'year')); $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); $prod_entry_mode = GETPOST('prod_entry_mode'); - if ($prod_entry_mode == 'free') - { + if ($prod_entry_mode == 'free') { $idprod = 0; $price_ht = price2num(GETPOST('price_ht'), 'MU'); $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); @@ -386,28 +402,23 @@ if (empty($reshook)) } } - if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) - { + if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) { setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) - { + if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') // Unit price can be 0 but not '' - { + if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not '' setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) - { + if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); $error++; } - if (GETPOST('qty', 'int') == '') - { + if (GETPOST('qty', 'int') == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } @@ -426,51 +437,49 @@ if (empty($reshook)) } } - if ($prod_entry_mode != 'free' && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { + if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' $productsupplier = new ProductFournisseur($db); $idprod = 0; - if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') { + $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + } $reg = array(); - if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) - { + if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) { $idprod = $reg[1]; $res = $productsupplier->fetch($idprod); // Load product from its id // Call to init some price properties of $productsupplier // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price - if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) - { + if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) { $fksoctosearch = 0; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist - if ($productsupplier->fourn_socid != $socid) // The price we found is for another supplier, so we clear supplier price - { + if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price $productsupplier->ref_supplier = ''; } } else { $fksoctosearch = $object->thirdparty->id; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist } - } elseif (GETPOST('idprodfournprice', 'alpha') > 0) - { + } elseif (GETPOST('idprodfournprice', 'alpha') > 0) { $qtytosearch = $qty; // Just to see if a price exists for the quantity. Not used to found vat. //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch); $res = $productsupplier->fetch($idprod); } - if ($idprod > 0) - { + if ($idprod > 0) { $label = $productsupplier->label; // Define output language if (!empty($conf->global->MAIN_MULTILANGS) && !empty($conf->global->PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE)) { $outputlangs = $langs; $newlang = ''; - if (empty($newlang) && GETPOST('lang_id', 'aZ09')) + if (empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if (empty($newlang)) + } + if (empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -489,8 +498,12 @@ if (empty($reshook)) $product_desc=''; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; - if (!empty($product_desc) && trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) { + $desc = $product_desc; + } + if (!empty($product_desc) && trim($product_desc) != trim($desc)) { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } $type = $productsupplier->type; if ($price_ht != '' || $price_ht_devise != '') { @@ -514,11 +527,15 @@ if (empty($reshook)) $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); - if (empty($pu)) $pu = 0; // If pu is '' or null, we force to have a numeric value + if (empty($pu)) { + $pu = 0; // If pu is '' or null, we force to have a numeric value + } $result = $object->addline( $desc, @@ -545,22 +562,19 @@ if (empty($reshook)) 0 ); } - if ($idprod == -99 || $idprod == 0) - { + if ($idprod == -99 || $idprod == 0) { // Product not selected $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors'); } - if ($idprod == -1) - { + if ($idprod == -1) { // Quantity too low $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); } - } elseif (empty($error)) // $price_ht is already set - { + } elseif (empty($error)) { // $price_ht is already set $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); $tva_tx = str_replace('*', '', $tva_tx); $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); @@ -578,8 +592,7 @@ if (empty($reshook)) $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty); - if ($price_ht !== '') - { + if ($price_ht !== '') { $pu_ht = price2num($price_ht, 'MU'); // $pu_ht must be rounded according to settings } else { $pu_ttc = price2num(GETPOST('price_ttc'), 'MU'); @@ -592,19 +605,21 @@ if (empty($reshook)) } //print "xx".$tva_tx; exit; - if (!$error && $result > 0) - { + if (!$error && $result > 0) { $db->commit(); $ret = $object->fetch($object->id); // Reload to get new records // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -613,7 +628,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } unset($_POST ['prod_entry_mode']); @@ -658,17 +675,17 @@ if (empty($reshook)) /* * Updating a line in the order */ - if ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) - { + if ($action == 'updateline' && $usercancreate && !GETPOST('cancel', 'alpha')) { $db->begin(); $vat_rate = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - if ($lineid) - { + if ($lineid) { $line = new CommandeFournisseurLigne($db); $res = $line->fetch($lineid); - if (!$res) dol_print_error($db); + if (!$res) { + dol_print_error($db); + } } $productsupplier = new ProductFournisseur($db); @@ -692,14 +709,12 @@ if (empty($reshook)) $localtax1_rate = get_localtax($vat_rate, 1, $mysoc, $object->thirdparty); $localtax2_rate = get_localtax($vat_rate, 2, $mysoc, $object->thirdparty); - if (GETPOST('price_ht') != '') - { + if (GETPOST('price_ht') != '') { $price_base_type = 'HT'; $ht = price2num(GETPOST('price_ht')); } else { $vatratecleaned = $vat_rate; - if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) // If vat is "xx (yy)" - { + if (preg_match('/^(.*)\s*\((.*)\)$/', $vat_rate, $reg)) { // If vat is "xx (yy)" $vatratecleaned = trim($reg[1]); $vatratecode = $reg[2]; } @@ -769,15 +784,17 @@ if (empty($reshook)) unset($_POST['date_endmonth']); unset($_POST['date_endyear']); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -786,7 +803,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } $db->commit(); @@ -799,20 +818,20 @@ if (empty($reshook)) } // Remove a product line - if ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) - { + if ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { $db->begin(); $result = $object->deleteline($lineid); - if ($result > 0) - { + if ($result > 0) { // Define output language $outputlangs = $langs; $newlang = ''; - if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) + if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) { $newlang = GETPOST('lang_id', 'aZ09'); - if ($conf->global->MAIN_MULTILANGS && empty($newlang)) + } + if ($conf->global->MAIN_MULTILANGS && empty($newlang)) { $newlang = $object->thirdparty->default_lang; + } if (!empty($newlang)) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang($newlang); @@ -839,21 +858,22 @@ if (empty($reshook)) } // Validate - if ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) - { + if ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { $db->begin(); $object->date_commande = dol_now(); $result = $object->valid($user); - if ($result >= 0) - { + if ($result >= 0) { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -873,8 +893,7 @@ if (empty($reshook)) } // If we have permission, and if we don't need to provide the idwarehouse, we go directly on approved step - if (!$error && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $usercanapprove && !(!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) - { + if (!$error && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE) && $usercanapprove && !(!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $object->hasProductsOrServices(1))) { $action = 'confirm_approve'; // can make standard or first level approval also if permission is set } @@ -885,41 +904,39 @@ if (empty($reshook)) } } - if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $usercanapprove) - { + if (($action == 'confirm_approve' || $action == 'confirm_approve2') && $confirm == 'yes' && $usercanapprove) { $db->begin(); $idwarehouse = GETPOST('idwarehouse', 'int'); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { - $qualified_for_stock_change = $object->hasProductsOrServices(2); + 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 = $object->hasProductsOrServices(1); } // Check parameters - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER - { - if (!$idwarehouse || $idwarehouse == -1) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) { // warning name of option should be STOCK_CALCULATE_ON_SUPPLIER_APPROVE_ORDER + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; } } - if (!$error) - { + if (!$error) { $result = $object->approve($user, $idwarehouse, ($action == 'confirm_approve2' ? 1 : 0)); - if ($result > 0) - { + if ($result > 0) { 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 ($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); @@ -942,11 +959,9 @@ if (empty($reshook)) } } - if ($action == 'confirm_refuse' && $confirm == 'yes' && $usercanapprove) - { + if ($action == 'confirm_refuse' && $confirm == 'yes' && $usercanapprove) { $result = $object->refuse($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); exit; } else { @@ -964,19 +979,20 @@ if (empty($reshook)) } } - if ($action == 'confirm_commande' && $confirm == 'yes' && $usercanorder) - { + if ($action == 'confirm_commande' && $confirm == 'yes' && $usercanorder) { $db->begin(); $result = $object->commande($user, GETPOST("datecommande"), GETPOST("methode", 'int'), GETPOST('comment', 'alphanohtml')); - if ($result > 0) - { - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + if ($result > 0) { + 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 ($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); @@ -1000,11 +1016,9 @@ if (empty($reshook)) } - if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) - { + if ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".DOL_URL_ROOT.'/fourn/commande/list.php?restore_lastsearch_values=1'); exit; } else { @@ -1013,19 +1027,15 @@ if (empty($reshook)) } // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) - { - if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) - { + if ($action == 'confirm_clone' && $confirm == 'yes' && $usercancreate) { + if (1 == 0 && !GETPOST('clone_content') && !GETPOST('clone_receivers')) { setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors'); } else { - if ($object->id > 0) - { + if ($object->id > 0) { $orig = clone $object; $result = $object->createFromClone($user, $socid); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -1038,22 +1048,18 @@ if (empty($reshook)) } // Set status of reception (complete, partial, ...) - if ($action == 'livraison' && $usercanreceived) - { + if ($action == 'livraison' && $usercanreceived) { $db->begin(); - if (GETPOST("type") != '') - { + if (GETPOST("type") != '') { $date_liv = dol_mktime(GETPOST('rehour'), GETPOST('remin'), GETPOST('resec'), GETPOST("remonth"), GETPOST("reday"), GETPOST("reyear")); $result = $object->Livraison($user, $date_liv, GETPOST("type"), GETPOST("comment")); // GETPOST("type") is 'tot', 'par', 'nev', 'can' - if ($result > 0) - { + if ($result > 0) { $langs->load("deliveries"); setEventMessages($langs->trans("DeliveryStateSaved"), null); $action = ''; - } elseif ($result == -3) - { + } elseif ($result == -3) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } else { @@ -1072,11 +1078,9 @@ if (empty($reshook)) } } - if ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanorder) - { + if ($action == 'confirm_cancel' && $confirm == 'yes' && $usercanorder) { $result = $object->cancel($user); - if ($result > 0) - { + if ($result > 0) { header("Location: ".$_SERVER["PHP_SELF"]."?id=".$object->id); exit; } else { @@ -1099,48 +1103,44 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $object->insertExtraFields('ORDER_SUPPLIER_MODIFY'); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } /* * Create an order */ - if ($action == 'add' && $usercancreate) - { - $error = 0; + if ($action == 'add' && $usercancreate) { + $error = 0; $selectedLines = GETPOST('toselect', 'array'); - if ($socid < 1) - { + if ($socid < 1) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors'); $action = 'create'; $error++; } - if (!$error) - { + if (!$error) { $db->begin(); // Creation commande @@ -1160,23 +1160,20 @@ if (empty($reshook)) $object->fk_project = GETPOST('projectid'); // Fill array 'array_options' with data from add form - if (!$error) - { + if (!$error) { $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; - } + if ($ret < 0) { + $error++; + } + } - if (!$error) - { - // If creation from another object of another module (Example: origin=propal, originid=1) - if (!empty($origin) && !empty($originid)) - { - if ($origin == 'propal' || $origin == 'proposal') - { + if (!$error) { + // If creation from another object of another module (Example: origin=propal, originid=1) + if (!empty($origin) && !empty($originid)) { + if ($origin == 'propal' || $origin == 'proposal') { $classname = 'Propal'; $element = 'comm/propal'; $subelement = 'propal'; - } elseif ($origin == 'order' || $origin == 'commande') - { + } elseif ($origin == 'order' || $origin == 'commande') { $classname = 'Commande'; $element = $subelement = 'commande'; } else { @@ -1196,23 +1193,20 @@ if (empty($reshook)) } $id = $object->create($user); - if ($id > 0) - { + if ($id > 0) { dol_include_once('/'.$element.'/class/'.$subelement.'.class.php'); $srcobject = new $classname($db); dol_syslog("Try to find source object origin=".$object->origin." originid=".$object->origin_id." to add lines"); $result = $srcobject->fetch($object->origin_id); - if ($result > 0) - { + if ($result > 0) { $tmpdate = ($srcobject->delivery_date ? $srcobject->delivery_date : $srcobject->date_livraison); $object->setDeliveryDate($user, $tmpdate); $object->set_id_projet($user, $srcobject->fk_project); $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } @@ -1220,10 +1214,10 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { - if (empty($lines[$i]->subprice) || $lines[$i]->qty <= 0 || !in_array($lines[$i]->id, $selectedLines)) + for ($i = 0; $i < $num; $i++) { + if (empty($lines[$i]->subprice) || $lines[$i]->qty <= 0 || !in_array($lines[$i]->id, $selectedLines)) { continue; + } $label = (!empty($lines[$i]->label) ? $lines[$i]->label : ''); $desc = (!empty($lines[$i]->desc) ? $lines[$i]->desc : $lines[$i]->product_desc); @@ -1235,20 +1229,17 @@ if (empty($reshook)) } // Extrafields - if (method_exists($lines[$i], 'fetch_optionals')) // For avoid conflicts if - { + if (method_exists($lines[$i], 'fetch_optionals')) { // For avoid conflicts if $lines[$i]->fetch_optionals(); $array_option = $lines[$i]->array_options; } $ref_supplier = ''; $product_fourn_price_id = 0; - if ($origin == "commande") - { + if ($origin == "commande") { $productsupplier = new ProductFournisseur($db); $result = $productsupplier->find_min_price_product_fournisseur($lines[$i]->fk_product, $lines[$i]->qty, $srcobject->socid); - if ($result > 0) - { + if ($result > 0) { $ref_supplier = $productsupplier->ref_supplier; $product_fourn_price_id = $productsupplier->product_fourn_price_id; } @@ -1259,8 +1250,7 @@ if (empty($reshook)) $tva_tx = $lines[$i]->tva_tx; - if ($origin == "commande") - { + if ($origin == "commande") { $soc = new societe($db); $soc->fetch($socid); $tva_tx = get_default_tva($soc, $mysoc, $lines[$i]->fk_product, $product_fourn_price_id); @@ -1309,8 +1299,9 @@ if (empty($reshook)) $parameters = array('objFrom' => $srcobject); $reshook = $hookmanager->executeHooks('createFrom', $parameters, $object, $action); // Note that $action and $object may have been - if ($reshook < 0) + if ($reshook < 0) { $error++; + } } else { setEventMessages($srcobject->error, $srcobject->errors, 'errors'); $error++; @@ -1320,17 +1311,15 @@ if (empty($reshook)) $error++; } } else { - $id = $object->create($user); - if ($id < 0) - { + $id = $object->create($user); + if ($id < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } } - if ($error) - { + if ($error) { $langs->load("errors"); $db->rollback(); $action = 'create'; @@ -1343,8 +1332,7 @@ if (empty($reshook)) } } - if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && !GETPOST('cancel', 'alpha')) - { + if ($action == 'webservice' && GETPOST('mode', 'alpha') == "send" && !GETPOST('cancel', 'alpha')) { $ws_url = $object->thirdparty->webservices_url; $ws_key = $object->thirdparty->webservices_key; $ws_user = GETPOST('ws_user', 'alpha'); @@ -1382,13 +1370,11 @@ if (empty($reshook)) //Prepare the order lines from order $order_lines = array(); - foreach ($object->lines as $line) - { + foreach ($object->lines as $line) { $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $line->ref_supplier); $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); - if ($result_product["result"]["result_code"] == "OK") - { + if ($result_product["result"]["result_code"] == "OK") { $order_lines[] = array( 'desc' => $line->product_desc, 'type' => $line->product_type, @@ -1419,11 +1405,9 @@ if (empty($reshook)) $ws_parameters = array('authentication'=>$ws_authentication, 'order' => $order); $result_order = $soapclient_order->call("createOrder", $ws_parameters, $ws_ns, ''); - if (empty($result_order["result"]["result_code"])) //No result, check error str - { + if (empty($result_order["result"]["result_code"])) { //No result, check error str setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors'); - } elseif ($result_order["result"]["result_code"] != "OK") //Something went wrong - { + } elseif ($result_order["result"]["result_code"] != "OK") { //Something went wrong setEventMessages($langs->trans("SOAPError")." '".$result_order["result"]["result_code"]."' - '".$result_order["result"]["result_label"]."'", null, 'errors'); } else { setEventMessages($langs->trans("RemoteOrderRef")." ".$result_order["ref"], null, 'mesgs'); @@ -1431,45 +1415,33 @@ if (empty($reshook)) } } - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) - { - if ($action == 'addcontact') - { - if ($object->id > 0) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { + if ($action == 'addcontact') { + if ($object->id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // bascule du statut d'un contact - elseif ($action == 'swapstatut' && $object->id > 0) - { + } elseif ($action == 'swapstatut' && $object->id > 0) { + // bascule du statut d'un contact $result = $object->swapContactStatus(GETPOST('ligne')); - } - - // Efface un contact - elseif ($action == 'deletecontact' && $object->id > 0) - { + } elseif ($action == 'deletecontact' && $object->id > 0) { + // Efface un contact $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -1488,15 +1460,16 @@ $form = new Form($db); $formfile = new FormFile($db); $formorder = new FormOrder($db); $productstatic = new Product($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $langs->trans("Order"), $help_url); $now = dol_now(); -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans('NewOrderSupplier'), '', 'supplier_order'); dol_htmloutput_events(); @@ -1504,14 +1477,12 @@ if ($action == 'create') $currency_code = $conf->currency; $societe = ''; - if ($socid > 0) - { + if ($socid > 0) { $societe = new Societe($db); $societe->fetch($socid); } - if (!empty($origin) && !empty($originid)) - { + if (!empty($origin) && !empty($originid)) { // Parse element/subelement (ex: project_task) $element = $subelement = $origin; $regs = array(); @@ -1520,12 +1491,10 @@ if ($action == 'create') $subelement = $regs[2]; } - if ($origin == 'propal' || $origin == 'proposal') - { + if ($origin == 'propal' || $origin == 'proposal') { $classname = 'Propal'; $element = 'comm/propal'; $subelement = 'propal'; - } elseif ($origin == 'order' || $origin == 'commande') - { + } elseif ($origin == 'order' || $origin == 'commande') { $classname = 'Commande'; $element = $subelement = 'commande'; } else { @@ -1538,8 +1507,9 @@ if ($action == 'create') $objectsrc = new $classname($db); $objectsrc->fetch($originid); - if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) + if (empty($objectsrc->lines) && method_exists($objectsrc, 'fetch_lines')) { $objectsrc->fetch_lines(); + } $objectsrc->fetch_thirdparty(); // Replicate extrafields @@ -1562,10 +1532,13 @@ if ($action == 'create') $datedelivery = (!empty($objectsrc->date_livraison) ? $objectsrc->date_livraison : (!empty($objectsrc->delivery_date) ? $objectsrc->delivery_date : '')); - if (!empty($conf->multicurrency->enabled)) - { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($conf->multicurrency->enabled)) { + if (!empty($objectsrc->multicurrency_code)) { + $currency_code = $objectsrc->multicurrency_code; + } + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) { + $currency_tx = $objectsrc->multicurrency_tx; + } } $note_private = $object->getDefaultCreateValueFor('note_private', (!empty($objectsrc->note_private) ? $objectsrc->note_private : null)); @@ -1577,15 +1550,21 @@ if ($action == 'create') $cond_reglement_id = $societe->cond_reglement_supplier_id; $mode_reglement_id = $societe->mode_reglement_supplier_id; - if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) $currency_code = $societe->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) { + $currency_code = $societe->multicurrency_code; + } $note_private = $object->getDefaultCreateValueFor('note_private'); $note_public = $object->getDefaultCreateValueFor('note_public'); } // If not defined, set default value from constant - if (empty($cond_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID)) $cond_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID; - if (empty($mode_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID)) $mode_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID; + if (empty($cond_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID)) { + $cond_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_TERM_ID; + } + if (empty($mode_reglement_id) && !empty($conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID)) { + $mode_reglement_id = $conf->global->SUPPLIER_ORDER_DEFAULT_PAYMENT_MODE_ID; + } print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; @@ -1594,7 +1573,9 @@ if ($action == 'create') print '<input type="hidden" name="remise_percent" value="'.$soc->remise_supplier_percent.'">'; print '<input type="hidden" name="origin" value="'.$origin.'">'; print '<input type="hidden" name="originid" value="'.$originid.'">'; - if (!empty($currency_tx)) print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">'; + if (!empty($currency_tx)) { + print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">'; + } print dol_get_fiche_head(''); @@ -1607,15 +1588,13 @@ if ($action == 'create') print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>'; print '<td>'; - if ($socid > 0) - { + if ($socid > 0) { print $societe->getNomUrl(1); print '<input type="hidden" name="socid" value="'.$socid.'">'; } else { print img_picto('', 'company').$form->select_company((empty($socid) ? '' : $socid), 'socid', 's.fournisseur=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); // reload page to retrieve customer informations - if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) - { + if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) { print '<script> $(document).ready(function() { $("#socid").change(function() { @@ -1630,8 +1609,7 @@ if ($action == 'create') } print '</td>'; - if ($societe->id > 0) - { + if ($societe->id > 0) { // Discounts for third party print '<tr><td>'.$langs->trans('Discounts').'</td><td>'; @@ -1665,13 +1643,14 @@ if ($action == 'create') print '</td>'; print '<td>'; $usehourmin = 0; - if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 1; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) { + $usehourmin = 1; + } print $form->selectDate($datelivraison ? $datelivraison : -1, 'liv_', $usehourmin, $usehourmin, '', "set"); print '</td></tr>'; // Bank Account - if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && !empty($conf->banque->enabled)) - { + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && !empty($conf->banque->enabled)) { $langs->load("bank"); print '<tr><td>'.$langs->trans('BankAccount').'</td><td>'; print img_picto('', 'bank_account', 'class="paddingrightonly"'); @@ -1680,8 +1659,7 @@ if ($action == 'create') } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load('projects'); @@ -1692,8 +1670,7 @@ if ($action == 'create') } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { $fkincoterms = (!empty($object->fk_incoterms) ? $object->fk_incoterms : ($socid > 0 ? $societe->fk_incoterms : '')); $locincoterms = (!empty($object->location_incoterms) ? $object->location_incoterms : ($socid > 0 ? $societe->location_incoterms : '')); print '<tr>'; @@ -1704,8 +1681,7 @@ if ($action == 'create') } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr>'; print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>'; print '<td class="maxwidthonsmartphone">'; @@ -1742,20 +1718,17 @@ if ($action == 'create') print '<tr><td>'.$langs->trans($newclassname).'</td><td>'.$objectsrc->getNomUrl(1).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>"; - if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) // Localtax1 RE - { + if ($mysoc->localtax1_assuj == "1" || $objectsrc->total_localtax1 != 0) { // Localtax1 RE print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>"; } - if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) // Localtax2 IRPF - { + if ($mysoc->localtax2_assuj == "1" || $objectsrc->total_localtax2 != 0) { // Localtax2 IRPF print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>"; } print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>"; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva).'</td></tr>'; print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc).'</td></tr>'; @@ -1767,8 +1740,7 @@ if ($action == 'create') $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } @@ -1786,8 +1758,7 @@ if ($action == 'create') // Show origin lines - if (!empty($origin) && !empty($originid) && is_object($objectsrc)) - { + if (!empty($origin) && !empty($originid) && is_object($objectsrc)) { $title = $langs->trans('ProductsAndServices'); print load_fiche_titre($title); @@ -1803,7 +1774,9 @@ if ($action == 'create') $societe = new Fournisseur($db); $result = $societe->fetch($object->socid); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } $author = new User($db); $author->fetch($object->user_author_id); @@ -1820,14 +1793,12 @@ if ($action == 'create') $formconfirm = ''; // Confirmation de la suppression de la commande - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteOrder'), $langs->trans('ConfirmDeleteOrder'), 'confirm_delete', '', 0, 2); } // Clone confirmation - if ($action == 'clone') - { + if ($action == 'clone') { // Create an array for form $formquestion = array( array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.fournisseur=1)')) @@ -1837,24 +1808,22 @@ if ($action == 'create') } // Confirmation de la validation - if ($action == 'valid') - { + if ($action == 'valid') { $object->date_commande = dol_now(); // We check if number is temporary number - if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) // empty should not happened, but when it occurs, the test save life - { + if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) { // empty should not happened, but when it occurs, the test save life $newref = $object->getNextNumRef($object->thirdparty); - } else $newref = $object->ref; + } else { + $newref = $object->ref; + } - if ($newref < 0) - { + if ($newref < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = ''; } else { $text = $langs->trans('ConfirmValidateOrder', $newref); - if (!empty($conf->notification->enabled)) - { + if (!empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $text .= '<br>'; @@ -1866,24 +1835,23 @@ if ($action == 'create') } // Confirm approval - if ($action == 'approve' || $action == 'approve2') - { + if ($action == 'approve' || $action == 'approve2') { $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { $qualified_for_stock_change = $object->hasProductsOrServices(1); } $formquestion = array(); - if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) && $qualified_for_stock_change) { $langs->load("stocks"); require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $forcecombo = 0; - if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + if ($conf->browser->name == 'ie') { + $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + } $formquestion = array( //'text' => $langs->trans("ConfirmClone"), //array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), @@ -1892,8 +1860,7 @@ if ($action == 'create') ); } $text = $langs->trans("ConfirmApproveThisOrder", $object->ref); - if (!empty($conf->notification->enabled)) - { + if (!empty($conf->notification->enabled)) { require_once DOL_DOCUMENT_ROOT.'/core/class/notify.class.php'; $notify = new Notify($db); $text .= '<br>'; @@ -1904,34 +1871,33 @@ if ($action == 'create') } // Confirmation de la desapprobation - if ($action == 'refuse') - { + if ($action == 'refuse') { $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("DenyingThisOrder"), $langs->trans("ConfirmDenyingThisOrder", $object->ref), "confirm_refuse", '', 0, 1); } // Confirmation de l'annulation - if ($action == 'cancel') - { + if ($action == 'cancel') { $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=$object->id", $langs->trans("Cancel"), $langs->trans("ConfirmCancelThisOrder", $object->ref), "confirm_cancel", '', 0, 1); } // Confirmation de l'envoi de la commande - if ($action == 'commande') - { + if ($action == 'commande') { $date_com = dol_mktime(GETPOST('rehour'), GETPOST('remin'), GETPOST('resec'), GETPOST("remonth"), GETPOST("reday"), GETPOST("reyear")); $formconfirm = $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id."&datecommande=".$date_com."&methode=".$_POST["methodecommande"]."&comment=".urlencode($_POST["comment"]), $langs->trans("MakeOrder"), $langs->trans("ConfirmMakeOrder", dol_print_date($date_com, 'day')), "confirm_commande", '', 0, 2); } // Confirmation to delete line - if ($action == 'ask_deleteline') - { + if ($action == 'ask_deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -1961,7 +1927,9 @@ if ($action == 'create') $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=edit_thirdparty&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetThirdParty')).'</a>'; } $morehtmlref .= ' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/commande/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherOrders").'</a>)'; + } } // Project @@ -1969,8 +1937,9 @@ if ($action == 'create') $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; if ($usercancreate) { - if ($action != 'classify') + if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; + } if ($action == 'classify') { //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); $morehtmlref .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -2007,8 +1976,7 @@ if ($action == 'create') print '<table class="border tableforfield centpercent">'; // Date - if ($object->methode_commande_id > 0) - { + if ($object->methode_commande_id > 0) { print '<tr><td class="titlefield">'.$langs->trans("Date").'</td><td>'; print $object->date_commande ? dol_print_date($object->date_commande, $usehourmin) : ''; if ($object->hasDelay() && !empty($object->date_delivery) && !empty($object->date_commande)) { @@ -2016,8 +1984,7 @@ if ($action == 'create') } print "</td></tr>"; - if ($object->methode_commande) - { + if ($object->methode_commande) { print '<tr><td>'.$langs->trans("Method").'</td><td>'.$object->getInputMethod().'</td></tr>'; } } @@ -2056,11 +2023,12 @@ if ($action == 'create') print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">'; print $langs->trans('PaymentConditions'); print '<td>'; - if ($action != 'editconditions') print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>'; + if ($action != 'editconditions') { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editconditions') - { + if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none'); @@ -2074,11 +2042,12 @@ if ($action == 'create') print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">'; print $langs->trans('PaymentMode'); print '</td>'; - if ($action != 'editmode') print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>'; + if ($action != 'editmode') { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->trans('SetMode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1); } else { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); @@ -2086,16 +2055,16 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print '<tr>'; print '<td>'; print '<table class="nobordernopadding centpercent"><tr><td>'; print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) + if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; if ($action == 'editmulticurrencycode') { @@ -2106,16 +2075,16 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency rate - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { print '<tr>'; print '<td>'; print '<table class="nobordernopadding centpercent"><tr>'; print '<td>'; print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) + if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { @@ -2136,14 +2105,14 @@ if ($action == 'create') } // Bank Account - if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && !empty($conf->banque->enabled)) - { + if (!empty($conf->global->BANK_ASK_PAYMENT_BANK_DURING_SUPPLIER_ORDER) && !empty($conf->banque->enabled)) { print '<tr><td class="nowrap">'; print '<table class="nobordernopadding centpercent"><tr><td class="nowrap">'; print $langs->trans('BankAccount'); print '<td>'; - if ($action != 'editbankaccount' && $usercancreate) + if ($action != 'editbankaccount' && $usercancreate) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; if ($action == 'editbankaccount') { @@ -2166,22 +2135,27 @@ if ($action == 'create') print '<table class="nobordernopadding centpercent"><tr><td>'; print $langs->trans('DateDeliveryPlanned'); print '</td>'; - if ($action != 'editdate_livraison') print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'</a></td>'; + if ($action != 'editdate_livraison') { + print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDeliveryDate'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td>'; - if ($action == 'editdate_livraison') - { + if ($action == 'editdate_livraison') { print '<form name="setdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="setdate_livraison">'; $usehourmin = 0; - if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 1; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) { + $usehourmin = 1; + } print $form->selectDate($object->delivery_date ? $object->delivery_date : -1, 'liv_', $usehourmin, $usehourmin, '', "setdate_livraison"); print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">'; print '</form>'; } else { $usehourmin = 'day'; - if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) $usehourmin = 'dayhour'; + if (!empty($conf->global->SUPPLIER_ORDER_USE_HOUR_FOR_DELIVERY_DATE)) { + $usehourmin = 'dayhour'; + } print $object->delivery_date ? dol_print_date($object->delivery_date, $usehourmin) : '&nbsp;'; if ($object->hasDelay() && !empty($object->delivery_date)) { print ' '.img_picto($langs->trans("Late").' : '.$object->showDelay(), "warning"); @@ -2190,19 +2164,20 @@ if ($action == 'create') print '</td></tr>'; // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr><td>'; print '<table class="nobordernopadding centpercent"><tr><td>'; print $langs->trans('IncotermLabel'); print '<td><td class="right">'; - if ($usercancreate) print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; - else print '&nbsp;'; + if ($usercancreate) { + print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/commande/card.php?id='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; + } else { + print '&nbsp;'; + } print '</td></tr></table>'; print '</td>'; print '<td>'; - if ($action != 'editincoterm') - { + if ($action != 'editincoterm') { print $form->textwithpicto(dol_escape_htmltag($object->display_incoterms()), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -2222,8 +2197,7 @@ if ($action == 'create') print '<table class="border tableforfield centpercent">'; - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { // Multicurrency Amount HT print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>'; print '<td class="nowrap">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; @@ -2254,14 +2228,12 @@ if ($action == 'create') print '</tr>'; // Amount Local Taxes - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) //Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>'; print '<td>'.price($object->total_localtax1, '', $langs, 1, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) //Localtax2 - { + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>'; print '<td>'.price($object->total_localtax2, '', $langs, 1, -1, -1, $conf->currency).'</td>'; print '</tr>'; @@ -2275,7 +2247,7 @@ if ($action == 'create') // Margin Infos /*if (! empty($conf->margin->enabled)) { - $formmargin->displayMarginInfos($object); + $formmargin->displayMarginInfos($object); }*/ @@ -2285,15 +2257,13 @@ if ($action == 'create') print '<div class="clearboth"></div><br>'; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; $title = $langs->trans('ContactsAddresses'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $blocname = 'notes'; $title = $langs->trans('Notes'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; @@ -2324,19 +2294,20 @@ if ($action == 'create') global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax; $forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1; $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum. - if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) $senderissupplier = 1; + if (!empty($conf->global->SUPPLIER_ORDER_WITH_PREDEFINED_PRICES_ONLY)) { + $senderissupplier = 1; + } // Show object lines - if (!empty($object->lines)) + if (!empty($object->lines)) { $ret = $object->printObjectLines($action, $societe, $mysoc, $lineid, 1); + } $num = count($object->lines); // Form to add new line - if ($object->statut == CommandeFournisseur::STATUS_DRAFT && $usercancreate) - { - if ($action != 'editline') - { + if ($object->statut == CommandeFournisseur::STATUS_DRAFT && $usercancreate) { + if ($action != 'editline') { // Add free products/services $object->formAddObjectLine(1, $societe, $mysoc); @@ -2354,24 +2325,22 @@ if ($action == 'create') * Boutons actions */ - if ($user->socid == 0 && $action != 'editline' && $action != 'delete') - { + if ($user->socid == 0 && $action != 'editline' && $action != 'delete') { print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { $object->fetchObjectLinked(); // Links are used to show or not button, so we load them now. // Validate - if ($object->statut == 0 && $num > 0) - { - if ($usercanvalidate) - { + if ($object->statut == 0 && $num > 0) { + if ($usercanvalidate) { $tmpbuttonlabel = $langs->trans('Validate'); - if ($usercanapprove && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE)) $tmpbuttonlabel = $langs->trans("ValidateAndApprove"); + if ($usercanapprove && empty($conf->global->SUPPLIER_ORDER_NO_DIRECT_APPROVE)) { + $tmpbuttonlabel = $langs->trans("ValidateAndApprove"); + } print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid">'; print $tmpbuttonlabel; @@ -2385,21 +2354,16 @@ if ($action == 'create') }*/ // Modify - if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) - { - if ($usercanorder) - { + if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) { + if ($usercanorder) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Modify").'</a>'; } } // Approve - if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) - { - if ($usercanapprove) - { - if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED && !empty($object->user_approve_id)) - { + if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) { + if ($usercanapprove) { + if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED && !empty($object->user_approve_id)) { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("FirstApprovalAlreadyDone")).'">'.$langs->trans("ApproveOrder").'</a>'; } else { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=approve">'.$langs->trans("ApproveOrder").'</a>'; @@ -2410,14 +2374,10 @@ if ($action == 'create') } // Second approval (if option SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED is set) - if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) - { - if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) - { - if ($usercanapprovesecond) - { - if (!empty($object->user_approve_id2)) - { + if (!empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) && $object->total_ht >= $conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED) { + if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) { + if ($usercanapprovesecond) { + if (!empty($object->user_approve_id2)) { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("SecondApprovalAlreadyDone")).'">'.$langs->trans("Approve2Order").'</a>'; } else { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=approve2">'.$langs->trans("Approve2Order").'</a>'; @@ -2429,10 +2389,8 @@ if ($action == 'create') } // Refuse - if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) - { - if ($usercanapprove || $usercanapprovesecond) - { + if ($object->statut == CommandeFournisseur::STATUS_VALIDATED) { + if ($usercanapprove || $usercanapprovesecond) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=refuse">'.$langs->trans("RefuseOrder").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->trans("NotAllowed")).'">'.$langs->trans("RefuseOrder").'</a>'; @@ -2441,51 +2399,43 @@ if ($action == 'create') // Send if (empty($user->socid)) { - if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED, 3, 4, 5)) || !empty($conf->global->SUPPLIER_ORDER_SENDBYEMAIL_FOR_ALL_STATUS)) - { - if ($usercanorder) - { + if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED, 3, 4, 5)) || !empty($conf->global->SUPPLIER_ORDER_SENDBYEMAIL_FOR_ALL_STATUS)) { + if ($usercanorder) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a>'; } } } // Reopen - if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED))) - { + if (in_array($object->statut, array(CommandeFournisseur::STATUS_ACCEPTED))) { $buttonshown = 0; - if (!$buttonshown && $usercanapprove) - { + if (!$buttonshown && $usercanapprove) { if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) - || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id)) - { + || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER_ONLY) && $user->id == $object->user_approve_id)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Disapprove").'</a>'; $buttonshown++; } } - if (!$buttonshown && $usercanapprovesecond && !empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) - { + if (!$buttonshown && $usercanapprovesecond && !empty($conf->global->SUPPLIER_ORDER_3_STEPS_TO_BE_APPROVED)) { if (empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) - || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2)) - { + || (!empty($conf->global->SUPPLIER_ORDER_REOPEN_BY_APPROVER2_ONLY) && $user->id == $object->user_approve_id2)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("Disapprove").'</a>'; } } } - if (in_array($object->statut, array(3, 4, 5, 6, 7, 9))) - { - if ($usercanorder) - { + if (in_array($object->statut, array(3, 4, 5, 6, 7, 9))) { + if ($usercanorder) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans("ReOpen").'</a>'; } } // Ship - if (!empty($conf->stock->enabled) && (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE))) - { + if (!empty($conf->stock->enabled) && (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE))) { $labelofbutton = $langs->trans('ReceiveProducts'); - if ($conf->reception->enabled) $labelofbutton = $langs->trans("CreateReception"); + if ($conf->reception->enabled) { + $labelofbutton = $langs->trans("CreateReception"); + } if (in_array($object->statut, array(3, 4, 5))) { if ($conf->fournisseur->enabled && $usercanreceived) { @@ -2496,10 +2446,8 @@ if ($action == 'create') } } - if ($object->statut == CommandeFournisseur::STATUS_ACCEPTED) - { - if ($usercanorder) - { + if ($object->statut == CommandeFournisseur::STATUS_ACCEPTED) { + if ($usercanorder) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=makeorder#makeorder">'.$langs->trans("MakeOrder").'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#">'.$langs->trans("MakeOrder").'</a></div>'; @@ -2507,10 +2455,8 @@ if ($action == 'create') } // Classify received (this does not record reception) - if ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY) - { - if ($usercanreceived) - { + if ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY) { + if ($usercanreceived) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifyreception#classifyreception">'.$langs->trans("ClassifyReception").'</a></div>'; } } @@ -2518,26 +2464,20 @@ if ($action == 'create') // Create bill //if (! empty($conf->facture->enabled)) //{ - if (!empty($conf->fournisseur->enabled) && ($object->statut >= 2 && $object->statut != 7 && $object->billed != 1)) // statut 2 means approved, 7 means canceled - { - if ($user->rights->fournisseur->facture->creer) - { + if (!empty($conf->fournisseur->enabled) && ($object->statut >= 2 && $object->statut != 7 && $object->billed != 1)) { // statut 2 means approved, 7 means canceled + if ($user->rights->fournisseur->facture->creer) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?action=create&amp;origin='.$object->element.'&amp;originid='.$object->id.'&amp;socid='.$object->socid.'">'.$langs->trans("CreateBill").'</a>'; } } //} // Classify billed manually (need one invoice if module invoice is on, no condition on invoice if not) - if ($usercancreate && $object->statut >= 2 && $object->statut != 7 && $object->billed != 1) // statut 2 means approved - { - if (empty($conf->facture->enabled)) - { + if ($usercancreate && $object->statut >= 2 && $object->statut != 7 && $object->billed != 1) { // statut 2 means approved + if (empty($conf->facture->enabled)) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifybilled">'.$langs->trans("ClassifyBilled").'</a>'; } else { - if (!empty($object->linkedObjectsIds['invoice_supplier'])) - { - if ($user->rights->fournisseur->facture->creer) - { + if (!empty($object->linkedObjectsIds['invoice_supplier'])) { + if ($user->rights->fournisseur->facture->creer) { print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=classifybilled">'.$langs->trans("ClassifyBilled").'</a>'; } } else { @@ -2547,29 +2487,24 @@ if ($action == 'create') } // Create a remote order using WebService only if module is activated - if (!empty($conf->syncsupplierwebservices->enabled) && $object->statut >= 2) // 2 means accepted - { + if (!empty($conf->syncsupplierwebservices->enabled) && $object->statut >= 2) { // 2 means accepted print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=webservice&amp;mode=init">'.$langs->trans('CreateRemoteOrder').'</a>'; } // Clone - if ($usercancreate) - { + if ($usercancreate) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;socid='.$object->socid.'&amp;action=clone&amp;object=order">'.$langs->trans("ToClone").'</a>'; } // Cancel - if ($object->statut == 2) - { - if ($usercanorder) - { + if ($object->statut == 2) { + if ($usercanorder) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=cancel">'.$langs->trans("CancelOrder").'</a>'; } } // Delete - if (!empty($usercandelete) || ($object->statut == CommandeFournisseur::STATUS_DRAFT && !empty($usercancreate))) - { + if (!empty($usercandelete) || ($object->statut == CommandeFournisseur::STATUS_DRAFT && !empty($usercancreate))) { print '<a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans("Delete").'</a>'; } } @@ -2578,8 +2513,7 @@ if ($action == 'create') - if ($usercanorder && $object->statut == CommandeFournisseur::STATUS_ACCEPTED && $action == 'makeorder') - { + if ($usercanorder && $object->statut == CommandeFournisseur::STATUS_ACCEPTED && $action == 'makeorder') { // Set status to ordered (action=commande) print '<!-- form to record supplier order -->'."\n"; print '<form name="commande" id="makeorder" action="card.php?id='.$object->id.'&amp;action=commande" method="POST">'; @@ -2591,7 +2525,9 @@ if ($action == 'create') //print '<tr class="liste_titre"><td colspan="2">'.$langs->trans("ToOrder").'</td></tr>'; print '<tr><td class="fieldrequired">'.$langs->trans("OrderDate").'</td><td>'; $date_com = dol_mktime(GETPOST('rehour', 'int'), GETPOST('remin', 'int'), GETPOST('resec', 'int'), GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - if (empty($date_com)) $date_com = dol_now(); + if (empty($date_com)) { + $date_com = dol_now(); + } print $form->selectDate($date_com, '', 1, 1, '', "commande", 1, 1); print '</td></tr>'; @@ -2612,8 +2548,7 @@ if ($action == 'create') print "<br>"; } - if ($action != 'makeorder') - { + if ($action != 'makeorder') { print '<div class="fichecenter"><div class="fichehalfleft">'; // Generated documents @@ -2634,10 +2569,8 @@ if ($action == 'create') print '</div><div class="fichehalfright"><div class="ficheaddleft">'; - if ($action == 'classifyreception') - { - if ($usercanreceived && ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY)) - { + if ($action == 'classifyreception') { + if ($usercanreceived && ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY)) { // Set status to received (action=livraison) print '<!-- form to record purchase order received -->'."\n"; print '<form id="classifyreception" action="card.php?id='.$object->id.'" method="post">'; @@ -2682,8 +2615,7 @@ if ($action == 'create') /* * Action webservice */ - if ($action == 'webservice' && GETPOST('mode', 'alpha') != "send" && !GETPOST('cancel', 'alpha')) - { + if ($action == 'webservice' && GETPOST('mode', 'alpha') != "send" && !GETPOST('cancel', 'alpha')) { $mode = GETPOST('mode', 'alpha'); $ws_url = $object->thirdparty->webservices_url; $ws_key = $object->thirdparty->webservices_key; @@ -2712,8 +2644,7 @@ if ($action == 'create') $mode = "init"; } - if ($mode == "init") - { + if ($mode == "init") { //Table/form header print '<table class="border centpercent">'; print '<form action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">'; @@ -2721,8 +2652,7 @@ if ($action == 'create') print '<input type="hidden" name="action" value="webservice">'; print '<input type="hidden" name="mode" value="check">'; - if ($error_occurred) - { + if ($error_occurred) { print "<br>".$langs->trans("ErrorOccurredReviseAndRetry")."<br>"; print '<input class="button button-cancel" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'">'; } else { @@ -2745,8 +2675,7 @@ if ($action == 'create') //End table/form print '</form>'; print '</table>'; - } elseif ($mode == "check") - { + } elseif ($mode == "check") { $ws_entity = ''; $ws_thirdparty = ''; $error_occurred = false; @@ -2761,14 +2690,12 @@ if ($action == 'create') $result_user = $soapclient_user->call("getUser", $ws_parameters, $ws_ns, ''); $user_status_code = $result_user["result"]["result_code"]; - if ($user_status_code == "OK") - { + if ($user_status_code == "OK") { //Fill the variables $ws_entity = $result_user["user"]["entity"]; $ws_authentication['entity'] = $ws_entity; $ws_thirdparty = $result_user["user"]["fk_thirdparty"]; - if (empty($ws_thirdparty)) - { + if (empty($ws_thirdparty)) { setEventMessages($langs->trans("RemoteUserMissingAssociatedSoc"), null, 'errors'); $error_occurred = true; } else { @@ -2788,8 +2715,7 @@ if ($action == 'create') } $ws_parameters = array('authentication' => $ws_authentication, 'id' => '', 'ref' => $ref_supplier); $result_product = $soapclient_product->call("getProductOrService", $ws_parameters, $ws_ns, ''); - if (!$result_product) - { + if (!$result_product) { setEventMessages($line_id.$langs->trans("SOAPError")." ".$soapclient_product->error_str." - ".$soapclient_product->response, null, 'errors'); $error_occurred = true; break; @@ -2797,13 +2723,10 @@ if ($action == 'create') // Check the result code $status_code = $result_product["result"]["result_code"]; - if (empty($status_code)) //No result, check error str - { + if (empty($status_code)) { //No result, check error str setEventMessages($langs->trans("SOAPError")." '".$soapclient_order->error_str."'", null, 'errors'); - } elseif ($status_code != "OK") //Something went wrong - { - if ($status_code == "NOT_FOUND") - { + } elseif ($status_code != "OK") { //Something went wrong + if ($status_code == "NOT_FOUND") { setEventMessages($line_id.$langs->trans("SupplierMissingRef")." '".$ref_supplier."'", null, 'warnings'); } else { setEventMessages($line_id.$langs->trans("ResponseNonOK")." '".$status_code."' - '".$result_product["result"]["result_label"]."'", null, 'errors'); @@ -2819,10 +2742,8 @@ if ($action == 'create') $product_fourn = new ProductFournisseur($db); $product_fourn_list = $product_fourn->list_product_fournisseur_price($line->fk_product); - if (count($product_fourn_list) > 0) - { - foreach ($product_fourn_list as $product_fourn_line) - { + if (count($product_fourn_list) > 0) { + foreach ($product_fourn_list as $product_fourn_line) { //Only accept the line where the supplier is the same at this order and has the same ref if ($product_fourn_line->fourn_id == $object->socid && $product_fourn_line->fourn_ref == $ref_supplier) { $local_price = price($product_fourn_line->fourn_price); @@ -2840,12 +2761,10 @@ if ($action == 'create') } } } - } elseif ($user_status_code == "PERMISSION_DENIED") - { + } elseif ($user_status_code == "PERMISSION_DENIED") { setEventMessages($langs->trans("RemoteUserNotPermission"), null, 'errors'); $error_occurred = true; - } elseif ($user_status_code == "BAD_CREDENTIALS") - { + } elseif ($user_status_code == "BAD_CREDENTIALS") { setEventMessages($langs->trans("RemoteUserBadCredentials"), null, 'errors'); $error_occurred = true; } else { @@ -2862,8 +2781,7 @@ if ($action == 'create') print '<input type="hidden" name="ws_password" value="'.$ws_password.'">'; print '<input type="hidden" name="ws_entity" value="'.$ws_entity.'">'; print '<input type="hidden" name="ws_thirdparty" value="'.$ws_thirdparty.'">'; - if ($error_occurred) - { + if ($error_occurred) { print "<br>".$langs->trans("ErrorOccurredReviseAndRetry")."<br>"; } else { print '<input class="button" type="submit" id="ws_submit" name="ws_submit" value="'.$langs->trans("Confirm").'">'; diff --git a/htdocs/fourn/commande/contact.php b/htdocs/fourn/commande/contact.php index 3e52f35d8bb..ae2e8bab481 100644 --- a/htdocs/fourn/commande/contact.php +++ b/htdocs/fourn/commande/contact.php @@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); $object = new CommandeFournisseur($db); @@ -51,51 +53,39 @@ $object = new CommandeFournisseur($db); * Add a new contact */ -if ($action == 'addcontact' && $user->rights->fournisseur->commande->creer) -{ +if ($action == 'addcontact' && $user->rights->fournisseur->commande->creer) { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} - -// Toggle the status of a contact -elseif ($action == 'swapstatut' && $user->rights->fournisseur->commande->creer) -{ - if ($object->fetch($id)) - { +} elseif ($action == 'swapstatut' && $user->rights->fournisseur->commande->creer) { + // Toggle the status of a contact + if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } -} - -// Deleting a contact -elseif ($action == 'deletecontact' && $user->rights->fournisseur->commande->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->fournisseur->commande->creer) { + // Deleting a contact $object->fetch($id); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -123,12 +113,10 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $langs->trans("OrderCard"); - if ($object->fetch($id, $ref) > 0) - { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $head = ordersupplier_prepare_head($object); @@ -145,12 +133,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fourn/commande/dispatch.php b/htdocs/fourn/commande/dispatch.php index dbe0bd5d7af..ee8c86aa0b8 100644 --- a/htdocs/fourn/commande/dispatch.php +++ b/htdocs/fourn/commande/dispatch.php @@ -40,14 +40,16 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.dispatch.class require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php'; -if (!empty($conf->projet->enabled)) +if (!empty($conf->projet->enabled)) { require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; +} // Load translation files required by the page $langs->loadLangs(array("bills", "orders", "sendings", "companies", "deliveries", "products", "stocks", "receptions")); -if (!empty($conf->productbatch->enabled)) +if (!empty($conf->productbatch->enabled)) { $langs->load('productbatch'); +} // Security check $id = GETPOST("id", 'int'); @@ -58,8 +60,9 @@ $fk_default_warehouse = GETPOST('fk_default_warehouse', 'int'); $cancel = GETPOST('cancel', 'alpha'); $confirm = GETPOST('confirm', 'alpha'); -if ($user->socid) +if ($user->socid) { $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); if (empty($conf->stock->enabled)) { @@ -70,8 +73,9 @@ $hookmanager->initHooks(array('ordersupplierdispatch')); // Recuperation de l'id de projet $projectid = 0; -if ($_GET["projectid"]) +if ($_GET["projectid"]) { $projectid = GETPOST("projectid", 'int'); +} $object = new CommandeFournisseur($db); @@ -93,25 +97,24 @@ if ($id > 0 || !empty($ref)) { $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if ($action == 'checkdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) -{ +if ($action == 'checkdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) { $error = 0; $supplierorderdispatch = new CommandeFournisseurDispatch($db); $db->begin(); $result = $supplierorderdispatch->fetch($lineid); - if (!$result) - { + if (!$result) { $error++; setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); $action = ''; } - if (!$error) - { + if (!$error) { $result = $supplierorderdispatch->setStatut(1); if ($result < 0) { setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); @@ -120,8 +123,7 @@ if ($action == 'checkdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_ } } - if (!$error) - { + if (!$error) { $result = $object->calcAndSetStatusDispatch($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -129,31 +131,27 @@ if ($action == 'checkdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_ $action = ''; } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); } } -if ($action == 'uncheckdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) -{ +if ($action == 'uncheckdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) { $error = 0; $supplierorderdispatch = new CommandeFournisseurDispatch($db); $db->begin(); $result = $supplierorderdispatch->fetch($lineid); - if (!$result) - { + if (!$result) { $error++; setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); $action = ''; } - if (!$error) - { + if (!$error) { $result = $supplierorderdispatch->setStatut(0); if ($result < 0) { setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); @@ -161,8 +159,7 @@ if ($action == 'uncheckdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCE $action = ''; } } - if (!$error) - { + if (!$error) { $result = $object->calcAndSetStatusDispatch($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -170,31 +167,27 @@ if ($action == 'uncheckdispatchline' && !((empty($conf->global->MAIN_USE_ADVANCE $action = ''; } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); } } -if ($action == 'denydispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) -{ +if ($action == 'denydispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check)))) { $error = 0; $supplierorderdispatch = new CommandeFournisseurDispatch($db); $db->begin(); $result = $supplierorderdispatch->fetch($lineid); - if (!$result) - { + if (!$result) { $error++; setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); $action = ''; } - if (!$error) - { + if (!$error) { $result = $supplierorderdispatch->setStatut(2); if ($result < 0) { setEventMessages($supplierorderdispatch->error, $supplierorderdispatch->errors, 'errors'); @@ -202,8 +195,7 @@ if ($action == 'denydispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_P $action = ''; } } - if (!$error) - { + if (!$error) { $result = $object->calcAndSetStatusDispatch($user); if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); @@ -211,8 +203,7 @@ if ($action == 'denydispatchline' && !((empty($conf->global->MAIN_USE_ADVANCED_P $action = ''; } } - if (!$error) - { + if (!$error) { $db->commit(); } else { $db->rollback(); @@ -225,12 +216,10 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) $db->begin(); $pos = 0; - foreach ($_POST as $key => $value) - { + foreach ($_POST as $key => $value) { // without batch module enabled $reg = array(); - if (preg_match('/^product_([0-9]+)_([0-9]+)$/i', $key, $reg)) - { + if (preg_match('/^product_([0-9]+)_([0-9]+)$/i', $key, $reg)) { $pos++; // $numline=$reg[2] + 1; // line of product @@ -238,7 +227,9 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) $prod = "product_".$reg[1].'_'.$reg[2]; $qty = "qty_".$reg[1].'_'.$reg[2]; $ent = "entrepot_".$reg[1].'_'.$reg[2]; - if (empty(GETPOST($ent))) $ent = $fk_default_warehouse; + if (empty(GETPOST($ent))) { + $ent = $fk_default_warehouse; + } $pu = "pu_".$reg[1].'_'.$reg[2]; // This is unit price including discount $fk_commandefourndet = "fk_commandefourndet_".$reg[1].'_'.$reg[2]; @@ -293,8 +284,7 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) } } // with batch module enabled - if (preg_match('/^product_batch_([0-9]+)_([0-9]+)$/i', $key, $reg)) - { + if (preg_match('/^product_batch_([0-9]+)_([0-9]+)$/i', $key, $reg)) { $pos++; // eat-by date dispatch @@ -398,14 +388,12 @@ if ($action == 'dispatch' && $user->rights->fournisseur->commande->receptionner) } // Remove a dispatched line -if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->fournisseur->commande->receptionner) -{ +if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->fournisseur->commande->receptionner) { $db->begin(); $supplierorderdispatch = new CommandeFournisseurDispatch($db); $result = $supplierorderdispatch->fetch($lineid); - if ($result > 0) - { + if ($result > 0) { $qty = $supplierorderdispatch->qty; $entrepot = $supplierorderdispatch->fk_entrepot; $product = $supplierorderdispatch->fk_product; @@ -417,48 +405,39 @@ if ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->fourn $result = $supplierorderdispatch->delete($user); } - if ($result < 0) - { + if ($result < 0) { $errors = $object->errors; $error++; - } - else { + } else { // If module stock is enabled and the stock increase is done on purchase order dispatching - if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) - { + if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { $mouv = new MouvementStock($db); - if ($product > 0) - { + if ($product > 0) { $mouv->origin = &$object; $result = $mouv->livraison($user, $product, $entrepot, $qty, $price, $comment, '', $eatby, $sellby, $batch); - if ($result < 0) - { + if ($result < 0) { $errors = $mouv->errors; $error++; } } } } - if ($error > 0) - { + if ($error > 0) { $db->rollback(); setEventMessages($error, $errors, 'errors'); - } - else { + } else { $db->commit(); } } // Update a dispatched line -if ($action == 'updateline' && $user->rights->fournisseur->commande->receptionner) -{ +if ($action == 'updateline' && $user->rights->fournisseur->commande->receptionner) { $db->begin(); $error = 0; $supplierorderdispatch = new CommandeFournisseurDispatch($db); $result = $supplierorderdispatch->fetch($lineid); - if ($result > 0) - { + if ($result > 0) { $qty = $supplierorderdispatch->qty; $entrepot = $supplierorderdispatch->fk_entrepot; $product = $supplierorderdispatch->fk_product; @@ -472,30 +451,23 @@ if ($action == 'updateline' && $user->rights->fournisseur->commande->receptionne $supplierorderdispatch->fk_entrepot = GETPOST('fk_entrepot'); $result = $supplierorderdispatch->update($user); } - if ($result < 0) - { + if ($result < 0) { $error++; $errors = $supplierorderdispatch->errors; - } - else { + } else { // If module stock is enabled and the stock increase is done on purchase order dispatching - if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) - { + if ($entrepot > 0 && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { $mouv = new MouvementStock($db); - if ($product > 0) - { + if ($product > 0) { $mouv->origin = &$object; $result = $mouv->livraison($user, $product, $entrepot, $qty, $price, $comment, '', $eatby, $sellby, $batch); - if ($result < 0) - { + if ($result < 0) { $errors = $mouv->errors; $error++; - } - else { + } else { $mouv->origin = &$object; $result = $mouv->reception($user, $product, $supplierorderdispatch->fk_entrepot, $supplierorderdispatch->qty, $price, $comment, $eatby, $sellby, $batch); - if ($result < 0) - { + if ($result < 0) { $errors = $mouv->errors; $error++; } @@ -503,12 +475,10 @@ if ($action == 'updateline' && $user->rights->fournisseur->commande->receptionne } } } - if ($error > 0) - { + if ($error > 0) { $db->rollback(); setEventMessages($error, $errors, 'errors'); - } - else { + } else { $db->commit(); } } @@ -544,8 +514,7 @@ if ($id > 0 || !empty($ref)) { $formconfirm = ''; // Confirmation to delete line - if ($action == 'ask_deleteline') - { + if ($action == 'ask_deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); } @@ -553,8 +522,11 @@ if ($id > 0 || !empty($ref)) { $parameters = array('lineid' => $lineid); // Note that $action and $object may be modified by hook $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -570,12 +542,10 @@ if ($id > 0 || !empty($ref)) { // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; @@ -643,8 +613,9 @@ if ($id > 0 || !empty($ref)) { print '<br>'; $disabled = 1; - if (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) + if (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) { $disabled = 0; + } // Line of orders if ($object->statut <= CommandeFournisseur::STATUS_ACCEPTED || $object->statut >= CommandeFournisseur::STATUS_CANCELED) { @@ -653,8 +624,7 @@ if ($id > 0 || !empty($ref)) { if ($object->statut == CommandeFournisseur::STATUS_ORDERSENT || $object->statut == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY - || $object->statut == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) - { + || $object->statut == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) { require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php'; $formproduct = new FormProduct($db); $formproduct->loadWarehouses(); @@ -662,12 +632,18 @@ if ($id > 0 || !empty($ref)) { $listwarehouses = $entrepot->list_array(1); - if (empty($conf->reception->enabled))print '<form method="POST" action="dispatch.php?id='.$object->id.'">'; - else print '<form method="post" action="'.dol_buildpath('/reception/card.php', 1).'?originid='.$object->id.'&origin=supplierorder">'; + if (empty($conf->reception->enabled)) { + print '<form method="POST" action="dispatch.php?id='.$object->id.'">'; + } else { + print '<form method="post" action="'.dol_buildpath('/reception/card.php', 1).'?originid='.$object->id.'&origin=supplierorder">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; - if (empty($conf->reception->enabled))print '<input type="hidden" name="action" value="dispatch">'; - else print '<input type="hidden" name="action" value="create">'; + if (empty($conf->reception->enabled)) { + print '<input type="hidden" name="action" value="dispatch">'; + } else { + print '<input type="hidden" name="action" value="create">'; + } print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; @@ -706,14 +682,17 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseurdet as l"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product as p ON l.fk_product=p.rowid"; $sql .= " WHERE l.fk_commande = ".$object->id; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $sql .= " AND l.product_type = 0"; + } // Enable hooks to alter the SQL query (WHERE) $parameters = array(); @@ -723,7 +702,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } $sql .= $hookmanager->resPrint; $sql .= " GROUP BY p.ref, p.label, p.tobatch, p.fk_default_warehouse, l.rowid, l.fk_product, l.subprice, l.remise_percent, l.ref"; // Calculation of amount dispatched is done per fk_product so we must group by fk_product @@ -785,7 +766,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print "</tr>\n"; @@ -803,8 +786,9 @@ if ($id > 0 || !empty($ref)) { $nbfreeproduct++; } else { $remaintodispatch = price2num($objp->qty - ((float) $products_dispatched[$objp->rowid]), 5); // Calculation of dispatched - if ($remaintodispatch < 0) + if ($remaintodispatch < 0) { $remaintodispatch = 0; + } if ($remaintodispatch || empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) { $nbproduct++; @@ -858,8 +842,9 @@ if ($id > 0 || !empty($ref)) { // Define unit price for PMP calculation $up_ht_disc = $objp->subprice; - if (!empty($objp->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) + if (!empty($objp->remise_percent) && empty($conf->global->STOCK_EXCLUDE_DISCOUNT_FOR_PMP)) { $up_ht_disc = price2num($up_ht_disc * (100 - $objp->remise_percent) / 100, 'MU'); + } // Supplier ref print '<td class="right">'.$objp->sref.'</td>'; @@ -892,7 +877,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print '</tr>'; @@ -903,8 +890,7 @@ if ($id > 0 || !empty($ref)) { print '<input name="product_batch'.$suffix.'" type="hidden" value="'.$objp->fk_product.'">'; print '<!-- This is a up (may include discount or not depending on STOCK_EXCLUDE_DISCOUNT_FOR_PMP. will be used for PMP calculation) -->'; - if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) // Not tested ! - { + if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) { // Not tested ! print $langs->trans("BuyingPrice").': <input class="maxwidth75" name="pu'.$suffix.'" type="text" value="'.price2num($up_ht_disc, 'MU').'">'; } else { print '<input class="maxwidth75" name="pu'.$suffix.'" type="hidden" value="'.price2num($up_ht_disc, 'MU').'">'; @@ -953,7 +939,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print '</tr>'; @@ -964,8 +952,7 @@ if ($id > 0 || !empty($ref)) { print '<input name="product'.$suffix.'" type="hidden" value="'.$objp->fk_product.'">'; print '<!-- This is a up (may include discount or not depending on STOCK_EXCLUDE_DISCOUNT_FOR_PMP. will be used for PMP calculation) -->'; - if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) // Not tested ! - { + if (!empty($conf->global->SUPPLIER_ORDER_EDIT_BUYINGPRICE_DURING_RECEIPT)) { // Not tested ! print $langs->trans("BuyingPrice").': <input class="maxwidth75" name="pu'.$suffix.'" type="text" value="'.price2num($up_ht_disc, 'MU').'">'; } else { print '<input class="maxwidth75" name="pu'.$suffix.'" type="hidden" value="'.price2num($up_ht_disc, 'MU').'">'; @@ -1030,7 +1017,9 @@ if ($id > 0 || !empty($ref)) { $object, $action ); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print "</tr>\n"; @@ -1046,16 +1035,14 @@ if ($id > 0 || !empty($ref)) { print "</table>\n"; print '</div>'; - if ($nbproduct) - { + if ($nbproduct) { $checkboxlabel = $langs->trans("CloseReceivedSupplierOrdersAutomatically", $langs->transnoentitiesnoconv('StatusOrderReceivedAll')); print '<div class="center">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { if (empty($conf->reception->enabled)) { print $langs->trans("Comment").' : '; print '<input type="text" class="minwidth400" maxlength="128" name="comment" value="'; @@ -1069,8 +1056,9 @@ if ($id > 0 || !empty($ref)) { $dispatchBt = empty($conf->reception->enabled) ? $langs->trans("Receive") : $langs->trans("CreateReception"); print '<br><input type="submit" class="button" name="dispatch" value="'.dol_escape_htmltag($dispatchBt).'"'; - if (count($listwarehouses) <= 0) + if (count($listwarehouses) <= 0) { print ' disabled'; + } print '>'; } print '</div>'; @@ -1079,9 +1067,11 @@ if ($id > 0 || !empty($ref)) { // Message if nothing to dispatch if (!$nbproduct) { print "<br>\n"; - if (empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) + if (empty($conf->global->SUPPLIER_ORDER_DISABLE_STOCK_DISPATCH_WHEN_TOTAL_REACHED)) { print '<div class="opacitymedium">'.$langs->trans("NoPredefinedProductToDispatch").'</div>'; // No predefined line at all - else print '<div class="opacitymedium">'.$langs->trans("NoMorePredefinedProductToDispatch").'</div>'; // No predefined line that remain to be dispatched. + } else { + print '<div class="opacitymedium">'.$langs->trans("NoMorePredefinedProductToDispatch").'</div>'; // No predefined line that remain to be dispatched. + } } print '</form>'; @@ -1113,12 +1103,16 @@ if ($id > 0 || !empty($ref)) { $sql .= " e.rowid as warehouse_id, e.ref as entrepot,"; $sql .= " cfd.rowid as dispatchlineid, cfd.fk_product, cfd.qty, cfd.eatby, cfd.sellby, cfd.batch, cfd.comment, cfd.status, cfd.datec"; $sql .= " ,cd.rowid, cd.subprice"; - if ($conf->reception->enabled)$sql .= " ,cfd.fk_reception, r.date_delivery"; + if ($conf->reception->enabled) { + $sql .= " ,cfd.fk_reception, r.date_delivery"; + } $sql .= " FROM ".MAIN_DB_PREFIX."product as p,"; $sql .= " ".MAIN_DB_PREFIX."commande_fournisseur_dispatch as cfd"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_fournisseurdet as cd ON cd.rowid = cfd.fk_commandefourndet"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."entrepot as e ON cfd.fk_entrepot = e.rowid"; - if ($conf->reception->enabled)$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."reception as r ON cfd.fk_reception = r.rowid"; + if ($conf->reception->enabled) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."reception as r ON cfd.fk_reception = r.rowid"; + } $sql .= " WHERE cfd.fk_commande = ".$object->id; $sql .= " AND cfd.fk_product = p.rowid"; $sql .= " ORDER BY cfd.rowid ASC"; @@ -1137,7 +1131,9 @@ if ($id > 0 || !empty($ref)) { print '<table id="dispatch_received_products" class="noborder centpercent">'; print '<tr class="liste_titre">'; - if ($conf->reception->enabled)print '<td>'.$langs->trans("Reception").'</td>'; + if ($conf->reception->enabled) { + print '<td>'.$langs->trans("Reception").'</td>'; + } print '<td>'.$langs->trans("Product").'</td>'; print '<td>'.$langs->trans("DateCreation").'</td>'; @@ -1169,8 +1165,7 @@ if ($id > 0 || !empty($ref)) { while ($i < $num) { $objp = $db->fetch_object($resql); - if ($action == 'editline' && $lineid == $objp->dispatchlineid) - { + if ($action == 'editline' && $lineid == $objp->dispatchlineid) { print '<form name="editdispatchedlines" id="editdispatchedlines" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'#line_'.GETPOST('lineid').'" method="POST"> <input type="hidden" name="token" value="'.newToken().'"> <input type="hidden" name="action" value="updateline"> @@ -1219,11 +1214,9 @@ if ($id > 0 || !empty($ref)) { // Qty print '<td class="right">'; - if ($action == 'editline' && $lineid == $objp->dispatchlineid) - { + if ($action == 'editline' && $lineid == $objp->dispatchlineid) { print '<input style="width: 50px;" type="number" min="1" name="qty" value="'.$objp->qty.'" />'; - } - else { + } else { print $objp->qty; } print '<input type="hidden" name="price" value="'.$objp->subprice.'" />'; @@ -1231,8 +1224,7 @@ if ($id > 0 || !empty($ref)) { // Warehouse print '<td>'; - if ($action == 'editline' && $lineid == $objp->dispatchlineid) - { + if ($action == 'editline' && $lineid == $objp->dispatchlineid) { if (count($listwarehouses) > 1) { print $formproduct->selectWarehouses(GETPOST("fk_entrepot") ?GETPOST("fk_entrepot") : ($objp->warehouse_id ? $objp->warehouse_id : ''), "fk_entrepot", '', 1, 0, $objp->fk_product, '', 1, 1, null, 'csswarehouse'); } elseif (count($listwarehouses) == 1) { @@ -1241,8 +1233,7 @@ if ($id > 0 || !empty($ref)) { $langs->load("errors"); print $langs->trans("ErrorNoWarehouseDefined"); } - } - else { + } else { $warehouse_static->id = $objp->warehouse_id; $warehouse_static->libelle = $objp->entrepot; print $warehouse_static->getNomUrl(1); @@ -1262,8 +1253,7 @@ if ($id > 0 || !empty($ref)) { // Add button to check/uncheck disaptching print '<td class="center">'; - if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check))) - { + if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande->receptionner)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && empty($user->rights->fournisseur->commande_advance->check))) { if (empty($objp->status)) { print '<a class="button buttonRefused" href="#">'.$langs->trans("Approve").'</a>'; print '<a class="button buttonRefused" href="#">'.$langs->trans("Deny").'</a>'; @@ -1273,8 +1263,9 @@ if ($id > 0 || !empty($ref)) { } } else { $disabled = ''; - if ($object->statut == 5) + if ($object->statut == 5) { $disabled = 1; + } if (empty($objp->status)) { print '<a class="button'.($disabled ? ' buttonRefused' : '').'" href="'.$_SERVER["PHP_SELF"]."?id=".$id."&action=checkdispatchline&lineid=".$objp->dispatchlineid.'">'.$langs->trans("Approve").'</a>'; print '<a class="button'.($disabled ? ' buttonRefused' : '').'" href="'.$_SERVER["PHP_SELF"]."?id=".$id."&action=denydispatchline&lineid=".$objp->dispatchlineid.'">'.$langs->trans("Deny").'</a>'; @@ -1297,8 +1288,7 @@ if ($id > 0 || !empty($ref)) { print '</td>'; } - if ($action != 'editline' || $lineid != $objp->dispatchlineid) - { + if ($action != 'editline' || $lineid != $objp->dispatchlineid) { print '<td class="linecoledit center">'; print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=editline&amp;lineid='.$objp->dispatchlineid.'#line_'.$objp->dispatchlineid.'">'; print img_edit(); @@ -1310,8 +1300,7 @@ if ($id > 0 || !empty($ref)) { print img_delete(); print '</a>'; print '</td>'; - } - else { + } else { print '<td class="center valignmiddle">'; print '<input type="submit" class="button button-save" id="savelinebutton" name="save" value="'.$langs->trans("Save").'" />'; print '</td>'; @@ -1322,7 +1311,9 @@ if ($id > 0 || !empty($ref)) { print "</tr>\n"; - if ($action == 'editline' && $lineid == $objp->dispatchlineid) print '</form>'; + if ($action == 'editline' && $lineid == $objp->dispatchlineid) { + print '</form>'; + } $i++; } diff --git a/htdocs/fourn/commande/document.php b/htdocs/fourn/commande/document.php index 293edb549ea..3bc2a799a5f 100644 --- a/htdocs/fourn/commande/document.php +++ b/htdocs/fourn/commande/document.php @@ -47,7 +47,9 @@ $action = GETPOST('action', 'aZ09'); $confirm = GETPOST('confirm', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); // Get parameters @@ -55,17 +57,22 @@ $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 +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 = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} $object = new CommandeFournisseur($db); -if ($object->fetch($id, $ref) < 0) -{ +if ($object->fetch($id, $ref) < 0) { dol_print_error($db); exit; } @@ -87,8 +94,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; $form = new Form($db); -if ($object->id > 0) -{ +if ($object->id > 0) { $help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $langs->trans("Order"), $help_url); @@ -105,8 +111,7 @@ if ($object->id > 0) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } @@ -121,12 +126,10 @@ if ($object->id > 0) // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fourn/commande/index.php b/htdocs/fourn/commande/index.php index 1e9e69fb8cd..d46456b52dc 100644 --- a/htdocs/fourn/commande/index.php +++ b/htdocs/fourn/commande/index.php @@ -32,7 +32,9 @@ require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php'; // Security check $orderid = GETPOST('orderid'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $orderid, '', 'commande'); $hookmanager = new HookManager($db); @@ -59,8 +61,7 @@ print load_fiche_titre($langs->trans("SuppliersOrdersArea"), '', 'supplier_order print '<div class="fichecenter"><div class="fichethirdleft">'; -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useless due to the global search combo -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { // This is useless due to the global search combo print '<form method="post" action="list.php">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<div class="div-table-responsive-no-min">'; @@ -79,16 +80,21 @@ if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) // This is useles $sql = "SELECT count(cf.rowid) as nb, fk_statut as status"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as cf"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE cf.fk_soc = s.rowid"; $sql .= " AND cf.entity IN (".getEntity('supplier_order').")"; -if ($user->socid) $sql .= ' AND cf.fk_soc = '.$user->socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if ($user->socid) { + $sql .= ' AND cf.fk_soc = '.$user->socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " GROUP BY cf.fk_statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -98,11 +104,9 @@ if ($resql) // 0=Draft -> 1=Validated -> 2=Approved -> 3=Process runing -> 4=Received partially -> 5=Received totally -> (reopen) 4=Received partially // -> 7=Canceled/Never received -> (reopen) 3=Process runing // -> 6=Canceled -> (reopen) 2=Approved - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $vals[($obj->status == CommandeFournisseur::STATUS_CANCELED_AFTER_ORDER ? CommandeFournisseur::STATUS_CANCELED : $obj->status)] = $obj->nb; $total += $obj->nb; @@ -118,28 +122,41 @@ if ($resql) print '<tr class="liste_titre"><th colspan="2">'.$langs->trans("Statistics").' - '.$langs->trans("SuppliersOrders").'</th></tr>'; print "</tr>\n"; $listofstatus = array(0, 1, 2, 3, 4, 5, 6, 9); - foreach ($listofstatus as $status) - { + foreach ($listofstatus as $status) { $dataseries[] = array($commandestatic->LibStatut($status, 1), (isset($vals[$status]) ? (int) $vals[$status] : 0)); - if ($status == CommandeFournisseur::STATUS_DRAFT) $colorseries[$status] = '-'.$badgeStatus0; - if ($status == CommandeFournisseur::STATUS_VALIDATED) $colorseries[$status] = '-'.$badgeStatus1; - if ($status == CommandeFournisseur::STATUS_ACCEPTED) $colorseries[$status] = $badgeStatus1; - if ($status == CommandeFournisseur::STATUS_REFUSED) $colorseries[$status] = $badgeStatus9; - if ($status == CommandeFournisseur::STATUS_ORDERSENT) $colorseries[$status] = $badgeStatus4; - if ($status == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY) $colorseries[$status] = '-'.$badgeStatus4; - if ($status == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) $colorseries[$status] = $badgeStatus6; - if ($status == CommandeFournisseur::STATUS_CANCELED || $status == CommandeFournisseur::STATUS_CANCELED_AFTER_ORDER) $colorseries[$status] = $badgeStatus9; + if ($status == CommandeFournisseur::STATUS_DRAFT) { + $colorseries[$status] = '-'.$badgeStatus0; + } + if ($status == CommandeFournisseur::STATUS_VALIDATED) { + $colorseries[$status] = '-'.$badgeStatus1; + } + if ($status == CommandeFournisseur::STATUS_ACCEPTED) { + $colorseries[$status] = $badgeStatus1; + } + if ($status == CommandeFournisseur::STATUS_REFUSED) { + $colorseries[$status] = $badgeStatus9; + } + if ($status == CommandeFournisseur::STATUS_ORDERSENT) { + $colorseries[$status] = $badgeStatus4; + } + if ($status == CommandeFournisseur::STATUS_RECEIVED_PARTIALLY) { + $colorseries[$status] = '-'.$badgeStatus4; + } + if ($status == CommandeFournisseur::STATUS_RECEIVED_COMPLETELY) { + $colorseries[$status] = $badgeStatus6; + } + if ($status == CommandeFournisseur::STATUS_CANCELED || $status == CommandeFournisseur::STATUS_CANCELED_AFTER_ORDER) { + $colorseries[$status] = $badgeStatus9; + } - if (!$conf->use_javascript_ajax) - { + if (!$conf->use_javascript_ajax) { print '<tr class="oddeven">'; print '<td>'.$commandestatic->LibStatut($status, 0).'</td>'; print '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>'; print "</tr>\n"; } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { print '<tr class="impair"><td class="center" colspan="2">'; include_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php'; @@ -168,32 +185,34 @@ if ($resql) * Draft orders */ -if (!empty($conf->fournisseur->enabled)) -{ +if (!empty($conf->fournisseur->enabled)) { $sql = "SELECT c.rowid, c.ref, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity IN (".getEntity("supplier_order").")"; // Thirdparty sharing is mandatory with supplier order sharing $sql .= " AND c.fk_statut = 0"; - if (!empty($socid)) $sql .= " AND c.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!empty($socid)) { + $sql .= " AND c.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="2">'.$langs->trans("DraftOrders").'</th></tr>'; $langs->load("orders"); $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -218,8 +237,7 @@ if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_T } $sql .= " u.rowid, u.lastname, u.firstname, u.email, u.statut"; $sql .= " FROM ".MAIN_DB_PREFIX."user as u"; -if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) -{ +if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_TRANSVERSE_MODE)) { $sql .= ",".MAIN_DB_PREFIX."usergroup_user as ug"; $sql .= " WHERE ((ug.fk_user = u.rowid"; $sql .= " AND ug.entity IN (".getEntity('usergroup')."))"; @@ -230,8 +248,7 @@ if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_T $sql .= " AND u.fk_soc IS NULL"; // An external user can not approved $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -240,16 +257,14 @@ if ($resql) print '<tr class="liste_titre"><th>'.$langs->trans("UserWithApproveOrderGrant").'</th>'; print "</tr>\n"; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $userstatic = new User($db); $userstatic->id = $obj->rowid; $userstatic->getrights('fournisseur'); - if (!empty($userstatic->rights->fournisseur->commande->approuver)) - { + if (!empty($userstatic->rights->fournisseur->commande->approuver)) { print '<tr class="oddeven">'; print '<td>'; $userstatic->lastname = $obj->lastname; @@ -281,29 +296,32 @@ $max = 5; $sql = "SELECT c.rowid, c.ref, c.fk_statut as status, c.tms, c.billed, s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as c"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE c.fk_soc = s.rowid"; $sql .= " AND c.entity = ".$conf->entity; //$sql.= " AND c.fk_statut > 2"; -if (!empty($socid)) $sql .= " AND c.fk_soc = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if (!empty($socid)) { + $sql .= " AND c.fk_soc = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} $sql .= " ORDER BY c.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<th colspan="4">'.$langs->trans("LastModifiedOrders", $max).'</th></tr>'; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven">'; @@ -338,7 +356,9 @@ if ($resql) } } print "</table></div><br>"; -} else dol_print_error($db); +} else { + dol_print_error($db); +} /* diff --git a/htdocs/fourn/commande/info.php b/htdocs/fourn/commande/info.php index a50cbbdad39..60c67fdd0e8 100644 --- a/htdocs/fourn/commande/info.php +++ b/htdocs/fourn/commande/info.php @@ -44,17 +44,24 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST("sortfield", 'alpha'); $sortorder = GETPOST("sortorder", 'alpha'); $page = GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'a.datep,a.id'; -if (!$sortorder) $sortorder = 'DESC,DESC'; +if (!$sortfield) { + $sortfield = 'a.datep,a.id'; +} +if (!$sortorder) { + $sortorder = 'DESC,DESC'; +} -if (GETPOST('actioncode', 'array')) -{ +if (GETPOST('actioncode', 'array')) { $actioncode = GETPOST('actioncode', 'array', 3); - if (!count($actioncode)) $actioncode = '0'; + if (!count($actioncode)) { + $actioncode = '0'; + } } else { $actioncode = GETPOST("actioncode", "alpha", 3) ?GETPOST("actioncode", "alpha", 3) : (GETPOST("actioncode") == '0' ? '0' : (empty($conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECTS) ? '' : $conf->global->AGENDA_DEFAULT_FILTER_TYPE_FOR_OBJECTS)); } @@ -62,10 +69,14 @@ $search_agenda_label = GETPOST('search_agenda_label'); // Security check $socid = 0; -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); -if (!$user->rights->fournisseur->commande->lire) accessforbidden(); +if (!$user->rights->fournisseur->commande->lire) { + accessforbidden(); +} @@ -76,11 +87,12 @@ if (!$user->rights->fournisseur->commande->lire) accessforbidden(); $parameters = array('id'=>$id); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} // Purge search criteria -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 -{ +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 $actioncode = ''; $search_agenda_label = ''; } @@ -94,15 +106,16 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $form = new Form($db); $object = new CommandeFournisseur($db); -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $object->fetch($id, $ref); $object->fetch_thirdparty(); $object->info($object->id); } $title = $langs->trans("SupplierOrder").' - '.$object->ref.' '.$object->name; -if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +if (!empty($conf->global->MAIN_HTML_TITLE) && preg_match('/projectnameonly/', $conf->global->MAIN_HTML_TITLE) && $object->name) { + $title = $object->ref.' '.$object->name.' - '.$langs->trans("Info"); +} $help_url = 'EN:Module_Suppliers_Orders|FR:CommandeFournisseur|ES:Módulo_Pedidos_a_proveedores'; llxHeader('', $title, $help_url); @@ -125,12 +138,10 @@ $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_ // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project -if (!empty($conf->projet->enabled)) -{ +if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; @@ -181,18 +192,15 @@ print dol_get_fiche_end(); $out = ''; $permok = $user->rights->agenda->myactions->create; -if ($permok) -{ +if ($permok) { $out .= '&originid='.$object->id.'&origin=order_supplier'; } print '<div class="tabsAction">'; -if (!empty($conf->agenda->enabled)) -{ - if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) - { +if (!empty($conf->agenda->enabled)) { + if (!empty($user->rights->agenda->myactions->create) || !empty($user->rights->agenda->allactions->create)) { print '<a class="butAction" href="'.DOL_URL_ROOT.'/comm/action/card.php?action=create'.$out.'&backtopage='.urlencode($_SERVER["PHP_SELF"].'?id='.$object->id).'">'.$langs->trans("AddAction").'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#">'.$langs->trans("AddAction").'</a>'; @@ -202,18 +210,21 @@ if (!empty($conf->agenda->enabled)) print '</div>'; -if (!empty($object->id)) -{ +if (!empty($object->id)) { $param = '&id='.$object->id; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.$contextpage; - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.$limit; + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.$contextpage; + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.$limit; + } print load_fiche_titre($langs->trans("ActionsOnOrder"), '', ''); // List of actions on element /*include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; - $formactions=new FormActions($db); - $somethingshown = $formactions->showactions($object,'project',0);*/ + $formactions=new FormActions($db); + $somethingshown = $formactions->showactions($object,'project',0);*/ // List of todo actions //show_actions_todo($conf,$langs,$db,$object,null,0,$actioncode); diff --git a/htdocs/fourn/commande/list.php b/htdocs/fourn/commande/list.php index 0918b316fb3..e35d9d84824 100644 --- a/htdocs/fourn/commande/list.php +++ b/htdocs/fourn/commande/list.php @@ -99,7 +99,9 @@ if (is_array(GETPOST('search_status', 'intcomma'))) { // Security check $orderid = GETPOST('orderid', 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $orderid, '', 'commande'); $diroutputmassaction = $conf->fournisseur->commande->dir_output.'/temp/massgeneration/'.$user->id; @@ -108,14 +110,22 @@ $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 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = 'cf.ref'; -if (!$sortorder) $sortorder = 'DESC'; +if (!$sortfield) { + $sortfield = 'cf.ref'; +} +if (!$sortorder) { + $sortorder = 'DESC'; +} -if ($search_status == '') $search_status = -1; +if ($search_status == '') { + $search_status = -1; +} // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context $object = new CommandeFournisseur($db); @@ -138,7 +148,9 @@ $fieldstosearchall = array( 's.town'=>"Town", 'cf.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["cf.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["cf.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; $arrayfields = array( @@ -180,21 +192,25 @@ $error = 0; * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createsupplierbills') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createsupplierbills') { + $massaction = ''; +} $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Selection of new fields include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; // Purge search criteria - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers - { + 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_categ = ''; $search_user = ''; $search_sale = ''; @@ -231,8 +247,7 @@ if (empty($reshook)) $search_array_options = array(); } if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') - || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) - { + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation } @@ -245,8 +260,7 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; // Mass action to generate vendor bills - if ($massaction == 'confirm_createsupplierbills') - { + if ($massaction == 'confirm_createsupplierbills') { $orders = GETPOST('toselect', 'array'); $createbills_onebythird = GETPOST('createbills_onebythird', 'int'); $validate_invoices = GETPOST('validate_invoices', 'int'); @@ -262,7 +276,9 @@ if (empty($reshook)) foreach ($orders as $id_order) { $cmd = new CommandeFournisseur($db); - if ($cmd->fetch($id_order) <= 0) continue; + if ($cmd->fetch($id_order) <= 0) { + continue; + } $objecttmp = new FactureFournisseur($db); if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) { @@ -274,11 +290,12 @@ if (empty($reshook)) $objecttmp->mode_reglement_id = $cmd->mode_reglement_id; $objecttmp->fk_project = $cmd->fk_project; $objecttmp->multicurrency_code = $cmd->multicurrency_code; - if (empty($createbills_onebythird)) $objecttmp->ref_client = $cmd->ref_client; + if (empty($createbills_onebythird)) { + $objecttmp->ref_client = $cmd->ref_client; + } $datefacture = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); - if (empty($datefacture)) - { + if (empty($datefacture)) { $datefacture = dol_now(); } @@ -295,8 +312,7 @@ if (empty($reshook)) } } - if ($objecttmp->id > 0) - { + if ($objecttmp->id > 0) { $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element ("; $sql .= "fk_source"; $sql .= ", sourcetype"; @@ -309,16 +325,13 @@ if (empty($reshook)) $sql .= ", '".$db->escape($objecttmp->element)."'"; $sql .= ")"; - if (!$db->query($sql)) - { + if (!$db->query($sql)) { $erorr++; } - if (!$error) - { + if (!$error) { $lines = $cmd->lines; - if (empty($lines) && method_exists($cmd, 'fetch_lines')) - { + if (empty($lines) && method_exists($cmd, 'fetch_lines')) { $cmd->fetch_lines(); $lines = $cmd->lines; } @@ -326,11 +339,9 @@ if (empty($reshook)) $fk_parent_line = 0; $num = count($lines); - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); - if ($lines[$i]->subprice < 0) - { + if ($lines[$i]->subprice < 0) { // Negative line, we create a discount line $discount = new DiscountAbsolute($db); $discount->fk_soc = $objecttmp->socid; @@ -341,8 +352,7 @@ if (empty($reshook)) $discount->fk_user = $user->id; $discount->description = $desc; $discountid = $discount->create($user); - if ($discountid > 0) - { + if ($discountid > 0) { $result = $objecttmp->insert_discount($discountid); //$result=$discount->link_to_invoice($lineid,$id); } else { @@ -355,17 +365,28 @@ if (empty($reshook)) $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); // Date start $date_start = false; - if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start; + if ($lines[$i]->date_debut_prevue) { + $date_start = $lines[$i]->date_debut_prevue; + } + if ($lines[$i]->date_debut_reel) { + $date_start = $lines[$i]->date_debut_reel; + } + if ($lines[$i]->date_start) { + $date_start = $lines[$i]->date_start; + } //Date end $date_end = false; - if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end; + if ($lines[$i]->date_fin_prevue) { + $date_end = $lines[$i]->date_fin_prevue; + } + if ($lines[$i]->date_fin_reel) { + $date_end = $lines[$i]->date_fin_reel; + } + if ($lines[$i]->date_end) { + $date_end = $lines[$i]->date_end; + } // Reset fk_parent_line for no child products and special product - if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) - { + if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9) { $fk_parent_line = 0; } $result = $objecttmp->addline( @@ -393,8 +414,7 @@ if (empty($reshook)) $lines[$i]->special_code, $fk_parent_line ); - if ($result > 0) - { + if ($result > 0) { $lineid = $result; } else { $lineid = 0; @@ -402,8 +422,7 @@ if (empty($reshook)) break; } // Defined the new fk_parent_line - if ($result > 0 && $lines[$i]->product_type == 9) - { + if ($result > 0 && $lines[$i]->product_type == 9) { $fk_parent_line = $result; } } @@ -413,8 +432,11 @@ if (empty($reshook)) $cmd->classifyBilled($user); // TODO Move this in workflow like done for customer orders - if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp; - else $TFact[$objecttmp->id] = $objecttmp; + if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) { + $TFactThird[$cmd->socid] = $objecttmp; + } else { + $TFact[$objecttmp->id] = $objecttmp; + } } // Build doc with all invoices @@ -424,11 +446,9 @@ if (empty($reshook)) if (!$error && $validate_invoices) { $massaction = $action = 'builddoc'; - foreach ($TAllFact as &$objecttmp) - { + foreach ($TAllFact as &$objecttmp) { $objecttmp->validate($user); - if ($result <= 0) - { + if ($result <= 0) { $error++; setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); break; @@ -446,8 +466,7 @@ if (empty($reshook)) $massaction = $action = 'confirm_createsupplierbills'; } - if (!$error) - { + if (!$error) { $db->commit(); if ($nb_bills_created == 1) { @@ -460,29 +479,73 @@ if (empty($reshook)) // Make a redirect to avoid to bill twice if we make a refresh or back $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sall) $param .= '&sall='.urlencode($sall); - if ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($search_status != '') $param .= '&search_status='.urlencode($search_status); - if ($search_orderday) $param .= '&search_orderday='.urlencode($search_orderday); - if ($search_ordermonth) $param .= '&search_ordermonth='.urlencode($search_ordermonth); - if ($search_orderyear) $param .= '&search_orderyear='.urlencode($search_orderyear); - if ($search_deliveryday) $param .= '&search_deliveryday='.urlencode($search_deliveryday); - if ($search_deliverymonth) $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); - if ($search_deliveryyear) $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_company) $param .= '&search_company='.urlencode($search_company); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($sall) { + $param .= '&sall='.urlencode($sall); + } + if ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($search_status != '') { + $param .= '&search_status='.urlencode($search_status); + } + if ($search_orderday) { + $param .= '&search_orderday='.urlencode($search_orderday); + } + if ($search_ordermonth) { + $param .= '&search_ordermonth='.urlencode($search_ordermonth); + } + if ($search_orderyear) { + $param .= '&search_orderyear='.urlencode($search_orderyear); + } + if ($search_deliveryday) { + $param .= '&search_deliveryday='.urlencode($search_deliveryday); + } + if ($search_deliverymonth) { + $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); + } + if ($search_deliveryyear) { + $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } //if ($search_ref_customer) $param .= '&search_ref_customer='.urlencode($search_ref_customer); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht); - if ($search_total_tva != '') $param .= '&search_total_tva='.urlencode($search_total_tva); - if ($search_total_ttc != '') $param .= '&search_total_ttc='.urlencode($search_total_ttc); - if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($billed != '') $param .= '&billed='.urlencode($billed); + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_total_ht != '') { + $param .= '&search_total_ht='.urlencode($search_total_ht); + } + if ($search_total_tva != '') { + $param .= '&search_total_tva='.urlencode($search_total_tva); + } + if ($search_total_ttc != '') { + $param .= '&search_total_ttc='.urlencode($search_total_ttc); + } + if ($search_project_ref >= 0) { + $param .= "&search_project_ref=".urlencode($search_project_ref); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($billed != '') { + $param .= '&billed='.urlencode($billed); + } header("Location: ".$_SERVER['PHP_SELF'].'?'.$param); exit; @@ -513,8 +576,7 @@ $formother = new FormOther($db); $formcompany = new FormCompany($db); $title = $langs->trans("ListOfSupplierOrders"); -if ($socid > 0) -{ +if ($socid > 0) { $fourn = new Fournisseur($db); $fourn->fetch($socid); $title .= ' - '.$fourn->name; @@ -528,14 +590,18 @@ if ($socid > 0) elseif ($search_status == '6,7') $title .= ' - '.$langs->trans("StatusOrderCanceled"); elseif (is_numeric($search_status) && $search_status >= 0) $title .= ' - '.$commandestatic->LibStatut($search_status); }*/ -if ($search_billed > 0) $title .= ' - '.$langs->trans("Billed"); +if ($search_billed > 0) { + $title .= ' - '.$langs->trans("Billed"); +} //$help_url="EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_Pedidos_de_clientes"; $help_url = ''; // llxHeader('',$title,$help_url); $sql = 'SELECT'; -if ($sall || $search_product_category > 0 || $search_user > 0) $sql = 'SELECT DISTINCT'; +if ($sall || $search_product_category > 0 || $search_user > 0) { + $sql = 'SELECT DISTINCT'; +} $sql .= ' s.rowid as socid, s.nom as name, s.town, s.zip, s.fk_pays, s.client, s.code_client, s.email,'; $sql .= " typent.code as typent_code,"; $sql .= " state.code_departement as state_code, state.nom as state_name,"; @@ -547,7 +613,9 @@ $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_title, $sql .= " u.firstname, u.lastname, u.photo, u.login, u.email as user_email"; // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); @@ -558,15 +626,22 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; $sql .= ", ".MAIN_DB_PREFIX."commande_fournisseur as cf"; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cf.rowid = ef.fk_object)"; -if ($sall || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commande_fournisseurdet as pd ON cf.rowid=pd.fk_commande'; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (cf.rowid = ef.fk_object)"; +} +if ($sall || $search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commande_fournisseurdet as pd ON cf.rowid=pd.fk_commande'; +} +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u ON cf.fk_user_author = u.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = cf.fk_projet"; // We'll need this table joined to the select in order to filter by sale -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -if ($search_user > 0) -{ +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } @@ -575,39 +650,93 @@ $reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object $sql .= $hookmanager->resPrint; $sql .= ' WHERE cf.fk_soc = s.rowid'; $sql .= ' AND cf.entity IN ('.getEntity('supplier_order').')'; -if ($socid > 0) $sql .= " AND s.rowid = ".$socid; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($search_ref) $sql .= natural_search('cf.ref', $search_ref); -if ($search_refsupp) $sql .= natural_search("cf.ref_supplier", $search_refsupp); -if ($sall) $sql .= natural_search(array_keys($fieldstosearchall), $sall); -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_request_author) $sql .= natural_search(array('u.lastname', 'u.firstname', 'u.login'), $search_request_author); -if ($search_billed != '' && $search_billed >= 0) $sql .= " AND cf.billed = ".$db->escape($search_billed); -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; +if ($socid > 0) { + $sql .= " AND s.rowid = ".$socid; +} +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($search_ref) { + $sql .= natural_search('cf.ref', $search_ref); +} +if ($search_refsupp) { + $sql .= natural_search("cf.ref_supplier", $search_refsupp); +} +if ($sall) { + $sql .= natural_search(array_keys($fieldstosearchall), $sall); +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_request_author) { + $sql .= natural_search(array('u.lastname', 'u.firstname', 'u.login'), $search_request_author); +} +if ($search_billed != '' && $search_billed >= 0) { + $sql .= " AND cf.billed = ".$db->escape($search_billed); +} +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} //Required triple check because statut=0 means draft filter -if (GETPOST('statut', 'intcomma') !== '') +if (GETPOST('statut', 'intcomma') !== '') { $sql .= " AND cf.fk_statut IN (".$db->sanitize($db->escape($db->escape(GETPOST('statut', 'intcomma')))).")"; -if ($search_status != '' && $search_status != '-1') +} +if ($search_status != '' && $search_status != '-1') { $sql .= " AND cf.fk_statut IN (".$db->sanitize($db->escape($search_status)).")"; +} $sql .= dolSqlDateFilter("cf.date_commande", $search_orderday, $search_ordermonth, $search_orderyear); $sql .= dolSqlDateFilter("cf.date_livraison", $search_deliveryday, $search_deliverymonth, $search_deliveryyear); -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$db->escape($search_sale); -if ($search_user > 0) $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='supplier_order' AND tc.source='internal' AND ec.element_id = cf.rowid AND ec.fk_socpeople = ".$db->escape($search_user); -if ($search_total_ht != '') $sql .= natural_search('cf.total_ht', $search_total_ht, 1); -if ($search_total_tva != '') $sql .= natural_search('cf.total_tva', $search_total_tva, 1); -if ($search_total_ttc != '') $sql .= natural_search('cf.total_ttc', $search_total_ttc, 1); -if ($search_multicurrency_code != '') $sql .= ' AND cf.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; -if ($search_multicurrency_tx != '') $sql .= natural_search('cf.multicurrency_tx', $search_multicurrency_tx, 1); -if ($search_multicurrency_montant_ht != '') $sql .= natural_search('cf.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); -if ($search_multicurrency_montant_tva != '') $sql .= natural_search('cf.multicurrency_total_tva', $search_multicurrency_montant_tva, 1); -if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('cf.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); -if ($search_project_ref != '') $sql .= natural_search("p.ref", $search_project_ref); +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$db->sanitize($db->escape($search_country)).')'; +} +if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $sql .= " AND s.fk_typent IN (".$db->sanitize($db->escape($search_type_thirdparty)).')'; +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_sale > 0) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$db->escape($search_sale); +} +if ($search_user > 0) { + $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='supplier_order' AND tc.source='internal' AND ec.element_id = cf.rowid AND ec.fk_socpeople = ".$db->escape($search_user); +} +if ($search_total_ht != '') { + $sql .= natural_search('cf.total_ht', $search_total_ht, 1); +} +if ($search_total_tva != '') { + $sql .= natural_search('cf.total_tva', $search_total_tva, 1); +} +if ($search_total_ttc != '') { + $sql .= natural_search('cf.total_ttc', $search_total_ttc, 1); +} +if ($search_multicurrency_code != '') { + $sql .= ' AND cf.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +} +if ($search_multicurrency_tx != '') { + $sql .= natural_search('cf.multicurrency_tx', $search_multicurrency_tx, 1); +} +if ($search_multicurrency_montant_ht != '') { + $sql .= natural_search('cf.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +} +if ($search_multicurrency_montant_tva != '') { + $sql .= natural_search('cf.multicurrency_total_tva', $search_multicurrency_montant_tva, 1); +} +if ($search_multicurrency_montant_ttc != '') { + $sql .= natural_search('cf.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +} +if ($search_project_ref != '') { + $sql .= natural_search("p.ref", $search_project_ref); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; // Add where from hooks @@ -619,12 +748,10 @@ $sql .= $db->order($sortfield, $sortorder); // Count total nb of records $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -634,14 +761,12 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/fourn/commande/card.php?id='.$id); @@ -651,36 +776,96 @@ if ($resql) llxHeader('', $title, $help_url); $param = ''; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($sall) $param .= '&sall='.urlencode($sall); - if ($socid > 0) $param .= '&socid='.urlencode($socid); - if ($sall) $param .= "&search_all=".urlencode($sall); - if ($search_orderday) $param .= '&search_orderday='.urlencode($search_orderday); - if ($search_ordermonth) $param .= '&search_ordermonth='.urlencode($search_ordermonth); - if ($search_orderyear) $param .= '&search_orderyear='.urlencode($search_orderyear); - if ($search_deliveryday) $param .= '&search_deliveryday='.urlencode($search_deliveryday); - if ($search_deliverymonth) $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); - if ($search_deliveryyear) $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_company) $param .= '&search_company='.urlencode($search_company); - if ($search_user > 0) $param .= '&search_user='.urlencode($search_user); - if ($search_request_author) $param .= '&search_request_author='.urlencode($search_request_author); - if ($search_sale > 0) $param .= '&search_sale='.urlencode($search_sale); - if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht); - if ($search_total_ttc != '') $param .= "&search_total_ttc=".urlencode($search_total_ttc); - if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); - if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); - if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); - if ($search_multicurrency_montant_tva != '') $param .= '&search_multicurrency_montant_tva='.urlencode($search_multicurrency_montant_tva); - if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); - if ($search_refsupp) $param .= "&search_refsupp=".urlencode($search_refsupp); - if ($search_status != '' && $search_status != '-1') $param .= "&search_status=".urlencode($search_status); - if ($search_project_ref >= 0) $param .= "&search_project_ref=".urlencode($search_project_ref); - if ($search_billed != '') $param .= "&search_billed=".urlencode($search_billed); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($sall) { + $param .= '&sall='.urlencode($sall); + } + if ($socid > 0) { + $param .= '&socid='.urlencode($socid); + } + if ($sall) { + $param .= "&search_all=".urlencode($sall); + } + if ($search_orderday) { + $param .= '&search_orderday='.urlencode($search_orderday); + } + if ($search_ordermonth) { + $param .= '&search_ordermonth='.urlencode($search_ordermonth); + } + if ($search_orderyear) { + $param .= '&search_orderyear='.urlencode($search_orderyear); + } + if ($search_deliveryday) { + $param .= '&search_deliveryday='.urlencode($search_deliveryday); + } + if ($search_deliverymonth) { + $param .= '&search_deliverymonth='.urlencode($search_deliverymonth); + } + if ($search_deliveryyear) { + $param .= '&search_deliveryyear='.urlencode($search_deliveryyear); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } + if ($search_user > 0) { + $param .= '&search_user='.urlencode($search_user); + } + if ($search_request_author) { + $param .= '&search_request_author='.urlencode($search_request_author); + } + if ($search_sale > 0) { + $param .= '&search_sale='.urlencode($search_sale); + } + if ($search_total_ht != '') { + $param .= '&search_total_ht='.urlencode($search_total_ht); + } + if ($search_total_ttc != '') { + $param .= "&search_total_ttc=".urlencode($search_total_ttc); + } + if ($search_multicurrency_code != '') { + $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + } + if ($search_multicurrency_tx != '') { + $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + } + if ($search_multicurrency_montant_ht != '') { + $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + } + if ($search_multicurrency_montant_tva != '') { + $param .= '&search_multicurrency_montant_tva='.urlencode($search_multicurrency_montant_tva); + } + if ($search_multicurrency_montant_ttc != '') { + $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); + } + if ($search_refsupp) { + $param .= "&search_refsupp=".urlencode($search_refsupp); + } + if ($search_status != '' && $search_status != '-1') { + $param .= "&search_status=".urlencode($search_status); + } + if ($search_project_ref >= 0) { + $param .= "&search_project_ref=".urlencode($search_project_ref); + } + if ($search_billed != '') { + $param .= "&search_billed=".urlencode($search_billed); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -695,18 +880,28 @@ if ($resql) 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); - if ($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); - if ($user->rights->fournisseur->commande->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); + if ($user->rights->fournisseur->facture->creer) { + $arrayofmassactions['createbills'] = $langs->trans("CreateInvoiceForThisSupplier"); + } + if ($user->rights->fournisseur->commande->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete', 'createbills'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/fourn/commande/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewOrder'), '', 'fa fa-plus-circle', $url, '', $user->rights->fournisseur->commande->creer); // Lines of title fields print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -723,8 +918,7 @@ if ($resql) $trackid = 'sord'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($massaction == 'createbills') - { + if ($massaction == 'createbills') { //var_dump($_REQUEST); print '<input type="hidden" name="massaction" value="confirm_createsupplierbills">'; @@ -763,17 +957,17 @@ if ($resql) print '<br>'; } - if ($sall) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($sall) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'</div>'; } $moreforfilter = ''; // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + if ($user->rights->societe->client->voir || $socid) { $langs->load("commercial"); $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; @@ -781,16 +975,14 @@ if ($resql) $moreforfilter .= '</div>'; } // If the user can view other users - if ($user->rights->user->user->lire) - { + if ($user->rights->user->user->lire) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); $moreforfilter .= '</div>'; } // If the user can view prospects other than his' - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -800,11 +992,13 @@ if ($resql) } $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 (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; + } else { + $moreforfilter = $hookmanager->resPrint; + } - if (!empty($moreforfilter)) - { + if (!empty($moreforfilter)) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; @@ -829,126 +1023,116 @@ if ($resql) print '<tr class="liste_titre_filter">'; // Ref - if (!empty($arrayfields['cf.ref']['checked'])) - { + if (!empty($arrayfields['cf.ref']['checked'])) { print '<td class="liste_titre"><input size="8" type="text" class="flat maxwidth75" name="search_ref" value="'.$search_ref.'"></td>'; } // Ref customer - if (!empty($arrayfields['cf.ref_supplier']['checked'])) - { + if (!empty($arrayfields['cf.ref_supplier']['checked'])) { print '<td class="liste_titre"><input type="text" class="flat maxwidth75" name="search_refsupp" value="'.$search_refsupp.'"></td>'; } // Project ref - if (!empty($arrayfields['p.project_ref']['checked'])) - { + if (!empty($arrayfields['p.project_ref']['checked'])) { print '<td class="liste_titre"><input type="text" class="flat maxwidth100" name="search_project_ref" value="'.$search_project_ref.'"></td>'; } // Request author - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { print '<td class="liste_titre">'; print '<input type="text" class="flat" size="6" name="search_request_author" value="'.$search_request_author.'">'; print '</td>'; } // Thirpdarty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre"><input type="text" size="6" class="flat" name="search_company" value="'.$search_company.'"></td>'; } // Town - if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="'.$search_town.'"></td>'; + if (!empty($arrayfields['s.town']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="'.$search_town.'"></td>'; + } // Zip - if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_zip" value="'.$search_zip.'"></td>'; + if (!empty($arrayfields['s.zip']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_zip" value="'.$search_zip.'"></td>'; + } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat maxwidth50" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; print '</td>'; } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="liste_titre center">'; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print '</td>'; } // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone center">'; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print '</td>'; } // Date order - if (!empty($arrayfields['cf.date_commande']['checked'])) - { + if (!empty($arrayfields['cf.date_commande']['checked'])) { print '<td class="liste_titre nowraponall center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_orderday" value="'.$search_orderday.'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_orderday" value="'.$search_orderday.'">'; + } print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_ordermonth" value="'.$search_ordermonth.'">'; $formother->select_year($search_orderyear ? $search_orderyear : -1, 'search_orderyear', 1, 20, 5); print '</td>'; } // Date delivery - if (!empty($arrayfields['cf.date_livraison']['checked'])) - { + if (!empty($arrayfields['cf.date_livraison']['checked'])) { print '<td class="liste_titre nowraponall center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_deliveryday" value="'.$search_deliveryday.'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_deliveryday" value="'.$search_deliveryday.'">'; + } print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_deliverymonth" value="'.$search_deliverymonth.'">'; $formother->select_year($search_deliveryyear ? $search_deliveryyear : -1, 'search_deliveryyear', 1, 20, 5); print '</td>'; } - if (!empty($arrayfields['cf.total_ht']['checked'])) - { + if (!empty($arrayfields['cf.total_ht']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_total_ht" value="'.$search_total_ht.'">'; print '</td>'; } - if (!empty($arrayfields['cf.total_tva']['checked'])) - { + if (!empty($arrayfields['cf.total_tva']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_total_tva" value="'.$search_total_tva.'">'; print '</td>'; } - if (!empty($arrayfields['cf.total_ttc']['checked'])) - { + if (!empty($arrayfields['cf.total_ttc']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_total_ttc" value="'.$search_total_ttc.'">'; print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_code']['checked'])) { // Currency print '<td class="liste_titre">'; print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) { // Currency rate print '<td class="liste_titre">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">'; print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">'; print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_total_tva']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_tva']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_tva" value="'.dol_escape_htmltag($search_multicurrency_montant_tva).'">'; print '</td>'; } - if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">'; @@ -962,27 +1146,23 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['cf.datec']['checked'])) - { + if (!empty($arrayfields['cf.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification - if (!empty($arrayfields['cf.tms']['checked'])) - { + if (!empty($arrayfields['cf.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Status - if (!empty($arrayfields['cf.fk_statut']['checked'])) - { + if (!empty($arrayfields['cf.fk_statut']['checked'])) { print '<td class="liste_titre right">'; $formorder->selectSupplierOrderStatus($search_status, 1, 'search_status'); print '</td>'; } // Status billed - if (!empty($arrayfields['cf.billed']['checked'])) - { + if (!empty($arrayfields['cf.billed']['checked'])) { print '<td class="liste_titre center">'; print $form->selectyesno('search_billed', $search_billed, 1, 0, 1, 1); print '</td>'; @@ -997,37 +1177,87 @@ if ($resql) // Fields title print '<tr class="liste_titre">'; - if (!empty($arrayfields['cf.ref']['checked'])) print_liste_field_titre($arrayfields['cf.ref']['label'], $_SERVER["PHP_SELF"], "cf.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cf.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['cf.ref_supplier']['label'], $_SERVER["PHP_SELF"], "cf.ref_supplier", "", $param, '', $sortfield, $sortorder, 'tdoverflowmax100imp '); - if (!empty($arrayfields['p.project_ref']['checked'])) print_liste_field_titre($arrayfields['p.project_ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], "u.login", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cf.fk_author']['checked'])) print_liste_field_titre($arrayfields['cf.fk_author']['label'], $_SERVER["PHP_SELF"], "cf.fk_author", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cf.date_commande']['checked'])) print_liste_field_titre($arrayfields['cf.date_commande']['label'], $_SERVER["PHP_SELF"], "cf.date_commande", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cf.date_livraison']['checked'])) print_liste_field_titre($arrayfields['cf.date_livraison']['label'], $_SERVER["PHP_SELF"], 'cf.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['cf.total_ht']['checked'])) print_liste_field_titre($arrayfields['cf.total_ht']['label'], $_SERVER["PHP_SELF"], "cf.total_ht", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['cf.total_tva']['checked'])) print_liste_field_titre($arrayfields['cf.total_tva']['label'], $_SERVER["PHP_SELF"], "cf.total_tva", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['cf.total_ttc']['checked'])) print_liste_field_titre($arrayfields['cf.total_ttc']['label'], $_SERVER["PHP_SELF"], "cf.total_ttc", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['cf.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_code', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_tx', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['cf.multicurrency_total_tva']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_total_tva']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['cf.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['cf.ref']['checked'])) { + print_liste_field_titre($arrayfields['cf.ref']['label'], $_SERVER["PHP_SELF"], "cf.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.ref_supplier']['checked'])) { + print_liste_field_titre($arrayfields['cf.ref_supplier']['label'], $_SERVER["PHP_SELF"], "cf.ref_supplier", "", $param, '', $sortfield, $sortorder, 'tdoverflowmax100imp '); + } + if (!empty($arrayfields['p.project_ref']['checked'])) { + print_liste_field_titre($arrayfields['p.project_ref']['label'], $_SERVER["PHP_SELF"], "p.ref", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['u.login']['checked'])) { + print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], "u.login", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER["PHP_SELF"], "s.nom", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['state.nom']['checked'])) { + print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['country.code_iso']['checked'])) { + print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cf.fk_author']['checked'])) { + print_liste_field_titre($arrayfields['cf.fk_author']['label'], $_SERVER["PHP_SELF"], "cf.fk_author", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.date_commande']['checked'])) { + print_liste_field_titre($arrayfields['cf.date_commande']['label'], $_SERVER["PHP_SELF"], "cf.date_commande", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cf.date_livraison']['checked'])) { + print_liste_field_titre($arrayfields['cf.date_livraison']['label'], $_SERVER["PHP_SELF"], 'cf.date_livraison', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['cf.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['cf.total_ht']['label'], $_SERVER["PHP_SELF"], "cf.total_ht", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['cf.total_tva']['checked'])) { + print_liste_field_titre($arrayfields['cf.total_tva']['label'], $_SERVER["PHP_SELF"], "cf.total_tva", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['cf.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['cf.total_ttc']['label'], $_SERVER["PHP_SELF"], "cf.total_ttc", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['cf.multicurrency_code']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.multicurrency_total_tva']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_total_tva']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['cf.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'cf.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['cf.datec']['checked'])) print_liste_field_titre($arrayfields['cf.datec']['label'], $_SERVER["PHP_SELF"], "cf.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['cf.tms']['checked'])) print_liste_field_titre($arrayfields['cf.tms']['label'], $_SERVER["PHP_SELF"], "cf.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['cf.fk_statut']['checked'])) print_liste_field_titre($arrayfields['cf.fk_statut']['label'], $_SERVER["PHP_SELF"], "cf.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['cf.billed']['checked'])) print_liste_field_titre($arrayfields['cf.billed']['label'], $_SERVER["PHP_SELF"], 'cf.billed', '', $param, '', $sortfield, $sortorder, 'center '); + if (!empty($arrayfields['cf.datec']['checked'])) { + print_liste_field_titre($arrayfields['cf.datec']['label'], $_SERVER["PHP_SELF"], "cf.date_creation", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['cf.tms']['checked'])) { + print_liste_field_titre($arrayfields['cf.tms']['label'], $_SERVER["PHP_SELF"], "cf.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['cf.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['cf.fk_statut']['label'], $_SERVER["PHP_SELF"], "cf.fk_statut", "", $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['cf.billed']['checked'])) { + print_liste_field_titre($arrayfields['cf.billed']['label'], $_SERVER["PHP_SELF"], 'cf.billed', '', $param, '', $sortfield, $sortorder, 'center '); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; @@ -1042,8 +1272,7 @@ if ($resql) $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $notshippable = 0; @@ -1067,8 +1296,7 @@ if ($resql) print '<tr class="oddeven">'; // Ref - if (!empty($arrayfields['cf.ref']['checked'])) - { + if (!empty($arrayfields['cf.ref']['checked'])) { print '<td class="nowrap">'; // Picto + Ref @@ -1079,24 +1307,30 @@ if ($resql) print $formfile->getDocumentsLink($objectstatic->element, $filename, $filedir); print '</td>'."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref Supplier - if (!empty($arrayfields['cf.ref_supplier']['checked'])) - { + if (!empty($arrayfields['cf.ref_supplier']['checked'])) { print '<td>'.$obj->ref_supplier.'</td>'."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project - if (!empty($arrayfields['p.project_ref']['checked'])) - { + if (!empty($arrayfields['p.project_ref']['checked'])) { $projectstatic->id = $obj->project_id; $projectstatic->ref = $obj->project_ref; $projectstatic->title = $obj->project_title; print '<td>'; - if ($obj->project_id > 0) print $projectstatic->getNomUrl(1); + if ($obj->project_id > 0) { + print $projectstatic->getNomUrl(1); + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Author $userstatic->id = $obj->fk_user_author; @@ -1105,68 +1339,78 @@ if ($resql) $userstatic->login = $obj->login; $userstatic->photo = $obj->photo; $userstatic->email = $obj->user_email; - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { print '<td class="tdoverflowmax150">'; - if ($userstatic->id) print $userstatic->getNomUrl(1); + if ($userstatic->id) { + print $userstatic->getNomUrl(1); + } print "</td>"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Thirdparty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="tdoverflowmax150">'; $thirdpartytmp->id = $obj->socid; $thirdpartytmp->name = $obj->name; $thirdpartytmp->email = $obj->email; print $thirdpartytmp->getNomUrl(1, 'supplier'); print '</td>'."\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print '<td>'; print $obj->town; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print '<td>'; print $obj->zip; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "<td>".$obj->state_name."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="center">'; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="center">'; - if (count($typenArray) == 0) $typenArray = $formcompany->typent_array(1); + if (count($typenArray) == 0) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Order date - if (!empty($arrayfields['cf.date_commande']['checked'])) - { + if (!empty($arrayfields['cf.date_commande']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_commande), 'day'); if ($objectstatic->statut != $objectstatic::STATUS_ORDERSENT && $objectstatic->statut != $objectstatic::STATUS_RECEIVED_PARTIALLY) { @@ -1175,11 +1419,12 @@ if ($resql) } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Plannned date of delivery - if (!empty($arrayfields['cf.date_livraison']['checked'])) - { + if (!empty($arrayfields['cf.date_livraison']['checked'])) { print '<td class="center">'; print dol_print_date($db->jdate($obj->date_livraison), 'day'); if ($objectstatic->statut == $objectstatic::STATUS_ORDERSENT || $objectstatic->statut == $objectstatic::STATUS_RECEIVED_PARTIALLY) { @@ -1188,65 +1433,81 @@ if ($resql) } } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['cf.total_ht']['checked'])) - { + if (!empty($arrayfields['cf.total_ht']['checked'])) { print '<td class="right">'.price($obj->total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_ht'; + } $totalarray['val']['cf.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['cf.total_tva']['checked'])) - { + if (!empty($arrayfields['cf.total_tva']['checked'])) { print '<td class="right">'.price($obj->total_tva)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_tva'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_tva'; + } $totalarray['val']['cf.total_tva'] += $obj->total_tva; } // Amount TTC - if (!empty($arrayfields['cf.total_ttc']['checked'])) - { + if (!empty($arrayfields['cf.total_ttc']['checked'])) { print '<td class="right">'.price($obj->total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'cf.total_ttc'; + } $totalarray['val']['cf.total_ttc'] += $obj->total_ttc; } // Currency - if (!empty($arrayfields['cf.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_code']['checked'])) { print '<td class="nowrap">'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Currency rate - if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_tx']['checked'])) { print '<td class="nowrap">'; $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_ht']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount VAT - if (!empty($arrayfields['cf.multicurrency_total_tva']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_tva']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_tva)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount TTC - if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['cf.multicurrency_total_ttc']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Extra fields @@ -1256,44 +1517,51 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['cf.datec']['checked'])) - { + if (!empty($arrayfields['cf.datec']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['cf.tms']['checked'])) - { + if (!empty($arrayfields['cf.tms']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['cf.fk_statut']['checked'])) - { + if (!empty($arrayfields['cf.fk_statut']['checked'])) { print '<td class="right nowrap">'.$objectstatic->LibStatut($obj->fk_statut, 5, $obj->billed).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Billed - if (!empty($arrayfields['cf.billed']['checked'])) - { + if (!empty($arrayfields['cf.billed']['checked'])) { print '<td class="center">'.yn($obj->billed).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->rowid, $arrayofselected)) $selected = 1; + if (in_array($obj->rowid, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$obj->rowid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->rowid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; @@ -1317,7 +1585,9 @@ if ($resql) print '</form>'."\n"; $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/fourn/commande/note.php b/htdocs/fourn/commande/note.php index dea5ad69afa..9f8c192752c 100644 --- a/htdocs/fourn/commande/note.php +++ b/htdocs/fourn/commande/note.php @@ -40,7 +40,9 @@ $ref = GETPOST('ref'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'commande_fournisseur', 'commande'); $object = new CommandeFournisseur($db); @@ -72,10 +74,8 @@ $form = new Form($db); $now = dol_now(); -if ($id > 0 || !empty($ref)) -{ - if ($result >= 0) - { +if ($id > 0 || !empty($ref)) { + if ($result >= 0) { $object->fetch_thirdparty(); $author = new User($db); @@ -97,12 +97,10 @@ if ($id > 0 || !empty($ref)) // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; diff --git a/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php b/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php index 57dfb90e3fd..a152ca26ff1 100644 --- a/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php +++ b/htdocs/fourn/commande/tpl/linkedobjectblock.tpl.php @@ -17,8 +17,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -37,41 +36,41 @@ $langs->load("orders"); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - <tr class="<?php echo $trclass; ?>"> - <td><?php echo $langs->trans("SupplierOrder"); ?></td> - <td><a href="<?php echo DOL_URL_ROOT.'/fourn/commande/card.php?id='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowOrder"), "order").' '.$objectlink->ref; ?></a></td> - <td class="left"><?php echo $objectlink->ref_supplier; ?></td> - <td class="center"><?php echo dol_print_date($objectlink->date, 'day'); ?></td> - <td class="right"><?php + <tr class="<?php echo $trclass; ?>"> + <td><?php echo $langs->trans("SupplierOrder"); ?></td> + <td><a href="<?php echo DOL_URL_ROOT.'/fourn/commande/card.php?id='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowOrder"), "order").' '.$objectlink->ref; ?></a></td> + <td class="left"><?php echo $objectlink->ref_supplier; ?></td> + <td class="center"><?php echo dol_print_date($objectlink->date, 'day'); ?></td> + <td class="right"><?php if ($user->rights->fournisseur->commande->lire) { $total = $total + $objectlink->total_ht; echo price($objectlink->total_ht); } ?></td> - <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> - <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> - </tr> + <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> + <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> + </tr> <?php } -if (count($linkedObjectBlock) > 1) -{ +if (count($linkedObjectBlock) > 1) { ?> - <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> - <td><?php echo $langs->trans("Total"); ?></td> - <td></td> - <td class="center"></td> - <td class="center"></td> - <td class="right"><?php echo price($total); ?></td> - <td class="right"></td> - <td class="right"></td> - </tr> - <?php + <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> + <td><?php echo $langs->trans("Total"); ?></td> + <td></td> + <td class="center"></td> + <td class="center"></td> + <td class="right"><?php echo price($total); ?></td> + <td class="right"></td> + <td class="right"></td> + </tr> + <?php } print "<!-- END PHP TEMPLATE -->\n"; diff --git a/htdocs/fourn/contact.php b/htdocs/fourn/contact.php index 781fd4b6e9a..82c8df6ac66 100644 --- a/htdocs/fourn/contact.php +++ b/htdocs/fourn/contact.php @@ -35,8 +35,7 @@ $langs->load("companies"); llxHeader(); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -45,12 +44,18 @@ $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 +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 = "ASC"; -if (!$sortfield) $sortfield = "p.name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "p.name"; +} $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; @@ -59,14 +64,20 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; */ $sql = "SELECT s.rowid as socid, s.nom as name, st.libelle as stcomm, p.rowid as cidp, p.lastname, p.firstname, p.email, p.phone"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; +} $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."socpeople as p, ".MAIN_DB_PREFIX."c_stcomm as st"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE s.fk_stcomm = st.id"; $sql .= " AND s.fournisseur = 1"; $sql .= " AND s.rowid = p.fk_soc"; $sql .= " AND s.entity IN (".getEntity('societe').")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} if (dol_strlen($stcomm)) { $sql .= " AND s.fk_stcomm=$stcomm"; @@ -90,8 +101,7 @@ $sql .= " ORDER BY $sortfield $sortorder "; $sql .= $db->plimit($limit, $offset); $result = $db->query($sql); -if ($result) -{ +if ($result) { $num = $db->num_rows($result); $title = (!empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT) ? $langs->trans("ListOfContacts") : $langs->trans("ListOfContactsAddresses")); @@ -107,8 +117,7 @@ if ($result) print "</tr>\n"; $i = 0; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($result); print '<tr class="oddeven">'; diff --git a/htdocs/fourn/facture/card.php b/htdocs/fourn/facture/card.php index 1e88aaf74c4..761e1bb9577 100644 --- a/htdocs/fourn/facture/card.php +++ b/htdocs/fourn/facture/card.php @@ -54,11 +54,15 @@ if (!empty($conf->projet->enabled)) { if (!empty($conf->variants->enabled)) { require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php'; } -if (!empty($conf->accounting->enabled)) require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +if (!empty($conf->accounting->enabled)) { + require_once DOL_DOCUMENT_ROOT.'/accountancy/class/accountingjournal.class.php'; +} $langs->loadLangs(array('bills', 'compta', 'suppliers', 'companies', 'products', 'banks', 'admin')); -if (!empty($conf->incoterm->enabled)) $langs->load('incoterm'); +if (!empty($conf->incoterm->enabled)) { + $langs->load('incoterm'); +} $id = (GETPOST('facid', 'int') ? GETPOST('facid', 'int') : GETPOST('id', 'int')); $socid = GETPOST('socid', 'int'); @@ -86,17 +90,22 @@ $extrafields = new ExtraFields($db); $extrafields->fetch_name_optionals_label($object->table_element); // Load object -if ($id > 0 || !empty($ref)) -{ +if ($id > 0 || !empty($ref)) { $ret = $object->fetch($id, $ref); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } $ret = $object->fetch_thirdparty(); - if ($ret < 0) dol_print_error($db, $object->error); + if ($ret < 0) { + dol_print_error($db, $object->error); + } } // Security check $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $isdraft = (($object->statut == FactureFournisseur::STATUS_DRAFT) ? 1 : 0); $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture', 'fk_soc', 'rowid', $isdraft); @@ -124,14 +133,13 @@ $error = 0; $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if ($cancel) - { - if (!empty($backtopage)) - { +if (empty($reshook)) { + if ($cancel) { + if (!empty($backtopage)) { header("Location: ".$backtopage); exit; } @@ -145,24 +153,23 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; // Must be include, not include_once // Link invoice to order - if (GETPOST('linkedOrder') && empty($cancel) && $id > 0) - { + if (GETPOST('linkedOrder') && empty($cancel) && $id > 0) { $object->fetch($id); $object->fetch_thirdparty(); $result = $object->add_object_linked('order_supplier', GETPOST('linkedOrder')); } // Action clone object - if ($action == 'confirm_clone' && $confirm == 'yes' && $permissiontoadd) - { + 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. - if (GETPOST('newsupplierref', 'alphanohtml')) $objectutil->ref_supplier = GETPOST('newsupplierref', 'alphanohtml'); + 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) - { + if ($result > 0) { header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result); exit; } else { @@ -170,15 +177,14 @@ if (empty($reshook)) setEventMessages($objectutil->error, $objectutil->errors, 'errors'); $action = ''; } - } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { + } elseif ($action == 'confirm_valid' && $confirm == 'yes' && $usercanvalidate) { $idwarehouse = GETPOST('idwarehouse'); $object->fetch($id); $object->fetch_thirdparty(); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) { $qualified_for_stock_change = $object->hasProductsOrServices(2); } else { $qualified_for_stock_change = $object->hasProductsOrServices(1); @@ -187,8 +193,7 @@ if (empty($reshook)) // 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) - { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -201,12 +206,15 @@ if (empty($reshook)) setEventMessages($object->error, $object->errors, 'errors'); } else { // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -215,7 +223,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } } } @@ -225,25 +235,19 @@ if (empty($reshook)) $isErasable = $object->is_erasable(); - if (($usercandelete && $isErasable > 0) || ($usercancreate && $isErasable == 1)) - { + if (($usercandelete && $isErasable > 0) || ($usercancreate && $isErasable == 1)) { $result = $object->delete($user); - if ($result > 0) - { + if ($result > 0) { header('Location: list.php?restore_lastsearch_values=1'); exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // Remove a product line - elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $usercancreate) { + // Remove a product line $result = $object->deleteline($lineid); - if ($result > 0) - { + if ($result > 0) { // Define output language /*$outputlangs = $langs; $newlang = ''; @@ -267,11 +271,8 @@ if (empty($reshook)) /* Fix bug 1485 : Reset action to avoid asking again confirmation on failure */ $action = ''; } - } - - // Delete link of credit note to invoice - elseif ($action == 'unlinkdiscount' && $usercancreate) - { + } elseif ($action == 'unlinkdiscount' && $usercancreate) { + // Delete link of credit note to invoice $discount = new DiscountAbsolute($db); $result = $discount->fetch(GETPOST("discountid")); $discount->unlink_invoice(); @@ -331,8 +332,12 @@ if (empty($reshook)) if (!$error) { $old_date_echeance = $object->date_echeance; $new_date_echeance = $object->calculate_date_lim_reglement(); - if ($new_date_echeance > $old_date_echeance) $object->date_echeance = $new_date_echeance; - if ($object->date_echeance < $object->date) $object->date_echeance = $object->date; + if ($new_date_echeance > $old_date_echeance) { + $object->date_echeance = $new_date_echeance; + } + if ($object->date_echeance < $object->date) { + $object->date_echeance = $object->date; + } $result = $object->update($user); if ($result < 0) { $error++; @@ -345,83 +350,72 @@ if (empty($reshook)) } else { $db->commit(); } - } - - // Set incoterm - elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) - { + } elseif ($action == 'set_incoterms' && !empty($conf->incoterm->enabled)) { + // Set incoterm $result = $object->setIncoterms(GETPOST('incoterm_id', 'int'), GETPOST('location_incoterms', 'alpha')); - } - - // payment mode - elseif ($action == 'setmode' && $usercancreate) - { + } elseif ($action == 'setmode' && $usercancreate) { + // payment mode $result = $object->setPaymentMethods(GETPOST('mode_reglement_id', 'int')); - } - - // Multicurrency Code - elseif ($action == 'setmulticurrencycode' && $usercancreate) { + } elseif ($action == 'setmulticurrencycode' && $usercancreate) { + // Multicurrency Code $result = $object->setMulticurrencyCode(GETPOST('multicurrency_code', 'alpha')); - } - - // Multicurrency rate - elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + } elseif ($action == 'setmulticurrencyrate' && $usercancreate) { + // Multicurrency rate $result = $object->setMulticurrencyRate(price2num(GETPOST('multicurrency_tx', 'alpha'))); - } - - // bank account - elseif ($action == 'setbankaccount' && $usercancreate) { + } elseif ($action == 'setbankaccount' && $usercancreate) { + // bank account $result = $object->setBankAccount(GETPOST('fk_account', 'int')); } - // transport mode - if ($action == 'settransportmode' && $user->rights->fournisseur->facture->creer) - { - $result = $object->setTransportMode(GETPOST('transport_mode_id', 'int')); - } - // Set label - elseif ($action == 'setlabel' && $usercancreate) - { + if ($action == 'settransportmode' && $user->rights->fournisseur->facture->creer) { + // transport mode + $result = $object->setTransportMode(GETPOST('transport_mode_id', 'int')); + } elseif ($action == 'setlabel' && $usercancreate) { + // Set label $object->fetch($id); $object->label = GETPOST('label'); $result = $object->update($user); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } } elseif ($action == 'setdatef' && $usercancreate) { $newdate = dol_mktime(0, 0, 0, $_POST['datefmonth'], $_POST['datefday'], $_POST['datefyear']); - if ($newdate > (dol_now() + (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE) ? 0 : $conf->global->INVOICE_MAX_OFFSET_IN_FUTURE))) - { - if (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)) setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings'); - else setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings'); + if ($newdate > (dol_now() + (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE) ? 0 : $conf->global->INVOICE_MAX_OFFSET_IN_FUTURE))) { + if (empty($conf->global->INVOICE_MAX_OFFSET_IN_FUTURE)) { + setEventMessages($langs->trans("WarningInvoiceDateInFuture"), null, 'warnings'); + } else { + setEventMessages($langs->trans("WarningInvoiceDateTooFarInFuture"), null, 'warnings'); + } } $object->fetch($id); $object->date = $newdate; $date_echence_calc = $object->calculate_date_lim_reglement(); - if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) - { + if (!empty($object->date_echeance) && $object->date_echeance < $date_echence_calc) { $object->date_echeance = $date_echence_calc; } - if ($object->date_echeance && $object->date_echeance < $object->date) - { + if ($object->date_echeance && $object->date_echeance < $object->date) { $object->date_echeance = $object->date; } $result = $object->update($user); - if ($result < 0) dol_print_error($db, $object->error); + if ($result < 0) { + dol_print_error($db, $object->error); + } } elseif ($action == 'setdate_lim_reglement' && $usercancreate) { $object->fetch($id); $object->date_echeance = dol_mktime(12, 0, 0, $_POST['date_lim_reglementmonth'], $_POST['date_lim_reglementday'], $_POST['date_lim_reglementyear']); - if (!empty($object->date_echeance) && $object->date_echeance < $object->date) - { + if (!empty($object->date_echeance) && $object->date_echeance < $object->date) { $object->date_echeance = $object->date; setEventMessages($langs->trans("DatePaymentTermCantBeLowerThanObjectDate"), null, 'warnings'); } $result = $object->update($user); - if ($result < 0) dol_print_error($db, $object->error); - } elseif ($action == "setabsolutediscount" && $usercancreate) - { + if ($result < 0) { + dol_print_error($db, $object->error); + } + } elseif ($action == "setabsolutediscount" && $usercancreate) { // POST[remise_id] or POST[remise_id_for_payment] // We use the credit to reduce amount of invoice @@ -437,23 +431,20 @@ if (empty($reshook)) } } // We use the credit to reduce remain to pay - if (!empty($_POST["remise_id_for_payment"])) - { + if (!empty($_POST["remise_id_for_payment"])) { require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php'; $discount = new DiscountAbsolute($db); $discount->fetch($_POST["remise_id_for_payment"]); //var_dump($object->getRemainToPay(0)); //var_dump($discount->amount_ttc);exit; - if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) - { + if (price2num($discount->amount_ttc) > price2num($object->getRemainToPay(0))) { // TODO Split the discount in 2 automatically $error++; setEventMessages($langs->trans("ErrorDiscountLargerThanRemainToPaySplitItBefore"), null, 'errors'); } - if (!$error) - { + if (!$error) { $result = $discount->link_to_invoice(0, $id); if ($result < 0) { setEventMessages($discount->error, $discount->errors, 'errors'); @@ -461,12 +452,15 @@ if (empty($reshook)) } } - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -474,12 +468,12 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) setEventMessages($object->error, $object->errors, 'errors'); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } - } - // Convertir en reduc - elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_converttoreduc' && $confirm == 'yes' && $usercancreate) { + // Convertir en reduc $object->fetch($id); $object->fetch_thirdparty(); //$object->fetch_lines(); // Already done into fetch @@ -489,10 +483,13 @@ if (empty($reshook)) $result = $discountcheck->fetch(0, 0, $object->id); $canconvert = 0; - if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) - if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) $canconvert = 1; // we can convert credit note into discount if credit note is not refunded completely and not already converted and amount of payment is 0 (see also the real condition used as the condition to show button converttoreduc) - if ($canconvert) - { + if ($object->type == FactureFournisseur::TYPE_DEPOSIT && empty($discountcheck->id)) { + $canconvert = 1; // we can convert deposit into discount if deposit is paid (completely, partially or not at all) and not already converted (see real condition into condition used to show button converttoreduc) + } + if (($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_STANDARD) && $object->paye == 0 && empty($discountcheck->id)) { + $canconvert = 1; // we can convert credit note into discount if credit note is not refunded completely and not already converted and amount of payment is 0 (see also the real condition used as the condition to show button converttoreduc) + } + if ($canconvert) { $db->begin(); $amount_ht = $amount_tva = $amount_ttc = array(); @@ -500,10 +497,9 @@ if (empty($reshook)) // Loop on each vat rate $i = 0; - foreach ($object->lines as $line) - { - if ($line->product_type < 9 && $line->total_ht != 0) // Remove lines with product_type greater than or equal to 9 - { // no need to create discount if amount is null + foreach ($object->lines as $line) { + if ($line->product_type < 9 && $line->total_ht != 0) { // Remove lines with product_type greater than or equal to 9 + // no need to create discount if amount is null $amount_ht[$line->tva_tx] += $line->total_ht; $amount_tva[$line->tva_tx] += $line->total_tva; $amount_ttc[$line->tva_tx] += $line->total_ttc; @@ -527,13 +523,13 @@ if (empty($reshook)) // Insert one discount by VAT rate category $discount = new DiscountAbsolute($db); - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $discount->description = '(CREDIT_NOTE)'; - elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) + } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) { $discount->description = '(DEPOSIT)'; - elseif ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) + } elseif ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) { $discount->description = '(EXCESS PAID)'; - else { + } else { setEventMessages($langs->trans('CantConvertToReducAnInvoiceOfThisType'), null, 'errors'); } $discount->discount_type = 1; // Supplier discount @@ -542,8 +538,7 @@ if (empty($reshook)) $error = 0; - if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) - { + if ($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || $object->type == FactureFournisseur::TYPE_SITUATION) { // If we're on a standard invoice, we have to get excess paid to create a discount in TTC without VAT // Total payments @@ -555,7 +550,9 @@ if (empty($reshook)) $sql .= ' AND p.entity IN ('.getEntity('invoice').')'; $resql = $db->query($sql); - if (!$resql) dol_print_error($db); + if (!$resql) { + dol_print_error($db); + } $res = $db->fetch_object($resql); $total_paiements = $res->total_paiements; @@ -571,43 +568,39 @@ if (empty($reshook)) while ($obj = $db->fetch_object($resql)) { $total_creditnote_and_deposit += $obj->amount_ttc; } - } else dol_print_error($db); + } else { + dol_print_error($db); + } $discount->amount_ht = $discount->amount_ttc = $total_paiements + $total_creditnote_and_deposit - $object->total_ttc; $discount->amount_tva = 0; $discount->tva_tx = 0; $result = $discount->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; } } - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) - { - foreach ($amount_ht as $tva_tx => $xxx) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT) { + foreach ($amount_ht as $tva_tx => $xxx) { $discount->amount_ht = abs($amount_ht[$tva_tx]); $discount->amount_tva = abs($amount_tva[$tva_tx]); $discount->amount_ttc = abs($amount_ttc[$tva_tx]); $discount->tva_tx = abs($tva_tx); $result = $discount->create($user); - if ($result < 0) - { + if ($result < 0) { $error++; break; } } } - if (empty($error)) - { + if (empty($error)) { if ($object->type != FactureFournisseur::TYPE_DEPOSIT) { // Classe facture $result = $object->setPaid($user); - if ($result >= 0) - { + if ($result >= 0) { $db->commit(); } else { setEventMessages($object->error, $object->errors, 'errors'); @@ -621,15 +614,10 @@ if (empty($reshook)) $db->rollback(); } } - } - - - // Delete payment - elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) - { - $object->fetch($id); - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) - { + } elseif ($action == 'confirm_delete_paiement' && $confirm == 'yes' && $usercancreate) { + // Delete payment + $object->fetch($id); + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0) { $paiementfourn = new PaiementFourn($db); $result = $paiementfourn->fetch(GETPOST('paiement_id')); if ($result > 0) { @@ -640,12 +628,11 @@ if (empty($reshook)) setEventMessages($paiementfourn->error, $paiementfourn->errors, 'errors'); } } - } - - // Create - elseif ($action == 'add' && $usercancreate) - { - if ($socid > 0) $object->socid = GETPOST('socid', 'int'); + } elseif ($action == 'add' && $usercancreate) { + // Create + if ($socid > 0) { + $object->socid = GETPOST('socid', 'int'); + } $db->begin(); @@ -653,14 +640,15 @@ if (empty($reshook)) // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } $dateinvoice = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); $datedue = dol_mktime(12, 0, 0, GETPOST('echmonth', 'int'), GETPOST('echday', 'int'), GETPOST('echyear', 'int')); // Replacement invoice - if (GETPOST('type') == FactureFournisseur::TYPE_REPLACEMENT) - { + if (GETPOST('type') == FactureFournisseur::TYPE_REPLACEMENT) { if (empty($dateinvoice)) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('DateInvoice')), null, 'errors'); $action = 'create'; @@ -713,16 +701,13 @@ if (empty($reshook)) } // Credit note invoice - if (GETPOST('type') == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if (GETPOST('type') == FactureFournisseur::TYPE_CREDIT_NOTE) { $sourceinvoice = GETPOST('fac_avoir', 'int'); - if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) - { + if (!($sourceinvoice > 0) && empty($conf->global->INVOICE_CREDIT_NOTE_STANDALONE)) { $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("CorrectInvoice")), null, 'errors'); } - if (GETPOST('socid', 'int') < 1) - { + if (GETPOST('socid', 'int') < 1) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors'); $action = 'create'; $error++; @@ -739,16 +724,14 @@ if (empty($reshook)) $action = 'create'; } - if (!GETPOST('ref_supplier')) - { + if (!GETPOST('ref_supplier')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors'); $action = 'create'; $_GET['socid'] = $_POST['socid']; $error++; } - if (!$error) - { + if (!$error) { $tmpproject = GETPOST('projectid', 'int'); // Creation facture @@ -781,15 +764,12 @@ if (empty($reshook)) $error++; } - if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) - { + if (GETPOST('invoiceAvoirWithLines', 'int') == 1 && $id > 0) { $facture_source = new FactureFournisseur($db); // fetch origin object - if ($facture_source->fetch($object->fk_facture_source) > 0) - { + if ($facture_source->fetch($object->fk_facture_source) > 0) { $fk_parent_line = 0; - foreach ($facture_source->lines as $line) - { + foreach ($facture_source->lines as $line) { // Reset fk_parent_line for no child products and special product if (($line->product_type != 9 && empty($line->fk_parent_line)) || $line->product_type == 9) { $fk_parent_line = 0; @@ -820,11 +800,9 @@ if (empty($reshook)) } } - if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) - { + if (GETPOST('invoiceAvoirWithPaymentRestAmount', 'int') == 1 && $id > 0) { $facture_source = new FactureFournisseur($db); // fetch origin object if not previously defined - if ($facture_source->fetch($object->fk_facture_source) > 0) - { + if ($facture_source->fetch($object->fk_facture_source) > 0) { $totalpaye = $facture_source->getSommePaiement(); $totalcreditnotes = $facture_source->getSumCreditNotesUsed(); $totaldeposits = $facture_source->getSumDepositsUsed(); @@ -837,10 +815,8 @@ if (empty($reshook)) } // Standard or deposit - if (GETPOST('type') == FactureFournisseur::TYPE_STANDARD || GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT) - { - if (GETPOST('socid', 'int') < 1) - { + if (GETPOST('type') == FactureFournisseur::TYPE_STANDARD || GETPOST('type') == FactureFournisseur::TYPE_DEPOSIT) { + if (GETPOST('socid', 'int') < 1) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Supplier')), null, 'errors'); $action = 'create'; $error++; @@ -857,16 +833,14 @@ if (empty($reshook)) $action = 'create'; } - if (!GETPOST('ref_supplier')) - { + if (!GETPOST('ref_supplier')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('RefSupplier')), null, 'errors'); $action = 'create'; $_GET['socid'] = $_POST['socid']; $error++; } - if (!$error) - { + if (!$error) { $tmpproject = GETPOST('projectid', 'int'); // Creation invoice @@ -890,13 +864,14 @@ if (empty($reshook)) $object->transport_mode_id = GETPOST('transport_mode_id'); // Auto calculation of date due if not filled by user - if (empty($object->date_echeance)) $object->date_echeance = $object->calculate_date_lim_reglement(); + if (empty($object->date_echeance)) { + $object->date_echeance = $object->calculate_date_lim_reglement(); + } $object->fetch_thirdparty(); // If creation from another object of another module - if (!$error && GETPOST('origin', 'alpha') && GETPOST('originid')) - { + if (!$error && GETPOST('origin', 'alpha') && GETPOST('originid')) { // Parse element/subelement (ex: project_task) $element = $subelement = GETPOST('origin', 'alpha'); /*if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs)) @@ -918,8 +893,7 @@ if (empty($reshook)) if ($element == 'order_supplier') { $element = 'fourn'; $subelement = 'fournisseur.commande'; } - if ($element == 'project') - { + if ($element == 'project') { $element = 'projet'; } $object->origin = GETPOST('origin', 'alpha'); @@ -928,25 +902,23 @@ if (empty($reshook)) require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; $classname = ucfirst($subelement); - if ($classname == 'Fournisseur.commande') $classname = 'CommandeFournisseur'; + if ($classname == 'Fournisseur.commande') { + $classname = 'CommandeFournisseur'; + } $objectsrc = new $classname($db); $objectsrc->fetch($originid); $objectsrc->fetch_thirdparty(); - if (!empty($object->origin) && !empty($object->origin_id)) - { + if (!empty($object->origin) && !empty($object->origin_id)) { $object->linkedObjectsIds[$object->origin] = $object->origin_id; } // Add also link with order if object is reception - if ($object->origin == 'reception') - { + if ($object->origin == 'reception') { $objectsrc->fetchObjectLinked(); - if (count($objectsrc->linkedObjectsIds['order_supplier']) > 0) - { - foreach ($objectsrc->linkedObjectsIds['order_supplier'] as $key => $value) - { + if (count($objectsrc->linkedObjectsIds['order_supplier']) > 0) { + foreach ($objectsrc->linkedObjectsIds['order_supplier'] as $key => $value) { $object->linkedObjectsIds['order_supplier'] = $value; } } @@ -955,26 +927,24 @@ if (empty($reshook)) $id = $object->create($user); // Add lines - if ($id > 0) - { + if ($id > 0) { require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; $classname = ucfirst($subelement); - if ($classname == 'Fournisseur.commande') $classname = 'CommandeFournisseur'; + if ($classname == 'Fournisseur.commande') { + $classname = 'CommandeFournisseur'; + } $srcobject = new $classname($db); $result = $srcobject->fetch(GETPOST('originid', 'int')); - if ($result > 0) - { + if ($result > 0) { $lines = $srcobject->lines; - if (empty($lines) && method_exists($srcobject, 'fetch_lines')) - { + if (empty($lines) && method_exists($srcobject, 'fetch_lines')) { $srcobject->fetch_lines(); $lines = $srcobject->lines; } $num = count($lines); - for ($i = 0; $i < $num; $i++) // TODO handle subprice < 0 - { + for ($i = 0; $i < $num; $i++) { // TODO handle subprice < 0 $desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle); $product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0); @@ -986,18 +956,25 @@ if (empty($reshook)) // Dates // TODO mutualiser $date_start = $lines[$i]->date_debut_prevue; - if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel; - if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start; + if ($lines[$i]->date_debut_reel) { + $date_start = $lines[$i]->date_debut_reel; + } + if ($lines[$i]->date_start) { + $date_start = $lines[$i]->date_start; + } $date_end = $lines[$i]->date_fin_prevue; - if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel; - if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end; + if ($lines[$i]->date_fin_reel) { + $date_end = $lines[$i]->date_fin_reel; + } + if ($lines[$i]->date_end) { + $date_end = $lines[$i]->date_end; + } // FIXME Missing special_code into addline and updateline methods $object->special_code = $lines[$i]->special_code; // FIXME If currency different from main currency, take multicurrency price - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { $pu = 0; $pu_currency = $lines[$i]->multicurrency_subprice; } else { @@ -1031,8 +1008,7 @@ if (empty($reshook)) $lines[$i]->special_code ); - if ($result < 0) - { + if ($result < 0) { $error++; break; } @@ -1046,19 +1022,16 @@ if (empty($reshook)) } else { $error++; } - } elseif (!$error) - { + } elseif (!$error) { $id = $object->create($user); - if ($id < 0) - { + if ($id < 0) { $error++; } } } } - if ($error) - { + if ($error) { $langs->load("errors"); $db->rollback(); @@ -1071,8 +1044,7 @@ if (empty($reshook)) if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) { $outputlangs = $langs; $result = $object->generateDocument($object->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) - { + if ($result < 0) { dol_print_error($db, $object->error, $object->errors); exit; } @@ -1081,11 +1053,8 @@ if (empty($reshook)) header("Location: ".$_SERVER['PHP_SELF']."?id=".$id); exit; } - } - - // Edit line - elseif ($action == 'updateline' && $usercancreate) - { + } elseif ($action == 'updateline' && $usercancreate) { + // Edit line $db->begin(); $object->fetch($id); @@ -1093,8 +1062,7 @@ if (empty($reshook)) $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); - if (GETPOST('price_ht') != '' || GETPOST('multicurrency_subprice') != '') - { + if (GETPOST('price_ht') != '' || GETPOST('multicurrency_subprice') != '') { $up = price2num(GETPOST('price_ht')); $price_base_type = 'HT'; } else { @@ -1102,13 +1070,10 @@ if (empty($reshook)) $price_base_type = 'TTC'; } - if (GETPOST('productid') > 0) - { + if (GETPOST('productid') > 0) { $productsupplier = new ProductFournisseur($db); - if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) - { - if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty')), GETPOST('productid', 'int'), 'restricthtml', GETPOST('socid', 'int')) < 0) - { + if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) { + if (GETPOST('productid') > 0 && $productsupplier->get_buyprice(0, price2num(GETPOST('qty')), GETPOST('productid', 'int'), 'restricthtml', GETPOST('socid', 'int')) < 0) { setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'warnings'); } } @@ -1116,7 +1081,9 @@ if (empty($reshook)) $prod = new Product($db); $prod->fetch(GETPOST('productid')); $label = $prod->description; - if (trim($_POST['product_desc']) != trim($label)) $label = $_POST['product_desc']; + if (trim($_POST['product_desc']) != trim($label)) { + $label = $_POST['product_desc']; + } $type = $prod->type; } else { @@ -1129,8 +1096,9 @@ if (empty($reshook)) // Define info_bits $info_bits = 0; - if (preg_match('/\*/', $tva_tx)) + if (preg_match('/\*/', $tva_tx)) { $info_bits |= 0x01; + } // Define vat_rate $tva_tx = str_replace('*', '', $tva_tx); @@ -1151,8 +1119,7 @@ if (empty($reshook)) } $result = $object->updateline(GETPOST('lineid', 'int'), $label, $up, $tva_tx, $localtax1_tx, $localtax2_tx, price2num(GETPOST('qty'), 'MS'), GETPOST('productid', 'int'), $price_base_type, $info_bits, $type, $remise_percent, 0, $date_start, $date_end, $array_options, GETPOST('units'), $pu_ht_devise, GETPOST('fourn_ref', 'alpha')); - if ($result >= 0) - { + if ($result >= 0) { unset($_POST['label']); unset($_POST['fourn_ref']); unset($_POST['date_starthour']); @@ -1177,8 +1144,7 @@ if (empty($reshook)) $db->begin(); $ret = $object->fetch($id); - if ($ret < 0) - { + if ($ret < 0) { dol_print_error($db, $object->error); exit; } @@ -1194,8 +1160,7 @@ if (empty($reshook)) $date_end = dol_mktime(GETPOST('date_end'.$predef.'hour'), GETPOST('date_end'.$predef.'min'), GETPOST('date_end'.$predef.'sec'), GETPOST('date_end'.$predef.'month'), GETPOST('date_end'.$predef.'day'), GETPOST('date_end'.$predef.'year')); $prod_entry_mode = GETPOST('prod_entry_mode'); - if ($prod_entry_mode == 'free') - { + if ($prod_entry_mode == 'free') { $idprod = 0; $price_ht = price2num(GETPOST('price_ht'), 'MU'); $tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0); @@ -1220,28 +1185,23 @@ if (empty($reshook)) } } - if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) - { + if ($prod_entry_mode == 'free' && GETPOST('price_ht') < 0 && $qty < 0) { setEventMessages($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) - { + if ($prod_entry_mode == 'free' && !GETPOST('idprodfournprice') && GETPOST('type') < 0) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') // Unit price can be 0 but not '' - { + if ($prod_entry_mode == 'free' && GETPOST('price_ht') === '' && GETPOST('price_ttc') === '' && $price_ht_devise === '') { // Unit price can be 0 but not '' setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice')), null, 'errors'); $error++; } - if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) - { + if ($prod_entry_mode == 'free' && !GETPOST('dp_desc')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), null, 'errors'); $error++; } - if (!GETPOST('qty')) - { + if (!GETPOST('qty')) { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), null, 'errors'); $error++; } @@ -1260,55 +1220,57 @@ if (empty($reshook)) } } - if ($prod_entry_mode != 'free' && empty($error)) // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' - { + if ($prod_entry_mode != 'free' && empty($error)) { // With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or '' $productsupplier = new ProductFournisseur($db); $idprod = 0; - if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + if (GETPOST('idprodfournprice', 'alpha') == -1 || GETPOST('idprodfournprice', 'alpha') == '') { + $idprod = -99; // Same behaviour than with combolist. When not select idprodfournprice is now -99 (to avoid conflict with next action that may return -1, -2, ...) + } $reg = array(); - if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) - { + if (preg_match('/^idprod_([0-9]+)$/', GETPOST('idprodfournprice', 'alpha'), $reg)) { $idprod = $reg[1]; $res = $productsupplier->fetch($idprod); // Load product from its id // Call to init some price properties of $productsupplier // So if a supplier price already exists for another thirdparty (first one found), we use it as reference price - if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) - { + if (!empty($conf->global->SUPPLIER_TAKE_FIRST_PRICE_IF_NO_PRICE_FOR_CURRENT_SUPPLIER)) { $fksoctosearch = 0; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist - if ($productsupplier->fourn_socid != $socid) // The price we found is for another supplier, so we clear supplier price - { + if ($productsupplier->fourn_socid != $socid) { // The price we found is for another supplier, so we clear supplier price $productsupplier->ref_supplier = ''; } } else { $fksoctosearch = $object->thirdparty->id; $productsupplier->get_buyprice(0, -1, $idprod, 'none', $fksoctosearch); // We force qty to -1 to be sure to find if a supplier price exist } - } elseif (GETPOST('idprodfournprice', 'alpha') > 0) - { + } elseif (GETPOST('idprodfournprice', 'alpha') > 0) { $qtytosearch = $qty; // Just to see if a price exists for the quantity. Not used to found vat. //$qtytosearch=-1; // We force qty to -1 to be sure to find if a supplier price exist $idprod = $productsupplier->get_buyprice(GETPOST('idprodfournprice', 'alpha'), $qtytosearch); $res = $productsupplier->fetch($idprod); } - if ($idprod > 0) - { + if ($idprod > 0) { $label = $productsupplier->label; // if we use supplier description of the products if (!empty($productsupplier->desc_supplier) && !empty($conf->global->PRODUIT_FOURN_TEXTS)) { $desc = $productsupplier->desc_supplier; - } else $desc = $productsupplier->description; + } else { + $desc = $productsupplier->description; + } //If text set in desc is the same as product descpription (as now it's preloaded) whe add it only one time if ($product_desc==$desc && !empty($conf->global->PRODUIT_AUTOFILL_DESC)) { $product_desc=''; } - if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) $desc = $product_desc; - if (!empty($product_desc) && trim($product_desc) != trim($desc)) $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + if (!empty($product_desc) && !empty($conf->global->MAIN_NO_CONCAT_DESCRIPTION)) { + $desc = $product_desc; + } + if (!empty($product_desc) && trim($product_desc) != trim($desc)) { + $desc = dol_concatdesc($desc, $product_desc, '', !empty($conf->global->MAIN_CHANGE_ORDER_CONCAT_DESCRIPTION)); + } $type = $productsupplier->type; if (GETPOST('price_ht') != '' || GETPOST('price_ht_devise') != '') { @@ -1330,11 +1292,15 @@ if (empty($reshook)) $tva_tx = get_default_tva($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); $tva_npr = get_default_npr($object->thirdparty, $mysoc, $productsupplier->id, GETPOST('idprodfournprice', 'alpha')); - if (empty($tva_tx)) $tva_npr = 0; + if (empty($tva_tx)) { + $tva_npr = 0; + } $localtax1_tx = get_localtax($tva_tx, 1, $mysoc, $object->thirdparty, $tva_npr); $localtax2_tx = get_localtax($tva_tx, 2, $mysoc, $object->thirdparty, $tva_npr); - if (empty($pu)) $pu = 0; // If pu is '' or null, we force to have a numeric value + if (empty($pu)) { + $pu = 0; // If pu is '' or null, we force to have a numeric value + } $result = $object->addline( $desc, @@ -1361,22 +1327,19 @@ if (empty($reshook)) '' ); } - if ($idprod == -99 || $idprod == 0) - { + if ($idprod == -99 || $idprod == 0) { // Product not selected $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductOrService")), null, 'errors'); } - if ($idprod == -1) - { + if ($idprod == -1) { // Quantity too low $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorQtyTooLowForThisSupplier"), null, 'errors'); } - } elseif (empty($error)) // $price_ht is already set - { + } elseif (empty($error)) { // $price_ht is already set $tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0); $tva_tx = str_replace('*', '', $tva_tx); $label = (GETPOST('product_label') ? GETPOST('product_label') : ''); @@ -1407,17 +1370,19 @@ if (empty($reshook)) } //print "xx".$tva_tx; exit; - if (!$error && $result > 0) - { + if (!$error && $result > 0) { $db->commit(); // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -1426,7 +1391,9 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } unset($_POST ['prod_entry_mode']); @@ -1470,12 +1437,8 @@ if (empty($reshook)) } elseif ($action == 'classin' && $usercancreate) { $object->fetch($id); $result = $object->setProject($projectid); - } - - - // Set invoice to draft status - elseif ($action == 'confirm_edit' && $confirm == 'yes' && $usercancreate) - { + } elseif ($action == 'confirm_edit' && $confirm == 'yes' && $usercancreate) { + // Set invoice to draft status $object->fetch($id); $totalpaye = $object->getSommePaiement(); @@ -1484,29 +1447,24 @@ if (empty($reshook)) // We check that lines of invoices are exported in accountancy $ventilExportCompta = $object->getVentilExportCompta(); - if (!$ventilExportCompta) - { + if (!$ventilExportCompta) { // On verifie si aucun paiement n'a ete effectue - if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) - { + if ($resteapayer == price2num($object->total_ttc, 'MT', 1) && $object->statut == FactureFournisseur::STATUS_VALIDATED) { $idwarehouse = GETPOST('idwarehouse'); $object->fetch_thirdparty(); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + 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) - { + if (!empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $qualified_for_stock_change) { $langs->load("stocks"); - if (!$idwarehouse || $idwarehouse == -1) - { + if (!$idwarehouse || $idwarehouse == -1) { $error++; setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("Warehouse")), null, 'errors'); $action = ''; @@ -1516,12 +1474,15 @@ if (empty($reshook)) $object->setDraft($user, $idwarehouse); // Define output language - if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) - { + 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 ($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); @@ -1530,24 +1491,21 @@ if (empty($reshook)) $ret = $object->fetch($id); // Reload to get new records $result = $object->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref); - if ($result < 0) dol_print_error($db, $result); + if ($result < 0) { + dol_print_error($db, $result); + } } $action = ''; } } - } - - // Set invoice to validated/unpaid status - elseif ($action == 'reopen' && $usercancreate) - { + } elseif ($action == 'reopen' && $usercancreate) { + // Set invoice to validated/unpaid status $result = $object->fetch($id); if ($object->statut == FactureFournisseur::STATUS_CLOSED - || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) - { + || ($object->statut == FactureFournisseur::STATUS_ABANDONED && $object->close_code != 'replaced')) { $result = $object->setUnpaid($user); - if ($result > 0) - { + if ($result > 0) { header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id); exit; } else { @@ -1572,91 +1530,75 @@ if (empty($reshook)) include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; // Make calculation according to calculationrule - if ($action == 'calculate') - { + if ($action == 'calculate') { $calculationrule = GETPOST('calculationrule'); $object->fetch($id); $object->fetch_thirdparty(); $result = $object->update_price(0, (($calculationrule == 'totalofround') ? '0' : '1'), 0, $object->thirdparty); - if ($result <= 0) - { + if ($result <= 0) { dol_print_error($db, $result); exit; } } - if ($action == 'update_extras') - { + if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object, GETPOST('attribute', 'restricthtml')); - if ($ret < 0) $error++; + if ($ret < 0) { + $error++; + } - if (!$error) - { + if (!$error) { // Actions on extra fields - if (!$error) - { + if (!$error) { $result = $object->insertExtraFields('BILL_SUPPLIER_MODIFY'); - if ($result < 0) - { + if ($result < 0) { $error++; } } } - if ($error) + if ($error) { $action = 'edit_extras'; + } } - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) - { - if ($action == 'addcontact') - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $usercancreate) { + if ($action == 'addcontact') { $result = $object->fetch($id); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } - } - - // bascule du statut d'un contact - elseif ($action == 'swapstatut') - { - if ($object->fetch($id)) - { + } elseif ($action == 'swapstatut') { + // bascule du statut d'un contact + if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } - } - - // Efface un contact - elseif ($action == 'deletecontact') - { + } elseif ($action == 'deletecontact') { + // Efface un contact $object->fetch($id); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -1675,7 +1617,9 @@ $form = new Form($db); $formfile = new FormFile($db); $bankaccountstatic = new Account($db); $paymentstatic = new PaiementFourn($db); -if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); } +if (!empty($conf->projet->enabled)) { + $formproject = new FormProjets($db); +} $now = dol_now(); @@ -1684,8 +1628,7 @@ $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Mód llxHeader('', $title, $helpurl); // Mode creation -if ($action == 'create') -{ +if ($action == 'create') { $facturestatic = new FactureFournisseur($db); print load_fiche_titre($langs->trans('NewBill'), '', 'supplier_invoice'); @@ -1698,7 +1641,9 @@ if ($action == 'create') if (GETPOST('socid') > 0) { $societe = new Societe($db); $societe->fetch(GETPOST('socid', 'int')); - if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) $currency_code = $societe->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($societe->multicurrency_code)) { + $currency_code = $societe->multicurrency_code; + } } if (!empty($origin) && !empty($originid)) { @@ -1726,7 +1671,9 @@ if ($action == 'create') require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php'; $classname = ucfirst($subelement); - if ($classname == 'Fournisseur.commande') $classname = 'CommandeFournisseur'; + if ($classname == 'Fournisseur.commande') { + $classname = 'CommandeFournisseur'; + } $objectsrc = new $classname($db); $objectsrc->fetch($originid); $objectsrc->fetch_thirdparty(); @@ -1743,10 +1690,13 @@ if ($action == 'create') $dateinvoice = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : ''; $transport_mode_id = (!empty($objectsrc->transport_mode_id) ? $objectsrc->transport_mode_id : (!empty($soc->transport_mode_id) ? $soc->transport_mode_id : 0)); - if (!empty($conf->multicurrency->enabled)) - { - if (!empty($objectsrc->multicurrency_code)) $currency_code = $objectsrc->multicurrency_code; - if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) $currency_tx = $objectsrc->multicurrency_tx; + if (!empty($conf->multicurrency->enabled)) { + if (!empty($objectsrc->multicurrency_code)) { + $currency_code = $objectsrc->multicurrency_code; + } + if (!empty($conf->global->MULTICURRENCY_USE_ORIGIN_TX) && !empty($objectsrc->multicurrency_tx)) { + $currency_tx = $objectsrc->multicurrency_tx; + } } $datetmp = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); @@ -1767,7 +1717,9 @@ if ($action == 'create') $datetmp = dol_mktime(12, 0, 0, $_POST['echmonth'], $_POST['echday'], $_POST['echyear']); $datedue = ($datetmp == '' ?-1 : $datetmp); - if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) $currency_code = $soc->multicurrency_code; + if (!empty($conf->multicurrency->enabled) && !empty($soc->multicurrency_code)) { + $currency_code = $soc->multicurrency_code; + } } // when payment condition is empty (means not override by payment condition form a other object, like third-party), try to use default value @@ -1786,10 +1738,14 @@ if ($action == 'create') print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - if ($societe->id > 0) print '<input type="hidden" name="socid" value="'.$societe->id.'">'."\n"; + if ($societe->id > 0) { + print '<input type="hidden" name="socid" value="'.$societe->id.'">'."\n"; + } print '<input type="hidden" name="origin" value="'.$origin.'">'; print '<input type="hidden" name="originid" value="'.$originid.'">'; - if (!empty($currency_tx)) print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">'; + if (!empty($currency_tx)) { + print '<input type="hidden" name="originmulticurrency_tx" value="'.$currency_tx.'">'; + } print dol_get_fiche_head(); @@ -1802,16 +1758,14 @@ if ($action == 'create') print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>'; print '<td>'; - if ($societe->id > 0) - { + if ($societe->id > 0) { $absolute_discount = $societe->getAvailableDiscounts('', '', 0, 1); print $societe->getNomUrl(1); print '<input type="hidden" name="socid" value="'.$societe->id.'">'; } else { print img_picto('', 'company').$form->select_company($societe->id, 'socid', 's.fournisseur=1', 'SelectThirdParty', 0, 0, null, 0, 'minwidth300'); // reload page to retrieve supplier informations - if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) - { + if (!empty($conf->global->RELOAD_PAGE_ON_SUPPLIER_CHANGE)) { print '<script type="text/javascript"> $(document).ready(function() { $("#socid").change(function() { @@ -1828,7 +1782,9 @@ if ($action == 'create') // Ref supplier print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="ref_supplier" value="'.(isset($_POST['ref_supplier']) ? $_POST['ref_supplier'] : $objectsrc->ref_supplier).'" type="text"'; - if ($societe->id > 0) print ' autofocus'; + if ($societe->id > 0) { + print ' autofocus'; + } print '></td>'; print '</tr>'; @@ -1876,7 +1832,7 @@ if ($action == 'create') print '</div></div>'; } } - */ + */ /* Not yet supported for supplier if ($societe->id > 0) @@ -1942,24 +1898,19 @@ if ($action == 'create') } */ - if (empty($origin)) - { - if ($societe->id > 0) - { + if (empty($origin)) { + if ($societe->id > 0) { // Credit note - if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) - { + if (empty($conf->global->INVOICE_DISABLE_CREDIT_NOTE)) { // Show link for credit note $facids = $facturestatic->list_qualified_avoir_supplier_invoices($societe->id); - if ($facids < 0) - { + if ($facids < 0) { dol_print_error($db, $facturestatic); exit; } $optionsav = ""; $newinvoice_static = new FactureFournisseur($db); - foreach ($facids as $key => $valarray) - { + foreach ($facids as $key => $valarray) { $newinvoice_static->id = $key; $newinvoice_static->ref = $valarray ['ref']; $newinvoice_static->statut = $valarray ['status']; @@ -1967,8 +1918,9 @@ if ($action == 'create') $newinvoice_static->paye = $valarray ['paye']; $optionsav .= '<option value="'.$key.'"'; - if ($key == GETPOST('fac_avoir', 'int')) + if ($key == GETPOST('fac_avoir', 'int')) { $optionsav .= ' selected'; + } $optionsav .= '>'; $optionsav .= $newinvoice_static->ref; $optionsav .= ' ('.$newinvoice_static->getLibStatut(1, $valarray ['paymentornot']).')'; @@ -1977,7 +1929,9 @@ if ($action == 'create') print '<div class="tagtr listofinvoicetype"><div class="tagtd listofinvoicetype">'; $tmp = '<input type="radio" id="radio_creditnote" name="type" value="2"'.(GETPOST('type') == 2 ? ' checked' : ''); - if (!$optionsav) $tmp .= ' disabled'; + if (!$optionsav) { + $tmp .= ' disabled'; + } $tmp .= '> '; // Show credit note options only if we checked credit note print '<script type="text/javascript" language="javascript"> @@ -1997,8 +1951,9 @@ if ($action == 'create') $text = $tmp.$langs->transnoentities("InvoiceAvoirAsk").' '; // $text.='<input type="text" value="">'; $text .= '<select class="flat valignmiddle" name="fac_avoir" id="fac_avoir"'; - if (!$optionsav) + if (!$optionsav) { $text .= ' disabled'; + } $text .= '>'; if ($optionsav) { $text .= '<option value="-1"></option>'; @@ -2034,8 +1989,7 @@ if ($action == 'create') print '</td></tr>'; - if ($societe->id > 0) - { + if ($societe->id > 0) { // Discounts for third party print '<tr><td>'.$langs->trans('Discounts').'</td><td>'; @@ -2071,16 +2025,14 @@ if ($action == 'create') print '</td></tr>'; // Bank Account - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print '<tr><td>'.$langs->trans('BankAccount').'</td><td>'; print img_picto('', 'bank_account').$form->select_comptes((GETPOSTISSET('fk_account') ?GETPOST('fk_account', 'alpha') : $fk_account), 'fk_account', 0, '', 1, '', 0, '', 1); print '</td></tr>'; } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $formproject = new FormProjets($db); $langs->load('projects'); @@ -2090,8 +2042,7 @@ if ($action == 'create') } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr>'; print '<td><label for="incoterm_id">'.$form->textwithpicto($langs->trans("IncotermLabel"), $objectsrc->label_incoterms, 1).'</label></td>'; print '<td colspan="3" class="maxwidthonsmartphone">'; @@ -2100,8 +2051,7 @@ if ($action == 'create') } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr>'; print '<td>'.$form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0).'</td>'; print '<td class="maxwidthonsmartphone">'; @@ -2110,8 +2060,7 @@ if ($action == 'create') } // Intracomm report - if (!empty($conf->intracommreport->enabled)) - { + if (!empty($conf->intracommreport->enabled)) { $langs->loadLangs(array("intracommreport")); print '<tr><td>'.$langs->trans('IntracommReportTransportMode').'</td><td>'; $form->selectTransportMode(isset($_POST['transport_mode_id']) ? $_POST['transport_mode_id'] : $transport_mode_id, 'transport_mode_id'); @@ -2136,13 +2085,11 @@ if ($action == 'create') // print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>'; print '</tr>'; - if (empty($reshook)) - { + if (empty($reshook)) { print $object->showOptionals($extrafields, 'edit'); } - if (is_object($objectsrc)) - { + if (is_object($objectsrc)) { print "\n<!-- ".$classname." info -->"; print "\n"; print '<input type="hidden" name="amount" value="'.$objectsrc->total_ht.'">'."\n"; @@ -2163,12 +2110,10 @@ if ($action == 'create') $invoice_supplier = $objectsrc->linkedObjects['invoice_supplier']; // count function need a array as argument (Note: the array must implement Countable too) - if (is_array($invoice_supplier)) - { + if (is_array($invoice_supplier)) { $cntinvoice = count($invoice_supplier); - if ($cntinvoice >= 1) - { + if ($cntinvoice >= 1) { setEventMessages('WarningBillExist', null, 'warnings'); echo ' ('.$langs->trans('LatestRelatedBill').end($invoice_supplier)->getNomUrl(1).')'; } @@ -2177,19 +2122,16 @@ if ($action == 'create') print '</td></tr>'; print '<tr><td>'.$langs->trans('AmountHT').'</td><td>'.price($objectsrc->total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($objectsrc->total_tva)."</td></tr>"; - if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) //Localtax1 - { + if ($mysoc->localtax1_assuj == "1" || $object->total_localtax1 != 0) { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax1)."</td></tr>"; } - if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) //Localtax2 - { + if ($mysoc->localtax2_assuj == "1" || $object->total_localtax2 != 0) { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td><td>'.price($objectsrc->total_localtax2)."</td></tr>"; } print '<tr><td>'.$langs->trans('AmountTTC').'</td><td>'.price($objectsrc->total_ttc)."</td></tr>"; - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<tr><td>'.$langs->trans('MulticurrencyAmountHT').'</td><td>'.price($objectsrc->multicurrency_total_ht).'</td></tr>'; print '<tr><td>'.$langs->trans('MulticurrencyAmountVAT').'</td><td>'.price($objectsrc->multicurrency_total_tva)."</td></tr>"; print '<tr><td>'.$langs->trans('MulticurrencyAmountTTC').'</td><td>'.price($objectsrc->multicurrency_total_ttc)."</td></tr>"; @@ -2240,11 +2182,15 @@ if ($action == 'create') $object->fetch($id, $ref); $result = $object->fetch_thirdparty(); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } $societe = new Fournisseur($db); $result = $societe->fetch($object->socid); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } $totalpaye = $object->getSommePaiement(); $totalcreditnotes = $object->getSumCreditNotesUsed(); @@ -2258,8 +2204,7 @@ if ($action == 'create') // $resteapayer=bcadd($resteapayer,$totalavoir,$conf->global->MAIN_MAX_DECIMALS_TOT); $resteapayer = price2num($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT'); - if ($object->paye) - { + if ($object->paye) { $resteapayer = 0; } $resteapayeraffiche = $resteapayer; @@ -2278,8 +2223,8 @@ if ($action == 'create') $absolute_creditnote = price2num($absolute_creditnote, 'MT'); /* - * View card - */ + * View card + */ $head = facturefourn_prepare_head($object); $titre = $langs->trans('SupplierInvoice'); @@ -2289,17 +2234,20 @@ if ($action == 'create') // Confirmation de la conversion de l'avoir en reduc if ($action == 'converttoreduc') { - if ($object->type == FactureFournisseur::TYPE_STANDARD) $type_fac = 'ExcessPaid'; - elseif ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $type_fac = 'CreditNote'; - elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) $type_fac = 'Deposit'; + if ($object->type == FactureFournisseur::TYPE_STANDARD) { + $type_fac = 'ExcessPaid'; + } elseif ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $type_fac = 'CreditNote'; + } elseif ($object->type == FactureFournisseur::TYPE_DEPOSIT) { + $type_fac = 'Deposit'; + } $text = $langs->trans('ConfirmConvertToReducSupplier', strtolower($langs->transnoentities($type_fac))); $text .= '<br>'.$langs->trans('ConfirmConvertToReducSupplier2'); $formconfirm = $form->formconfirm($_SERVER['PHP_SELF'].'?facid='.$object->id, $langs->trans('ConvertToReduc'), $text, 'confirm_converttoreduc', '', "yes", 2); } // Clone confirmation - if ($action == 'clone') - { + if ($action == 'clone') { // Create an array for form $formquestion = array( array('type' => 'text', 'name' => 'newsupplierref', 'label' => $langs->trans("RefSupplier"), 'value' => $langs->trans("CopyOf").' '.$object->ref_supplier), @@ -2310,8 +2258,7 @@ if ($action == 'create') } // Confirmation of validation - if ($action == 'valid') - { + if ($action == 'valid') { // We check if number is temporary number if (preg_match('/^[\(]?PROV/i', $object->ref) || empty($object->ref)) { // empty should not happened, but when it occurs, the test save life @@ -2341,8 +2288,7 @@ 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) - { + 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); @@ -2365,19 +2311,16 @@ if ($action == 'create') } // Confirmation edit (back to draft) - if ($action == 'edit') - { + if ($action == 'edit') { $formquestion = array(); $qualified_for_stock_change = 0; - if (empty($conf->global->STOCK_SUPPORTS_SERVICES)) - { + 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) - { + 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); @@ -2398,34 +2341,32 @@ if ($action == 'create') } // Confirmation set paid - if ($action == 'paid') - { + if ($action == 'paid') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1); } // Confirmation de la suppression de la facture fournisseur - if ($action == 'delete') - { + if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1); } - if ($action == 'deletepayment') - { + if ($action == 'deletepayment') { $payment_id = GETPOST('paiement_id'); $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&paiement_id='.$payment_id, $langs->trans('DeletePayment'), $langs->trans('ConfirmDeletePayment'), 'confirm_delete_paiement', '', 0, 1); } - // Confirmation to delete line - if ($action == 'ask_deleteline') - { + // Confirmation to delete line + if ($action == 'ask_deleteline') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 0, 1); } - if (!$formconfirm) - { + if (!$formconfirm) { $parameters = array('formConfirm' => $formconfirm, 'lineid'=>$lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } } // Print form confirm @@ -2441,14 +2382,14 @@ if ($action == 'create') $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, $usercancreate, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($usercancreate) - { + if ($usercancreate) { if ($action != 'classify') { $morehtmlref .= '<a class="editfielda" href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a> : '; } @@ -2492,36 +2433,34 @@ if ($action == 'create') print '<span class="badgeneutral">'; print $object->getLibType(); print '</span>'; - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { + 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) - { + 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) - { + if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i = 0; - foreach ($facidavoir as $id) - { - if ($i == 0) print ' '; - else print ','; + 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) - { + if (isset($facidnext) && $facidnext > 0) { $facthatreplace = new FactureFournisseur($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; @@ -2576,8 +2515,7 @@ if ($action == 'create') } print '</tr></table>'; print '</td><td colspan="2">'; - if ($action == 'editconditions') - { + if ($action == 'editconditions') { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'cond_reglement_id'); } else { $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->cond_reglement_id, 'none'); @@ -2604,8 +2542,7 @@ if ($action == 'create') } print '</tr></table>'; print '</td><td colspan="2">'; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'mode_reglement_id', 'DBIT', 1, 1); } else { $form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id, $object->mode_reglement_id, 'none'); @@ -2613,16 +2550,16 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Multicurrency code print '<tr>'; print '<td>'; print '<table class="nobordernopadding" width="100%"><tr><td>'; print $form->editfieldkey('Currency', 'multicurrency_code', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) + if ($action != 'editmulticurrencycode' && $object->statut == $object::STATUS_DRAFT) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencycode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="3">'; if ($action == 'editmulticurrencycode') { @@ -2633,15 +2570,15 @@ if ($action == 'create') print '</td></tr>'; // Multicurrency rate - if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) - { + if ($object->multicurrency_code != $conf->currency || $object->multicurrency_tx != 1) { print '<tr>'; print '<td>'; print '<table class="nobordernopadding" width="100%"><tr><td>'; print $form->editfieldkey('CurrencyRate', 'multicurrency_tx', '', $object, 0); print '</td>'; - if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) + if ($action != 'editmulticurrencyrate' && $object->statut == $object::STATUS_DRAFT && $object->multicurrency_code && $object->multicurrency_code != $conf->currency) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editmulticurrencyrate&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMultiCurrencyCode'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="3">'; if ($action == 'editmulticurrencyrate' || $action == 'actualizemulticurrencyrate') { @@ -2662,14 +2599,14 @@ if ($action == 'create') } // Bank Account - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print '<tr><td class="nowrap">'; print '<table width="100%" class="nobordernopadding"><tr><td class="nowrap">'; print $langs->trans('BankAccount'); print '<td>'; - if ($action != 'editbankaccount' && $usercancreate) + if ($action != 'editbankaccount' && $usercancreate) { print '<td class="right"><a class="editfielda" href="'.$_SERVER["PHP_SELF"].'?action=editbankaccount&amp;id='.$object->id.'">'.img_edit($langs->trans('SetBankAccount'), 1).'</a></td>'; + } print '</tr></table>'; print '</td><td colspan="3">'; if ($action == 'editbankaccount') { @@ -2682,19 +2619,20 @@ if ($action == 'create') } // Incoterms - if (!empty($conf->incoterm->enabled)) - { + if (!empty($conf->incoterm->enabled)) { print '<tr><td>'; print '<table width="100%" class="nobordernopadding"><tr><td>'; print $langs->trans('IncotermLabel'); print '<td><td class="right">'; - if ($usercancreate) print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; - else print '&nbsp;'; + if ($usercancreate) { + print '<a class="editfielda" href="'.DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$object->id.'&action=editincoterm">'.img_edit().'</a>'; + } else { + print '&nbsp;'; + } print '</td></tr></table>'; print '</td>'; print '<td colspan="3">'; - if ($action != 'editincoterm') - { + if ($action != 'editincoterm') { print $form->textwithpicto($object->display_incoterms(), $object->label_incoterms, 1); } else { print $form->select_incoterms((!empty($object->fk_incoterms) ? $object->fk_incoterms : ''), (!empty($object->location_incoterms) ? $object->location_incoterms : ''), $_SERVER['PHP_SELF'].'?id='.$object->id); @@ -2716,11 +2654,9 @@ if ($action == 'create') print '</td>'; print '<td>'; - if ($action == 'editmode') - { + if ($action == 'editmode') { $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'transport_mode_id', 1, 1); - } - else { + } else { $form->formSelectTransportMode($_SERVER['PHP_SELF'].'?id='.$object->id, $object->transport_mode_id, 'none'); } print '</td></tr>'; @@ -2739,8 +2675,7 @@ if ($action == 'create') print '<table class="border tableforfield centpercent">'; - if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) - { + if (!empty($conf->multicurrency->enabled) && ($object->multicurrency_code != $conf->currency)) { // Multicurrency Amount HT print '<tr><td class="titlefieldmiddle">'.$form->editfieldkey('MulticurrencyAmountHT', 'multicurrency_total_ht', '', $object, 0).'</td>'; print '<td class="nowrap">'.price($object->multicurrency_total_ht, '', $langs, 0, - 1, - 1, (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)).'</td>'; @@ -2760,10 +2695,16 @@ if ($action == 'create') // Amount print '<tr><td class="titlefield">'.$langs->trans('AmountHT').'</td><td>'.price($object->total_ht, 1, $langs, 0, -1, -1, $conf->currency).'</td></tr>'; print '<tr><td>'.$langs->trans('AmountVAT').'</td><td>'.price($object->total_tva, 1, $langs, 0, -1, -1, $conf->currency).'<div class="inline-block"> &nbsp; &nbsp; &nbsp; &nbsp; '; - if (GETPOST('calculationrule')) $calculationrule = GETPOST('calculationrule', 'alpha'); - else $calculationrule = (empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND) ? 'totalofround' : 'roundoftotal'); - if ($calculationrule == 'totalofround') $calculationrulenum = 1; - else $calculationrulenum = 2; + if (GETPOST('calculationrule')) { + $calculationrule = GETPOST('calculationrule', 'alpha'); + } else { + $calculationrule = (empty($conf->global->MAIN_ROUNDOFTOTAL_NOT_TOTALOFROUND) ? 'totalofround' : 'roundoftotal'); + } + if ($calculationrule == 'totalofround') { + $calculationrulenum = 1; + } else { + $calculationrulenum = 2; + } // Show link for "recalculate" if ($object->getVentilExportCompta() == 0) { $s = $langs->trans("ReCalculate").' '; @@ -2776,14 +2717,12 @@ if ($action == 'create') // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($societe->localtax1_assuj == "1") //Localtax1 - { + if ($societe->localtax1_assuj == "1") { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($societe->localtax2_assuj == "1") //Localtax2 - { + if ($societe->localtax2_assuj == "1") { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; @@ -2793,23 +2732,37 @@ if ($action == 'create') print '</table>'; /* - * List of payments - */ + * List of payments + */ $totalpaye = 0; $sign = 1; - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = - 1; + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $sign = - 1; + } $nbrows = 9; $nbcols = 3; - if (!empty($conf->projet->enabled)) $nbrows++; - if (!empty($conf->banque->enabled)) { $nbrows++; $nbcols++; } - if (!empty($conf->incoterm->enabled)) $nbrows++; - if (!empty($conf->multicurrency->enabled)) $nbrows += 5; + if (!empty($conf->projet->enabled)) { + $nbrows++; + } + if (!empty($conf->banque->enabled)) { + $nbrows++; $nbcols++; + } + if (!empty($conf->incoterm->enabled)) { + $nbrows++; + } + if (!empty($conf->multicurrency->enabled)) { + $nbrows += 5; + } // Local taxes - if ($societe->localtax1_assuj == "1") $nbrows++; - if ($societe->localtax2_assuj == "1") $nbrows++; + if ($societe->localtax1_assuj == "1") { + $nbrows++; + } + if ($societe->localtax2_assuj == "1") { + $nbrows++; + } $sql = 'SELECT p.datep as dp, p.ref, p.num_paiement as num_payment, p.rowid, p.fk_bank,'; $sql .= ' c.id as paiement_type,'; @@ -2824,8 +2777,7 @@ if ($action == 'create') $sql .= ' ORDER BY p.datep, p.tms'; $result = $db->query($sql); - if ($result) - { + if ($result) { $num = $db->num_rows($result); $i = 0; @@ -2835,15 +2787,15 @@ if ($action == 'create') print '<td class="liste_titre">'.($object->type == FactureFournisseur::TYPE_CREDIT_NOTE ? $langs->trans("PaymentsBack") : $langs->trans('Payments')).'</td>'; print '<td>'.$langs->trans('Date').'</td>'; print '<td>'.$langs->trans('Type').'</td>'; - if (!empty($conf->banque->enabled)) print '<td class="right">'.$langs->trans('BankAccount').'</td>'; + if (!empty($conf->banque->enabled)) { + print '<td class="right">'.$langs->trans('BankAccount').'</td>'; + } print '<td class="right">'.$langs->trans('Amount').'</td>'; print '<td width="18">&nbsp;</td>'; print '</tr>'; - if ($num > 0) - { - while ($i < $num) - { + if ($num > 0) { + while ($i < $num) { $objp = $db->fetch_object($result); $paymentstatic->id = $objp->rowid; @@ -2860,8 +2812,7 @@ if ($action == 'create') print '<td>'; print $form->form_modes_reglement(null, $objp->paiement_type, 'none').' '.$objp->num_payment; print '</td>'; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { $bankaccountstatic->id = $objp->baid; $bankaccountstatic->ref = $objp->baref; $bankaccountstatic->label = $objp->baref; @@ -2876,13 +2827,14 @@ if ($action == 'create') } print '<td class="right">'; - if ($objp->baid > 0) print $bankaccountstatic->getNomUrl(1, 'transactions'); + if ($objp->baid > 0) { + print $bankaccountstatic->getNomUrl(1, 'transactions'); + } print '</td>'; } print '<td class="right">'.price($sign * $objp->amount).'</td>'; print '<td class="center">'; - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { + if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { print '<a href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=deletepayment&token='.newToken().'&paiement_id='.$objp->rowid.'">'; print img_delete(); print '</a>'; @@ -2897,16 +2849,16 @@ if ($action == 'create') } /* - if ($object->paye == 0) - { - print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('AlreadyPaid').' :</td><td class="right">'.price($totalpaye).'</td><td></td></tr>'; - print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($object->total_ttc).'</td><td></td></tr>'; + if ($object->paye == 0) + { + print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('AlreadyPaid').' :</td><td class="right">'.price($totalpaye).'</td><td></td></tr>'; + print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans("Billed").' :</td><td class="right">'.price($object->total_ttc).'</td><td></td></tr>'; - $resteapayer = $object->total_ttc - $totalpaye; + $resteapayer = $object->total_ttc - $totalpaye; - print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('RemainderToPay').' :</td>'; - print '<td class="right'.($resteapayer?' amountremaintopay':'').'">'.price($resteapayer).'</td><td></td></tr>'; - } + print '<tr><td colspan="'.$nbcols.'" class="right">'.$langs->trans('RemainderToPay').' :</td>'; + print '<td class="right'.($resteapayer?' amountremaintopay':'').'">'.price($resteapayer).'</td><td></td></tr>'; + } */ $db->free($result); @@ -2914,14 +2866,15 @@ if ($action == 'create') dol_print_error($db); } - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { // Total already paid print '<tr><td colspan="'.$nbcols.'" class="right">'; print '<span class="opacitymedium">'; - if ($object->type != FactureFournisseur::TYPE_DEPOSIT) + if ($object->type != FactureFournisseur::TYPE_DEPOSIT) { print $langs->trans('AlreadyPaidNoCreditNotesNoDeposits'); - else print $langs->trans('AlreadyPaid'); + } else { + print $langs->trans('AlreadyPaid'); + } print '</span>'; print '</td><td class="right"'.(($totalpaye > 0) ? ' class="amountalreadypaid"' : '').'>'.price($totalpaye).'</td><td>&nbsp;</td></tr>'; @@ -2948,10 +2901,12 @@ if ($action == 'create') $obj = $db->fetch_object($resql); $invoice->fetch($obj->fk_invoice_supplier_source); print '<tr><td colspan="'.$nbcols.'" class="right">'; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) { print $langs->trans("CreditNote").' '; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + } + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) { print $langs->trans("Deposit").' '; + } print $invoice->getNomUrl(0); print ' :</td>'; print '<td class="right">'.price($obj->amount_ttc).'</td>'; @@ -2959,10 +2914,12 @@ if ($action == 'create') print '<a href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&action=unlinkdiscount&discountid='.$obj->rowid.'">'.img_delete().'</a>'; print '</td></tr>'; $i++; - if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) + if ($invoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $creditnoteamount += $obj->amount_ttc; - if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) + } + if ($invoice->type == FactureFournisseur::TYPE_DEPOSIT) { $depositamount += $obj->amount_ttc; + } } } else { dol_print_error($db); @@ -3002,8 +2959,9 @@ if ($action == 'create') if (($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED) && $object->close_code == 'abandon') { print '<tr><td colspan="'.$nbcols.'" class="right nowrap">'; $text = $langs->trans("HelpAbandonOther"); - if ($object->close_note) + if ($object->close_note) { $text .= '<br><br><b>'.$langs->trans("Reason").'</b>:'.$object->close_note; + } print '<span class="opacitymedium">'; print $form->textwithpicto($langs->trans("Abandoned"), $text, - 1); print '</span>'; @@ -3022,9 +2980,11 @@ if ($action == 'create') // Remainder to pay print '<tr><td colspan="'.$nbcols.'" class="right">'; print '<span class="opacitymedium">'; - if ($resteapayeraffiche >= 0) + if ($resteapayeraffiche >= 0) { print $langs->trans('RemainderToPay'); - else print $langs->trans('ExcessPaid'); + } else { + print $langs->trans('ExcessPaid'); + } print '</span>'; print '</td>'; print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($resteapayeraffiche).'</td>'; @@ -3044,9 +3004,11 @@ if ($action == 'create') // Remainder to pay back print '<tr><td colspan="'.$nbcols.'" class="right">'; print '<span class="opacitymedium">'; - if ($resteapayeraffiche <= 0) + if ($resteapayeraffiche <= 0) { print $langs->trans('RemainderToPayBack'); - else print $langs->trans('ExcessPaid'); + } else { + print $langs->trans('ExcessPaid'); + } print '</td>'; print '</span>'; print '<td class="right'.($resteapayeraffiche ? ' amountremaintopay' : (' '.$cssforamountpaymentcomplete)).'">'.price($sign * $resteapayeraffiche).'</td>'; @@ -3067,15 +3029,13 @@ if ($action == 'create') print '<div class="clearboth"></div><br>'; - if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_CONTACTS_TAB)) { $blocname = 'contacts'; $title = $langs->trans('ContactsAddresses'); include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php'; } - if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) - { + if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { $colwidth = 20; $blocname = 'notes'; $title = $langs->trans('Notes'); @@ -3084,8 +3044,8 @@ if ($action == 'create') /* - * Lines - */ + * Lines + */ print '<form name="addproduct" id="addproduct" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.(($action != 'editline') ? '#addline' : '#line_'.GETPOST('lineid')).'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="'.(($action != 'editline') ? 'addline' : 'updateline').'">'; @@ -3104,7 +3064,9 @@ if ($action == 'create') $forceall = 1; $dateSelector = 0; $inputalsopricewithtax = 1; $senderissupplier = 2; // $senderissupplier=2 is same than 1 but disable test on minimum qty and disable autofill qty with minimum. //if (! empty($conf->global->SUPPLIER_INVOICE_WITH_NOPRICEDEFINED)) $senderissupplier=2; - if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) $senderissupplier = 1; + if (!empty($conf->global->SUPPLIER_INVOICE_WITH_PREDEFINED_PRICES_ONLY)) { + $senderissupplier = 1; + } // Show object lines if (!empty($object->lines)) { @@ -3114,10 +3076,8 @@ if ($action == 'create') $num = count($object->lines); // Form to add new line - if ($object->statut == FactureFournisseur::STATUS_DRAFT && $usercancreate) - { - if ($action != 'editline') - { + if ($object->statut == FactureFournisseur::STATUS_DRAFT && $usercancreate) { + if ($action != 'editline') { // Add free products/services $object->formAddObjectLine(1, $societe, $mysoc); @@ -3133,27 +3093,23 @@ if ($action == 'create') print dol_get_fiche_end(); - if ($action != 'presend') - { + if ($action != 'presend') { /* - * Buttons actions - */ + * Buttons actions + */ print '<div class="tabsAction">'; $parameters = array(); $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been // modified by hook - if (empty($reshook)) - { + if (empty($reshook)) { // Modify a validated invoice with no payments - if ($object->statut == FactureFournisseur::STATUS_VALIDATED && $action != 'confirm_edit' && $object->getSommePaiement() == 0 && $usercancreate) - { + 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 $ventilExportCompta = $object->getVentilExportCompta(); // Should be 0 since the sum of payments are zero. But we keep the protection. - if ($ventilExportCompta == 0) - { + if ($ventilExportCompta == 0) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=edit">'.$langs->trans('Modify').'</a></div>'; } else { print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Modify').'</span></div>'; @@ -3163,13 +3119,11 @@ if ($action == 'create') $discount = new DiscountAbsolute($db); $result = $discount->fetch(0, 0, $object->id); - // Reopen a standard paid invoice + // Reopen a standard paid invoice if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_REPLACEMENT || ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && empty($discount->id))) - && ($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED)) // A paid invoice (partially or completely) - { - if (!$facidnext && $object->close_code != 'replaced' && $usercancreate) // Not replaced by another invoice - { + && ($object->statut == FactureFournisseur::STATUS_CLOSED || $object->statut == FactureFournisseur::STATUS_ABANDONED)) { // A paid invoice (partially or completely) + if (!$facidnext && $object->close_code != 'replaced' && $usercancreate) { // Not replaced by another invoice print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=reopen">'.$langs->trans('ReOpen').'</a></div>'; } else { if ($usercancreate) { @@ -3182,24 +3136,22 @@ if ($action == 'create') // Send by mail if (empty($user->socid)) { - if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) - { - if ($usercansend) - { + if (($object->statut == FactureFournisseur::STATUS_VALIDATED || $object->statut == FactureFournisseur::STATUS_CLOSED)) { + if ($usercansend) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'; - } else print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip">'.$langs->trans('SendMail').'</a></div>'; + } else { + print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip">'.$langs->trans('SendMail').'</a></div>'; + } } } // Make payments - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) - { + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE && $action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create'.($object->fk_account > 0 ? '&amp;accountid='.$object->fk_account : '').'">'.$langs->trans('DoPayment').'</a></div>'; // 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) - { + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_VALIDATED && $object->paye == 0 && $user->socid == 0) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=paid"'; print '>'.$langs->trans('ClassifyPaid').'</a></div>'; @@ -3209,10 +3161,8 @@ if ($action == 'create') // Reverse back money or convert to reduction if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE || $object->type == FactureFournisseur::TYPE_DEPOSIT || $object->type == FactureFournisseur::TYPE_STANDARD) { // For credit note only - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) - { - if ($resteapayer == 0) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE && $object->statut == 1 && $object->paye == 0) { + if ($resteapayer == 0) { print '<div class="inline-block divButAction"><span class="butActionRefused classfortooltip" title="'.$langs->trans("DisabledBecauseRemainderToPayIsZero").'">'.$langs->trans('DoPaymentBack').'</span></div>'; } else { print '<div class="inline-block divButAction"><a class="butAction" href="paiement.php?facid='.$object->id.'&amp;action=create&amp;accountid='.$object->fk_account.'">'.$langs->trans('DoPaymentBack').'</a></div>'; @@ -3220,8 +3170,7 @@ if ($action == 'create') } // For standard invoice with excess paid - if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $usercancreate && empty($discount->id)) - { + if ($object->type == FactureFournisseur::TYPE_STANDARD && empty($object->paye) && ($object->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits) < 0 && $usercancreate && empty($discount->id)) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertExcessPaidToReduc').'</a></div>'; } // For credit note @@ -3231,19 +3180,15 @@ if ($action == 'create') print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc" title="'.dol_escape_htmltag($langs->trans("ConfirmConvertToReducSupplier2")).'">'.$langs->trans('ConvertToReduc').'</a></div>'; } // For deposit invoice - if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->paye == 1 && $resteapayer == 0 && $usercancreate && empty($discount->id)) - { + if ($object->type == FactureFournisseur::TYPE_DEPOSIT && $object->paye == 1 && $resteapayer == 0 && $usercancreate && empty($discount->id)) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?facid='.$object->id.'&amp;action=converttoreduc">'.$langs->trans('ConvertToReduc').'</a></div>'; } } // Validate - if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) - { - if (count($object->lines)) - { - if ($usercanvalidate) - { + if ($action != 'confirm_edit' && $object->statut == FactureFournisseur::STATUS_DRAFT) { + if (count($object->lines)) { + if ($usercanvalidate) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=valid"'; print '>'.$langs->trans('Validate').'</a></div>'; } else { @@ -3260,24 +3205,20 @@ if ($action == 'create') }*/ // Clone - if ($action != 'edit' && $usercancreate) - { + if ($action != 'edit' && $usercancreate) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=clone&amp;socid='.$object->socid.'">'.$langs->trans('ToClone').'</a></div>'; } // Create a credit note - if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $usercancreate) - { - if (!$objectidnext) - { + if (($object->type == FactureFournisseur::TYPE_STANDARD || $object->type == FactureFournisseur::TYPE_DEPOSIT) && $object->statut > 0 && $usercancreate) { + if (!$objectidnext) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?socid='.$object->socid.'&amp;fac_avoir='.$object->id.'&amp;action=create&amp;type=2'.($object->fk_project > 0 ? '&amp;projectid='.$object->fk_project : '').'">'.$langs->trans("CreateCreditNote").'</a></div>'; } } // 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) - { + 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 '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecausePayments").'">'.$langs->trans('Delete').'</a></div>'; @@ -3287,8 +3228,7 @@ if ($action == 'create') print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotLastInvoice").'">'.$langs->trans('Delete').'</a></div>'; } elseif ($isErasable == -1) { print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseDispatchedInBookkeeping").'">'.$langs->trans('Delete').'</a></div>'; - } elseif ($isErasable <= 0) // Any other cases - { + } elseif ($isErasable <= 0) { // Any other cases print '<div class="inline-block divButAction"><a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("DisabledBecauseNotErasable").'">'.$langs->trans('Delete').'</a></div>'; } else { print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'; @@ -3296,13 +3236,12 @@ if ($action == 'create') } print '</div>'; - if ($action != 'confirm_edit') - { + if ($action != 'confirm_edit') { print '<div class="fichecenter"><div class="fichehalfleft">'; /* - * Documents generes - */ + * Documents generes + */ $ref = dol_sanitizeFileName($object->ref); $subdir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; $filedir = $conf->fournisseur->facture->dir_output.'/'.$subdir; diff --git a/htdocs/fourn/facture/contact.php b/htdocs/fourn/facture/contact.php index d655b97c74f..4f450bca3c4 100644 --- a/htdocs/fourn/facture/contact.php +++ b/htdocs/fourn/facture/contact.php @@ -41,7 +41,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); $object = new FactureFournisseur($db); @@ -51,51 +53,39 @@ $object = new FactureFournisseur($db); * Ajout d'un nouveau contact */ -if ($action == 'addcontact' && $user->rights->fournisseur->facture->creer) -{ +if ($action == 'addcontact' && $user->rights->fournisseur->facture->creer) { $result = $object->fetch($id, $ref); - if ($result > 0 && $id > 0) - { + if ($result > 0 && $id > 0) { $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $langs->load("errors"); setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} - -// bascule du statut d'un contact -elseif ($action == 'swapstatut' && $user->rights->fournisseur->facture->creer) -{ - if ($object->fetch($id)) - { +} elseif ($action == 'swapstatut' && $user->rights->fournisseur->facture->creer) { + // bascule du statut d'un contact + if ($object->fetch($id)) { $result = $object->swapContactStatus(GETPOST('ligne')); } else { dol_print_error($db); } -} - -// Efface un contact -elseif ($action == 'deletecontact' && $user->rights->fournisseur->facture->creer) -{ +} elseif ($action == 'deletecontact' && $user->rights->fournisseur->facture->creer) { + // Efface un contact $object->fetch($id); $result = $object->delete_contact($_GET["lineid"]); - if ($result >= 0) - { + if ($result >= 0) { header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); exit; } else { @@ -124,10 +114,8 @@ $userstatic = new User($db); /* */ /* *************************************************************************** */ -if ($id > 0 || !empty($ref)) -{ - if ($object->fetch($id, $ref) > 0) - { +if ($id > 0 || !empty($ref)) { + if ($object->fetch($id, $ref) > 0) { $object->fetch_thirdparty(); $alreadypaid = $object->getSommePaiement(); @@ -144,17 +132,18 @@ if ($id > 0 || !empty($ref)) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') + if ($user->rights->facture->creer) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $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 .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -192,36 +181,34 @@ if ($id > 0 || !empty($ref)) // Type print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td colspan="4">'; print $object->getLibType(); - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { + 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) - { + 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) - { + if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i = 0; - foreach ($facidavoir as $fid) - { - if ($i == 0) print ' '; - else print ','; + foreach ($facidavoir as $fid) { + if ($i == 0) { + print ' '; + } else { + print ','; + } $facavoir = new FactureFournisseur($db); $facavoir->fetch($fid); print $facavoir->getNomUrl(1); } print ')'; } - if ($facidnext > 0) - { + if ($facidnext > 0) { $facthatreplace = new FactureFournisseur($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; @@ -239,14 +226,12 @@ if ($id > 0 || !empty($ref)) // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($societe->localtax1_assuj == "1") //Localtax1 - { + if ($societe->localtax1_assuj == "1") { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($societe->localtax2_assuj == "1") //Localtax2 - { + if ($societe->localtax2_assuj == "1") { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; diff --git a/htdocs/fourn/facture/document.php b/htdocs/fourn/facture/document.php index 4b2b45c7226..24009d35dbc 100644 --- a/htdocs/fourn/facture/document.php +++ b/htdocs/fourn/facture/document.php @@ -46,7 +46,9 @@ $confirm = GETPOST('confirm', 'alpha'); $ref = GETPOST('ref', 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); // Get parameters @@ -54,16 +56,21 @@ $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 +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 = "ASC"; -if (!$sortfield) $sortfield = "name"; +if (!$sortorder) { + $sortorder = "ASC"; +} +if (!$sortfield) { + $sortfield = "name"; +} $object = new FactureFournisseur($db); -if ($object->fetch($id, $ref)) -{ +if ($object->fetch($id, $ref)) { $object->fetch_thirdparty(); $ref = dol_sanitizeFileName($object->ref); $upload_dir = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').$ref; @@ -87,8 +94,7 @@ $title = $langs->trans('SupplierInvoice')." - ".$langs->trans('Documents'); $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores"; llxHeader('', $title, $helpurl); -if ($object->id > 0) -{ +if ($object->id > 0) { $head = facturefourn_prepare_head($object); print dol_get_fiche_head($head, 'documents', $langs->trans('SupplierInvoice'), -1, 'supplier_invoice'); @@ -102,17 +108,18 @@ if ($object->id > 0) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') + if ($user->rights->facture->creer) { + if ($action != 'classify') { //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $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 .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; @@ -148,16 +155,14 @@ if ($object->id > 0) // Build file list $filearray = dol_dir_list($upload_dir, "files", 0, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1); $totalsize = 0; - foreach ($filearray as $key => $file) - { + foreach ($filearray as $key => $file) { $totalsize += $file['size']; } /* * Confirm delete file */ - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&urlfile='.urlencode($_GET["urlfile"]), $langs->trans('DeleteFile'), $langs->trans('ConfirmDeleteFile'), 'confirm_deletefile', '', 0, 1); } @@ -166,28 +171,27 @@ if ($object->id > 0) // Type print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>'; print $object->getLibType(); - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { + 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) - { + 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) - { + if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i = 0; - foreach ($facidavoir as $id) - { - if ($i == 0) print ' '; - else print ','; + foreach ($facidavoir as $id) { + if ($i == 0) { + print ' '; + } else { + print ','; + } $facavoir = new FactureFournisseur($db); $facavoir->fetch($id); print $facavoir->getNomUrl(1); @@ -215,14 +219,12 @@ if ($object->id > 0) // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($mysoc->localtax1_assuj == "1") //Localtax1 - { + if ($mysoc->localtax1_assuj == "1") { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $mysoc->country_code).'</td>'; print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($mysoc->localtax2_assuj == "1") //Localtax2 - { + if ($mysoc->localtax2_assuj == "1") { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $mysoc->country_code).'</td>'; print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; @@ -255,8 +257,7 @@ if ($object->id > 0) $defaulttpldir = '/core/tpl'; $dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir)); - foreach ($dirtpls as $module => $reldir) - { + foreach ($dirtpls as $module => $reldir) { if (!empty($module)) { $tpl = dol_buildpath($reldir.'/document_actions_post_headers.tpl.php'); } else { @@ -268,7 +269,9 @@ if ($object->id > 0) } else { $res = include $tpl; // for debug } - if ($res) break; + if ($res) { + break; + } } } else { print $langs->trans('ErrorUnknown'); diff --git a/htdocs/fourn/facture/impayees.php b/htdocs/fourn/facture/impayees.php index 18c4bff9036..7019b90b868 100644 --- a/htdocs/fourn/facture/impayees.php +++ b/htdocs/fourn/facture/impayees.php @@ -31,7 +31,9 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; -if (!$user->rights->fournisseur->facture->lire) accessforbidden(); +if (!$user->rights->fournisseur->facture->lire) { + accessforbidden(); +} $langs->loadLangs(array("companies", "bills")); @@ -39,8 +41,7 @@ $socid = GETPOST('socid', 'int'); $option = GETPOST('option'); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -56,15 +57,20 @@ $search_amount_all_tax = GETPOST('search_amount_all_tax', 'alpha'); $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = "f.date_lim_reglement"; -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "f.date_lim_reglement"; +} +if (!$sortorder) { + $sortorder = "ASC"; +} -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // Both test are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // Both test are required to be compatible with all browsers $search_ref = ""; $search_ref_supplier = ""; $search_company = ""; @@ -85,101 +91,124 @@ $title = $langs->trans("BillsSuppliersUnpaid"); $facturestatic = new FactureFournisseur($db); $companystatic = new Societe($db); -if ($user->rights->fournisseur->facture->lire) -{ +if ($user->rights->fournisseur->facture->lire) { $sql = "SELECT s.rowid as socid, s.nom as name,"; $sql .= " f.rowid, f.ref, f.ref_supplier, f.total_ht, f.total_ttc,"; $sql .= " f.datef as df, f.date_lim_reglement as datelimite, "; $sql .= " f.paye as paye, f.rowid as facid, f.fk_statut"; $sql .= " ,sum(pf.amount) as am"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ",".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."paiementfourn_facturefourn as pf ON f.rowid=pf.fk_facturefourn "; $sql .= " WHERE f.entity = ".$conf->entity; $sql .= " AND f.fk_soc = s.rowid"; $sql .= " AND f.paye = 0 AND f.fk_statut = 1"; - if ($option == 'late') $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if ($option == 'late') { + $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } - if (GETPOST('filtre')) - { + if (GETPOST('filtre')) { $filtrearr = explode(",", GETPOST('filtre')); - foreach ($filtrearr as $fil) - { + foreach ($filtrearr as $fil) { $filt = explode(":", $fil); $sql .= " AND ".$filt[0]." = ".$filt[1]; } } - if ($search_ref) - { + if ($search_ref) { $sql .= " AND f.ref LIKE '%".$db->escape($search_ref)."%'"; } - if ($search_ref_supplier) - { + if ($search_ref_supplier) { $sql .= " AND f.ref_supplier LIKE '%".$db->escape($search_ref_supplier)."%'"; } - if ($search_company) - { + if ($search_company) { $sql .= " AND s.nom LIKE '%".$db->escape($search_company)."%'"; } - if ($search_amount_no_tax) - { + if ($search_amount_no_tax) { $sql .= " AND f.total_ht = '".$db->escape($search_amount_no_tax)."'"; } - if ($search_amount_all_tax) - { + if ($search_amount_all_tax) { $sql .= " AND f.total_ttc = '".$db->escape($search_amount_all_tax)."'"; } - if (dol_strlen(GETPOST('sf_re')) > 0) - { + if (dol_strlen(GETPOST('sf_re')) > 0) { $sql .= " AND f.ref_supplier LIKE '%".$db->escape(GETPOST('sf_re'))."%'"; } $sql .= " GROUP BY s.rowid, s.nom, f.rowid, f.ref, f.ref_supplier, f.total_ht, f.total_ttc, f.datef, f.date_lim_reglement, f.paye, f.fk_statut"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= $db->order($sortfield, $sortorder); - if (!in_array("f.ref_supplier", explode(',', $sortfield))) $sql .= ", f.ref_supplier DESC"; + if (!in_array("f.ref_supplier", explode(',', $sortfield))) { + $sql .= ", f.ref_supplier DESC"; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($socid) - { + if ($socid) { $soc = new Societe($db); $soc->fetch($socid); } $param = ''; - if ($socid) $param .= "&socid=".$socid; + if ($socid) { + $param .= "&socid=".$socid; + } - if ($search_ref) $param .= '&amp;search_ref='.urlencode($search_ref); - if ($search_ref_supplier) $param .= '&amp;search_ref_supplier='.urlencode($search_ref_supplier); - if ($search_company) $param .= '&amp;search_company='.urlencode($search_company); - if ($search_amount_no_tax) $param .= '&amp;search_amount_no_tax='.urlencode($search_amount_no_tax); - if ($search_amount_all_tax) $param .= '&amp;search_amount_all_tax='.urlencode($search_amount_all_tax); + if ($search_ref) { + $param .= '&amp;search_ref='.urlencode($search_ref); + } + if ($search_ref_supplier) { + $param .= '&amp;search_ref_supplier='.urlencode($search_ref_supplier); + } + if ($search_company) { + $param .= '&amp;search_company='.urlencode($search_company); + } + if ($search_amount_no_tax) { + $param .= '&amp;search_amount_no_tax='.urlencode($search_amount_no_tax); + } + if ($search_amount_all_tax) { + $param .= '&amp;search_amount_all_tax='.urlencode($search_amount_all_tax); + } $param .= ($option ? "&option=".$option : ""); - if (!empty($late)) $param .= '&late='.urlencode($late); + if (!empty($late)) { + $param .= '&late='.urlencode($late); + } $urlsource = str_replace('&amp;', '&', $param); $titre = ($socid ? $langs->trans("BillsSuppliersUnpaidForCompany", $soc->name) : $langs->trans("BillsSuppliersUnpaid")); - if ($option == 'late') $titre .= ' ('.$langs->trans("Late").')'; - else $titre .= ' ('.$langs->trans("All").')'; + if ($option == 'late') { + $titre .= ' ('.$langs->trans("Late").')'; + } else { + $titre .= ' ('.$langs->trans("All").')'; + } $link = ''; - if (empty($option)) $link = '<a href="'.$_SERVER["PHP_SELF"].'?option=late'.($socid ? '&socid='.$socid : '').'">'.$langs->trans("ShowUnpaidLateOnly").'</a>'; - elseif ($option == 'late') $link = '<a href="'.$_SERVER["PHP_SELF"].'?'.($socid ? '&socid='.$socid : '').'">'.$langs->trans("ShowUnpaidAll").'</a>'; + if (empty($option)) { + $link = '<a href="'.$_SERVER["PHP_SELF"].'?option=late'.($socid ? '&socid='.$socid : '').'">'.$langs->trans("ShowUnpaidLateOnly").'</a>'; + } elseif ($option == 'late') { + $link = '<a href="'.$_SERVER["PHP_SELF"].'?'.($socid ? '&socid='.$socid : '').'">'.$langs->trans("ShowUnpaidAll").'</a>'; + } print load_fiche_titre($titre, $link); print_barre_liste('', '', $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', 0); // We don't want pagination on this page @@ -220,14 +249,12 @@ if ($user->rights->fournisseur->facture->lire) print '</td>'; print "</tr>\n"; - if ($num > 0) - { + if ($num > 0) { $total_ht = 0; $total_ttc = 0; $total_paid = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $facturestatic->statut = $objp->fk_statut; diff --git a/htdocs/fourn/facture/index.php b/htdocs/fourn/facture/index.php index 131b34bbe39..8904310bf3e 100644 --- a/htdocs/fourn/facture/index.php +++ b/htdocs/fourn/facture/index.php @@ -34,8 +34,7 @@ $langs->loadLangs(['bills', 'boxes']); // Filter to show only result of one supplier $socid = GETPOST('socid', 'int'); -if (isset($user->socid) && $user->socid > 0) -{ +if (isset($user->socid) && $user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -58,8 +57,7 @@ print '<div class="fichecenter">'; print '<div class="fichethirdleft">'; // This is useless due to the global search combo -if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) -{ +if (!empty($conf->global->MAIN_SEARCH_FORM_ON_HOME_AREAS)) { print getAreaSearchFrom(); print '<br>'; } @@ -129,16 +127,21 @@ function getPieChart($socid = 0) $sql = "SELECT count(f.rowid), f.fk_statut"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."facture_fourn as f"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; - if ($user->socid) $sql .= ' AND f.fk_soc = '.$user->socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($user->socid) { + $sql .= ' AND f.fk_soc = '.$user->socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " GROUP BY f.fk_statut"; $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -149,11 +152,9 @@ function getPieChart($socid = 0) $total = 0; $vals = []; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); - if ($row) - { + if ($row) { $vals[$row[1]] = $row[0]; $total += $row[0]; } @@ -174,14 +175,12 @@ function getPieChart($socid = 0) $array = [FactureFournisseur::STATUS_DRAFT, FactureFournisseur::STATUS_VALIDATED, FactureFournisseur::STATUS_CLOSED, FactureFournisseur::STATUS_ABANDONED]; $dataseries = []; - foreach ($array as $status) - { + foreach ($array as $status) { $objectstatic->statut = $status; $objectstatic->paye = $status == FactureFournisseur::STATUS_CLOSED ? -1 : 0; $dataseries[] = [$objectstatic->getLibStatut(1), (isset($vals[$status]) ? (int) $vals[$status] : 0)]; - if (!$conf->use_javascript_ajax) - { + if (!$conf->use_javascript_ajax) { $result .= '<tr class="oddeven">'; $result .= '<td>'.$objectstatic->getLibStatut(0).'</td>'; $result .= '<td class="right"><a href="list.php?statut='.$status.'">'.(isset($vals[$status]) ? $vals[$status] : 0).'</a></td>'; @@ -189,8 +188,7 @@ function getPieChart($socid = 0) } } - if ($conf->use_javascript_ajax) - { + if ($conf->use_javascript_ajax) { $dolgraph = new DolGraph(); $dolgraph->SetData($dataseries); $dolgraph->setShowLegend(2); @@ -229,17 +227,22 @@ function getDraftTable($maxCount = 500, $socid = 0) $sql = "SELECT f.rowid, f.ref, s.nom as socname, s.rowid as socid, s.canvas, s.client, f.total_ttc"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; $sql .= " AND f.fk_statut = ".FactureFournisseur::STATUS_DRAFT; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= $db->plimit($maxCount, 0); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -258,8 +261,7 @@ function getDraftTable($maxCount = 500, $socid = 0) $result .= '</td>'; $result .= '</tr>'; - if ($num < 1) - { + if ($num < 1) { $result .= '</table>'; $result .= '</div>'; return $result; @@ -271,8 +273,7 @@ function getDraftTable($maxCount = 500, $socid = 0) $total = 0; $i = 0; - while ($i < $nbofloop) - { + while ($i < $nbofloop) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -293,14 +294,11 @@ function getDraftTable($maxCount = 500, $socid = 0) $total += $obj->total_ttc; } - if ($num > $nbofloop) - { + if ($num > $nbofloop) { $result .= '<tr class="liste_total">'; $result .= '<td colspan="3" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>'; $result .= '</tr>'; - } - elseif ($total > 0) - { + } elseif ($total > 0) { $result .= '<tr class="liste_total">'; $result .= '<td colspan="2" class="right">'.$langs->trans("Total").'</td>'; $result .= '<td class="right">'.price($total).'</td>'; @@ -327,17 +325,22 @@ function getLatestEditTable($maxCount = 5, $socid = 0) $sql .= " f.datec"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $sql .= " ORDER BY f.tms DESC"; $sql .= $db->plimit($maxCount, 0); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -350,8 +353,7 @@ function getLatestEditTable($maxCount = 5, $socid = 0) $result .= '<td colspan="4">'.$langs->trans("BoxTitleLastSupplierBills", $maxCount).'</td>'; $result .= '</tr>'; - if ($num < 1) - { + if ($num < 1) { $result .= '</table>'; $result .= '</div>'; return $result; @@ -362,8 +364,7 @@ function getLatestEditTable($maxCount = 5, $socid = 0) $formfile = new FormFile($db); $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->rowid; @@ -423,18 +424,23 @@ function getOpenTable($maxCount = 500, $socid = 0) $sql .= ", f.datef as df, f.date_lim_reglement as datelimite"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."facture_fourn as f"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= " WHERE f.fk_soc = s.rowid"; $sql .= " AND f.entity IN (".getEntity('facture_fourn').")"; $sql .= " AND f.fk_statut = ".FactureFournisseur::STATUS_VALIDATED; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; - if ($socid) $sql .= " AND s.rowid = ".$socid; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } + if ($socid) { + $sql .= " AND s.rowid = ".$socid; + } $sql .= " ORDER BY f.rowid DESC"; $sql .= $db->plimit($maxCount, 0); $resql = $db->query($sql); - if (!$resql) - { + if (!$resql) { dol_print_error($db); return ''; } @@ -452,8 +458,7 @@ function getOpenTable($maxCount = 500, $socid = 0) $result .= '</td>'; $result .= '</tr>'; - if ($num < 1) - { + if ($num < 1) { $result .= '</table>'; $result .= '</div>'; return $result; @@ -467,8 +472,7 @@ function getOpenTable($maxCount = 500, $socid = 0) $total = 0; $i = 0; - while ($i < $nbofloop) - { + while ($i < $nbofloop) { $obj = $db->fetch_object($resql); $objectstatic->id = $obj->id; @@ -491,8 +495,7 @@ function getOpenTable($maxCount = 500, $socid = 0) $result .= '<td class="nobordernopadding nowrap">'.$objectstatic->getNomUrl(1).'</td>'; $result .= '<td width="18" class="nobordernopadding nowrap">'; - if ($db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) - { + if ($db->jdate($obj->dfv) < ($now - $conf->propal->cloture->warning_delay)) { $result .= img_warning($langs->trans("Late")); } @@ -514,14 +517,11 @@ function getOpenTable($maxCount = 500, $socid = 0) $total += $obj->total_ttc; } - if ($num > $nbofloop) - { + if ($num > $nbofloop) { $result .= '<tr class="liste_total">'; $result .= '<td colspan="4" class="right">'.$langs->trans("XMoreLines", ($num - $nbofloop)).'</td>'; $result .= '</tr>'; - } - elseif ($total > 0) - { + } elseif ($total > 0) { $result .= '<tr class="liste_total">'; $result .= '<td colspan="2" class="right">'.$langs->trans("Total").'</td>'; $result .= '<td align="right">'.price($total).'</td>'; diff --git a/htdocs/fourn/facture/info.php b/htdocs/fourn/facture/info.php index 69ea8839cfb..efe91880a56 100644 --- a/htdocs/fourn/facture/info.php +++ b/htdocs/fourn/facture/info.php @@ -40,7 +40,9 @@ $id = GETPOST("facid", 'int') ?GETPOST("facid", 'int') : GETPOST("id", 'int'); $ref = GETPOST("ref", 'alpha'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); $object = new FactureFournisseur($db); @@ -75,39 +77,40 @@ $morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_ $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); -if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; +if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; +} // Project -if (!empty($conf->projet->enabled)) -{ - $langs->load("projects"); - $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->facture->creer) - { - if ($action != 'classify') - //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - $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 .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref .= '<input type="hidden" name="action" value="classin">'; - $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref .= $formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref .= '</form>'; - } else { - $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); - } - } else { - if (!empty($object->fk_project)) { - $proj = new Project($db); - $proj->fetch($object->fk_project); - $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">'; - $morehtmlref .= $proj->ref; - $morehtmlref .= '</a>'; - } else { - $morehtmlref .= ''; - } - } +if (!empty($conf->projet->enabled)) { + $langs->load("projects"); + $morehtmlref .= '<br>'.$langs->trans('Project').' '; + if ($user->rights->facture->creer) { + if ($action != 'classify') { + //$morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; + $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 .= '<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref .= '<input type="hidden" name="action" value="classin">'; + $morehtmlref .= '<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref .= $formproject->select_projects($object->thirdparty->id, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref .= '<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref .= '</form>'; + } else { + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->thirdparty->id, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= '<a href="'.DOL_URL_ROOT.'/projet/card.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">'; + $morehtmlref .= $proj->ref; + $morehtmlref .= '</a>'; + } else { + $morehtmlref .= ''; + } + } } $morehtmlref .= '</div>'; diff --git a/htdocs/fourn/facture/list.php b/htdocs/fourn/facture/list.php index 99ab93ca973..7c6ed0c5e16 100644 --- a/htdocs/fourn/facture/list.php +++ b/htdocs/fourn/facture/list.php @@ -44,7 +44,9 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; -if (!$user->rights->fournisseur->facture->lire) accessforbidden(); +if (!$user->rights->fournisseur->facture->lire) { + accessforbidden(); +} // Load translation files required by the page $langs->loadLangs(array('products', 'bills', 'companies', 'projects')); @@ -120,12 +122,18 @@ $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 ($page == -1 || $page == null || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { $page = 0; } +if ($page == -1 || $page == null || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { + $page = 0; +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortorder) $sortorder = "DESC"; -if (!$sortfield) $sortfield = "f.datef,f.rowid"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "f.datef,f.rowid"; +} $diroutputmassaction = $conf->fournisseur->facture->dir_output.'/temp/massgeneration/'.$user->id; @@ -149,7 +157,9 @@ $fieldstosearchall = array( 's.nom'=>"ThirdParty", 'f.note_public'=>'NotePublic', ); -if (empty($user->socid)) $fieldstosearchall["f.note_private"] = "NotePrivate"; +if (empty($user->socid)) { + $fieldstosearchall["f.note_private"] = "NotePrivate"; +} $checkedtypetiers = 0; $arrayfields = array( @@ -198,19 +208,23 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); * Actions */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend' && $massaction != 'confirm_createbills') { + $massaction = ''; +} $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; - if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha')) // All tests must be present to be compatible with all browsers - { + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter', 'alpha') || GETPOST('button_removefilter.x', 'alpha')) { // All tests must be present to be compatible with all browsers $search_all = ""; $search_user = ''; $search_sale = ''; @@ -266,12 +280,10 @@ if (empty($reshook)) $uploaddir = $conf->fournisseur->facture->dir_output; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; - if ($massaction == 'banktransfertrequest') - { + if ($massaction == 'banktransfertrequest') { $langs->load("withdrawals"); - if (!$user->rights->paymentbybanktransfer->create) - { + if (!$user->rights->paymentbybanktransfer->create) { $error++; setEventMessages($langs->trans("NotEnoughPermissions"), null, 'errors'); } else { @@ -280,12 +292,10 @@ if (empty($reshook)) $arrayofselected = is_array($toselect) ? $toselect : array(); $listofbills = array(); - foreach ($arrayofselected as $toselectid) - { + foreach ($arrayofselected as $toselectid) { $objecttmp = new FactureFournisseur($db); $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $totalpaye = $objecttmp->getSommePaiement(); $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); $totaldeposits = $objecttmp->getSumDepositsUsed(); @@ -314,8 +324,7 @@ if (empty($reshook)) $rsql .= " ORDER BY pfd.date_demande DESC"; $result_sql = $db->query($rsql); - if ($result_sql) - { + if ($result_sql) { $numprlv = $db->num_rows($result_sql); } @@ -332,15 +341,12 @@ if (empty($reshook)) } //Massive withdraw request for request with no errors - if (!empty($listofbills)) - { + if (!empty($listofbills)) { $nbwithdrawrequestok = 0; - foreach ($listofbills as $aBill) - { + foreach ($listofbills as $aBill) { $db->begin(); $result = $aBill->demande_prelevement($user, $aBill->resteapayer, 'bank-transfer', 'supplier_invoice'); - if ($result > 0) - { + if ($result > 0) { $db->commit(); $nbwithdrawrequestok++; } else { @@ -348,8 +354,7 @@ if (empty($reshook)) setEventMessages($aBill->error, $aBill->errors, 'errors'); } } - if ($nbwithdrawrequestok > 0) - { + if ($nbwithdrawrequestok > 0) { setEventMessages($langs->trans("WithdrawRequestsDone", $nbwithdrawrequestok), null, 'mesgs'); } } @@ -358,8 +363,7 @@ if (empty($reshook)) } -if ($massaction == 'transfer_request') -{ +if ($massaction == 'transfer_request') { $langs->load("withdrawals"); if (!$user->rights->paymentbybanktransfer->create) { @@ -371,12 +375,10 @@ if ($massaction == 'transfer_request') $arrayofselected = is_array($toselect) ? $toselect : array(); $listofbills = array(); - foreach ($arrayofselected as $toselectid) - { + foreach ($arrayofselected as $toselectid) { $objecttmp = new FactureFournisseur($db); $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $totalpaye = $objecttmp->getSommePaiement(); $totalcreditnotes = $objecttmp->getSumCreditNotesUsed(); $totaldeposits = $objecttmp->getSumDepositsUsed(); @@ -405,16 +407,14 @@ if ($massaction == 'transfer_request') $rsql .= " ORDER BY pfd.date_demande DESC"; $result_sql = $db->query($rsql); - if ($result_sql) - { + if ($result_sql) { $numprlv = $db->num_rows($result_sql); } if ($numprlv > 0) { $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("RequestAlreadyDone"), $objecttmp->errors, 'warnings'); - } - elseif (!empty($objecttmp->mode_reglement_code) && $objecttmp->mode_reglement_code != 'VIR') { + } elseif (!empty($objecttmp->mode_reglement_code) && $objecttmp->mode_reglement_code != 'VIR') { $error++; setEventMessages($objecttmp->ref.' '.$langs->trans("BadPaymentMethod"), $objecttmp->errors, 'errors'); } else { @@ -460,7 +460,9 @@ $thirdparty = new Societe($db); // llxHeader('',$langs->trans("SuppliersInvoices"),'EN:Suppliers_Invoices|FR:FactureFournisseur|ES:Facturas_de_proveedores'); $sql = "SELECT"; -if ($search_all || $search_product_category > 0) $sql = 'SELECT DISTINCT'; +if ($search_all || $search_product_category > 0) { + $sql = 'SELECT DISTINCT'; +} $sql .= " f.rowid as facid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement as datelimite, f.fk_mode_reglement, f.fk_cond_reglement,"; $sql .= " f.total_ht, f.total_ttc, f.total_tva as total_vat, f.paye as paye, f.fk_statut as fk_statut, f.libelle as label, f.datec as date_creation, f.tms as date_update,"; $sql .= " f.localtax1 as total_localtax1, f.localtax2 as total_localtax2,"; @@ -475,11 +477,17 @@ $sql .= " p.rowid as project_id, p.ref as project_ref, p.title as project_label, $sql .= " u.login"; // We need dynamount_payed to be able to sort on status (value is surely wrong because we can count several lines several times due to other left join or link with contacts. But what we need is just 0 or > 0) // TODO Better solution to be able to sort on already payed or remain to pay is to store amount_payed in a denormalized field. -if (!$search_all) $sql .= ', SUM(pf.amount) as dynamount_payed'; -if ($search_categ_sup) $sql .= ", cs.fk_categorie, cs.fk_soc"; +if (!$search_all) { + $sql .= ', SUM(pf.amount) as dynamount_payed'; +} +if ($search_categ_sup) { + $sql .= ", cs.fk_categorie, cs.fk_soc"; +} // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key.' as options_'.$key : ''); + } } // Add fields from hooks $parameters = array(); @@ -489,86 +497,164 @@ $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; -if (!empty($search_categ_sup)) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs ON s.rowid = cs.fk_soc"; +if (!empty($search_categ_sup)) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_fournisseur as cs ON s.rowid = cs.fk_soc"; +} $sql .= ', '.MAIN_DB_PREFIX.'facture_fourn as f'; -if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; -if (!$search_all) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_facturefourn = f.rowid'; -if ($search_all || $search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn_det as pd ON f.rowid=pd.fk_facture_fourn'; -if ($search_product_category > 0) $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (f.rowid = ef.fk_object)"; +} +if (!$search_all) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf ON pf.fk_facturefourn = f.rowid'; +} +if ($search_all || $search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'facture_fourn_det as pd ON f.rowid=pd.fk_facture_fourn'; +} +if ($search_product_category > 0) { + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'categorie_product as cp ON cp.fk_product=pd.fk_product'; +} $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user AS u ON f.fk_user_author = u.rowid'; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = f.fk_projet"; // We'll need this table joined to the select in order to filter by sale -if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; -if ($search_user > 0) -{ +if ($search_sale > 0 || (!$user->rights->societe->client->voir && !$socid)) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} +if ($search_user > 0) { $sql .= ", ".MAIN_DB_PREFIX."element_contact as ec"; $sql .= ", ".MAIN_DB_PREFIX."c_type_contact as tc"; } $sql .= ' WHERE f.fk_soc = s.rowid'; $sql .= ' AND f.entity IN ('.getEntity('facture_fourn').')'; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($search_product_category > 0) $sql .= " AND cp.fk_categorie = ".$search_product_category; -if ($socid > 0) $sql .= ' AND s.rowid = '.$socid; -if ($search_ref) -{ - if (is_numeric($search_ref)) $sql .= natural_search(array('f.ref'), $search_ref); - else $sql .= natural_search('f.ref', $search_ref); +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; } -if ($search_ref) $sql .= natural_search('f.ref', $search_ref); -if ($search_refsupplier) $sql .= natural_search('f.ref_supplier', $search_refsupplier); -if ($search_type != '' && $search_type >= 0) -{ - if ($search_type == '0') $sql .= " AND f.type = 0"; // standard - if ($search_type == '1') $sql .= " AND f.type = 1"; // replacement - if ($search_type == '2') $sql .= " AND f.type = 2"; // credit note - if ($search_type == '3') $sql .= " AND f.type = 3"; // deposit +if ($search_product_category > 0) { + $sql .= " AND cp.fk_categorie = ".$search_product_category; +} +if ($socid > 0) { + $sql .= ' AND s.rowid = '.$socid; +} +if ($search_ref) { + if (is_numeric($search_ref)) { + $sql .= natural_search(array('f.ref'), $search_ref); + } else { + $sql .= natural_search('f.ref', $search_ref); + } +} +if ($search_ref) { + $sql .= natural_search('f.ref', $search_ref); +} +if ($search_refsupplier) { + $sql .= natural_search('f.ref_supplier', $search_refsupplier); +} +if ($search_type != '' && $search_type >= 0) { + if ($search_type == '0') { + $sql .= " AND f.type = 0"; // standard + } + if ($search_type == '1') { + $sql .= " AND f.type = 1"; // replacement + } + if ($search_type == '2') { + $sql .= " AND f.type = 2"; // credit note + } + if ($search_type == '3') { + $sql .= " AND f.type = 3"; // deposit + } //if ($search_type == '4') $sql.=" AND f.type = 4"; // proforma //if ($search_type == '5') $sql.=" AND f.type = 5"; // situation } -if ($search_project) $sql .= natural_search('p.ref', $search_project); -if ($search_company) $sql .= natural_search('s.nom', $search_company); -if ($search_town) $sql .= natural_search('s.town', $search_town); -if ($search_zip) $sql .= natural_search("s.zip", $search_zip); -if ($search_state) $sql .= natural_search("state.nom", $search_state); -if ($search_country) $sql .= " AND s.fk_pays IN (".$search_country.')'; -if ($search_type_thirdparty != '' && $search_type_thirdparty >= 0) $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; -if ($search_montant_ht != '') $sql .= natural_search('f.total_ht', $search_montant_ht, 1); -if ($search_montant_vat != '') $sql .= natural_search('f.total_tva', $search_montant_vat, 1); -if ($search_montant_localtax1 != '') $sql .= natural_search('f.localtax1', $search_montant_localtax1, 1); -if ($search_montant_localtax2 != '') $sql .= natural_search('f.localtax2', $search_montant_localtax2, 1); -if ($search_montant_ttc != '') $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1); -if ($search_multicurrency_code != '') $sql .= ' AND f.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; -if ($search_multicurrency_tx != '') $sql .= natural_search('f.multicurrency_tx', $search_multicurrency_tx, 1); -if ($search_multicurrency_montant_ht != '') $sql .= natural_search('f.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); -if ($search_multicurrency_montant_vat != '') $sql .= natural_search('f.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); -if ($search_multicurrency_montant_ttc != '') $sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); -if ($search_login) $sql .= natural_search('u.login', $search_login); -if ($search_status != '' && $search_status >= 0) $sql .= " AND f.fk_statut = ".$db->escape($search_status); -if ($search_paymentmode > 0) $sql .= " AND f.fk_mode_reglement = ".((int) $search_paymentmode); -if ($search_paymentcond > 0) $sql .= " AND f.fk_cond_reglement = ".((int) $search_paymentcond); +if ($search_project) { + $sql .= natural_search('p.ref', $search_project); +} +if ($search_company) { + $sql .= natural_search('s.nom', $search_company); +} +if ($search_town) { + $sql .= natural_search('s.town', $search_town); +} +if ($search_zip) { + $sql .= natural_search("s.zip", $search_zip); +} +if ($search_state) { + $sql .= natural_search("state.nom", $search_state); +} +if ($search_country) { + $sql .= " AND s.fk_pays IN (".$search_country.')'; +} +if ($search_type_thirdparty != '' && $search_type_thirdparty >= 0) { + $sql .= " AND s.fk_typent IN (".$search_type_thirdparty.')'; +} +if ($search_montant_ht != '') { + $sql .= natural_search('f.total_ht', $search_montant_ht, 1); +} +if ($search_montant_vat != '') { + $sql .= natural_search('f.total_tva', $search_montant_vat, 1); +} +if ($search_montant_localtax1 != '') { + $sql .= natural_search('f.localtax1', $search_montant_localtax1, 1); +} +if ($search_montant_localtax2 != '') { + $sql .= natural_search('f.localtax2', $search_montant_localtax2, 1); +} +if ($search_montant_ttc != '') { + $sql .= natural_search('f.total_ttc', $search_montant_ttc, 1); +} +if ($search_multicurrency_code != '') { + $sql .= ' AND f.multicurrency_code = "'.$db->escape($search_multicurrency_code).'"'; +} +if ($search_multicurrency_tx != '') { + $sql .= natural_search('f.multicurrency_tx', $search_multicurrency_tx, 1); +} +if ($search_multicurrency_montant_ht != '') { + $sql .= natural_search('f.multicurrency_total_ht', $search_multicurrency_montant_ht, 1); +} +if ($search_multicurrency_montant_vat != '') { + $sql .= natural_search('f.multicurrency_total_tva', $search_multicurrency_montant_vat, 1); +} +if ($search_multicurrency_montant_ttc != '') { + $sql .= natural_search('f.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); +} +if ($search_login) { + $sql .= natural_search('u.login', $search_login); +} +if ($search_status != '' && $search_status >= 0) { + $sql .= " AND f.fk_statut = ".$db->escape($search_status); +} +if ($search_paymentmode > 0) { + $sql .= " AND f.fk_mode_reglement = ".((int) $search_paymentmode); +} +if ($search_paymentcond > 0) { + $sql .= " AND f.fk_cond_reglement = ".((int) $search_paymentcond); +} $sql .= dolSqlDateFilter("f.datef", $day, $month, $year); $sql .= dolSqlDateFilter("f.date_lim_reglement", $day_lim, $month_lim, $year_lim); -if ($option == 'late') $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; -if ($search_label) $sql .= natural_search('f.libelle', $search_label); -if ($search_categ_sup > 0) $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_sup); -if ($search_categ_sup == -2) $sql .= " AND cs.fk_categorie IS NULL"; -if ($search_status != '' && $search_status >= 0) -{ +if ($option == 'late') { + $sql .= " AND f.date_lim_reglement < '".$db->idate(dol_now() - $conf->facture->fournisseur->warning_delay)."'"; +} +if ($search_label) { + $sql .= natural_search('f.libelle', $search_label); +} +if ($search_categ_sup > 0) { + $sql .= " AND cs.fk_categorie = ".$db->escape($search_categ_sup); +} +if ($search_categ_sup == -2) { + $sql .= " AND cs.fk_categorie IS NULL"; +} +if ($search_status != '' && $search_status >= 0) { $sql .= " AND f.fk_statut = ".$search_status; } -if ($filter && $filter != -1) -{ +if ($filter && $filter != -1) { $aFilter = explode(',', $filter); - foreach ($aFilter as $fil) - { + foreach ($aFilter as $fil) { $filt = explode(':', $fil); $sql .= ' AND '.$db->escape(trim($filt[0])).' = '.$db->escape(trim($filt[1])); } } -if ($search_sale > 0) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $search_sale); -if ($search_user > 0) -{ +if ($search_sale > 0) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $search_sale); +} +if ($search_user > 0) { $sql .= " AND ec.fk_c_type_contact = tc.rowid AND tc.element='invoice_supplier' AND tc.source='internal' AND ec.element_id = f.rowid AND ec.fk_socpeople = ".$search_user; } // Add where from extra fields @@ -578,8 +664,7 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -if (!$search_all) -{ +if (!$search_all) { $sql .= " GROUP BY f.rowid, f.ref, f.ref_supplier, f.type, f.datef, f.date_lim_reglement, f.fk_mode_reglement, f.fk_cond_reglement,"; $sql .= " f.total_ht, f.total_ttc, f.total_tva, f.paye, f.fk_statut, f.libelle, f.datec, f.tms,"; $sql .= " f.localtax1, f.localtax2,"; @@ -605,12 +690,10 @@ if (!$search_all) $sql .= $db->order($sortfield, $sortorder); $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -620,14 +703,12 @@ $sql .= $db->plimit($limit + 1, $offset); //print $sql; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); - if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) - { + if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $sall) { $obj = $db->fetch_object($resql); $id = $obj->facid; @@ -637,47 +718,114 @@ if ($resql) llxHeader('', $langs->trans("SuppliersInvoices"), 'EN:Suppliers_Invoices|FR:FactureFournisseur|ES:Facturas_de_proveedores'); - if ($socid) - { + if ($socid) { $soc = new Societe($db); $soc->fetch($socid); - if (empty($search_company)) $search_company = $soc->name; + if (empty($search_company)) { + $search_company = $soc->name; + } } $param = '&socid='.$socid; - if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage); - if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit); - if ($search_all) $param .= '&search_all='.urlencode($search_all); - if ($day) $param .= '&day='.urlencode($day); - if ($month) $param .= '&month='.urlencode($month); - if ($year) $param .= '&year='.urlencode($year); - if ($day_lim) $param .= '&day_lim='.urlencode($day_lim); - if ($month_lim) $param .= '&month_lim='.urlencode($month_lim); - if ($year_lim) $param .= '&year_lim='.urlencode($year_lim); - if ($search_ref) $param .= '&search_ref='.urlencode($search_ref); - if ($search_refsupplier) $param .= '&search_refsupplier='.urlencode($search_refsupplier); - if ($search_type != '') $param .= '&search_type='.urlencode($search_type); - if ($search_label) $param .= '&search_label='.urlencode($search_label); - if ($search_company) $param .= '&search_company='.urlencode($search_company); - if ($search_login) $param .= '&search_login='.urlencode($search_login); - if ($search_montant_ht != '') $param .= '&search_montant_ht='.urlencode($search_montant_ht); - if ($search_montant_vat != '') $param .= '&search_montant_vat='.urlencode($search_montant_vat); - if ($search_montant_localtax1 != '') $param .= '&search_montant_localtax1='.urlencode($search_montant_localtax1); - if ($search_montant_localtax2 != '') $param .= '&search_montant_localtax2='.urlencode($search_montant_localtax2); - if ($search_montant_ttc != '') $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); - if ($search_multicurrency_code != '') $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); - if ($search_multicurrency_tx != '') $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); - if ($search_multicurrency_montant_ht != '') $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); - if ($search_multicurrency_montant_vat != '') $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); - if ($search_multicurrency_montant_ttc != '') $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); - if ($search_amount_no_tax) $param .= '&search_amount_no_tax='.urlencode($search_amount_no_tax); - if ($search_amount_all_tax) $param .= '&search_amount_all_tax='.urlencode($search_amount_all_tax); - if ($search_status >= 0) $param .= "&search_status=".urlencode($search_status); - if ($show_files) $param .= '&show_files='.urlencode($show_files); - if ($option) $param .= "&option=".urlencode($option); - if ($optioncss != '') $param .= '&optioncss='.urlencode($optioncss); - if ($search_categ_sup > 0) $param .= '&search_categ_sup='.urlencode($search_categ_sup); - if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); + } + if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.urlencode($limit); + } + if ($search_all) { + $param .= '&search_all='.urlencode($search_all); + } + if ($day) { + $param .= '&day='.urlencode($day); + } + if ($month) { + $param .= '&month='.urlencode($month); + } + if ($year) { + $param .= '&year='.urlencode($year); + } + if ($day_lim) { + $param .= '&day_lim='.urlencode($day_lim); + } + if ($month_lim) { + $param .= '&month_lim='.urlencode($month_lim); + } + if ($year_lim) { + $param .= '&year_lim='.urlencode($year_lim); + } + if ($search_ref) { + $param .= '&search_ref='.urlencode($search_ref); + } + if ($search_refsupplier) { + $param .= '&search_refsupplier='.urlencode($search_refsupplier); + } + if ($search_type != '') { + $param .= '&search_type='.urlencode($search_type); + } + if ($search_label) { + $param .= '&search_label='.urlencode($search_label); + } + if ($search_company) { + $param .= '&search_company='.urlencode($search_company); + } + if ($search_login) { + $param .= '&search_login='.urlencode($search_login); + } + if ($search_montant_ht != '') { + $param .= '&search_montant_ht='.urlencode($search_montant_ht); + } + if ($search_montant_vat != '') { + $param .= '&search_montant_vat='.urlencode($search_montant_vat); + } + if ($search_montant_localtax1 != '') { + $param .= '&search_montant_localtax1='.urlencode($search_montant_localtax1); + } + if ($search_montant_localtax2 != '') { + $param .= '&search_montant_localtax2='.urlencode($search_montant_localtax2); + } + if ($search_montant_ttc != '') { + $param .= '&search_montant_ttc='.urlencode($search_montant_ttc); + } + if ($search_multicurrency_code != '') { + $param .= '&search_multicurrency_code='.urlencode($search_multicurrency_code); + } + if ($search_multicurrency_tx != '') { + $param .= '&search_multicurrency_tx='.urlencode($search_multicurrency_tx); + } + if ($search_multicurrency_montant_ht != '') { + $param .= '&search_multicurrency_montant_ht='.urlencode($search_multicurrency_montant_ht); + } + if ($search_multicurrency_montant_vat != '') { + $param .= '&search_multicurrency_montant_vat='.urlencode($search_multicurrency_montant_vat); + } + if ($search_multicurrency_montant_ttc != '') { + $param .= '&search_multicurrency_montant_ttc='.urlencode($search_multicurrency_montant_ttc); + } + if ($search_amount_no_tax) { + $param .= '&search_amount_no_tax='.urlencode($search_amount_no_tax); + } + if ($search_amount_all_tax) { + $param .= '&search_amount_all_tax='.urlencode($search_amount_all_tax); + } + if ($search_status >= 0) { + $param .= "&search_status=".urlencode($search_status); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); + } + if ($option) { + $param .= "&option=".urlencode($option); + } + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_categ_sup > 0) { + $param .= '&search_categ_sup='.urlencode($search_categ_sup); + } + if ($search_type_thirdparty != '' && $search_type_thirdparty > 0) { + $param .= '&search_type_thirdparty='.urlencode($search_type_thirdparty); + } // Add $param from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; @@ -690,25 +838,33 @@ if ($resql) //'presend'=>$langs->trans("SendByMail"), ); if ($conf->paymentbybanktransfer->enabled) { - $langs->load("withdrawals"); - $arrayofmassactions['transfer_request'] = $langs->trans("MakeBankTransferOrder"); + $langs->load("withdrawals"); + $arrayofmassactions['transfer_request'] = $langs->trans("MakeBankTransferOrder"); } //if($user->rights->fournisseur->facture->creer) $arrayofmassactions['createbills']=$langs->trans("CreateInvoiceForThisCustomer"); if (!empty($conf->paymentbybanktransfer->enabled) && !empty($user->rights->paymentbybanktransfer->create)) { $langs->load('withdrawals'); $arrayofmassactions['banktransfertrequest'] = $langs->trans("MakeBankTransferOrder"); } - if ($user->rights->fournisseur->facture->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (in_array($massaction, array('presend', 'predelete', 'createbills'))) $arrayofmassactions = array(); + if ($user->rights->fournisseur->facture->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (in_array($massaction, array('presend', 'predelete', 'createbills'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $url = DOL_URL_ROOT.'/fourn/facture/card.php?action=create'; - if (!empty($socid)) $url .= '&socid='.$socid; + if (!empty($socid)) { + $url .= '&socid='.$socid; + } $newcardbutton = dolGetButtonTitle($langs->trans('NewBill'), '', 'fa fa-plus-circle', $url, '', $user->rights->fournisseur->facture->creer); $i = 0; print '<form method="POST" name="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n"; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; print '<input type="hidden" name="action" value="list">'; @@ -724,8 +880,7 @@ if ($resql) $trackid = 'sinv'.$object->id; include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; - if ($massaction == 'createbills') - { + if ($massaction == 'createbills') { //var_dump($_REQUEST); print '<input type="hidden" name="massaction" value="confirm_createbills">'; @@ -764,33 +919,31 @@ if ($resql) print '<br>'; } - if ($search_all) - { - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); + if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } - // If the user can view prospects other than his' - $moreforfilter = ''; - if ($user->rights->societe->client->voir || $socid) - { - $langs->load("commercial"); - $moreforfilter .= '<div class="divsearchfield">'; - $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; - $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); - $moreforfilter .= '</div>'; - } // If the user can view prospects other than his' - if ($user->rights->societe->client->voir || $socid) - { + $moreforfilter = ''; + if ($user->rights->societe->client->voir || $socid) { + $langs->load("commercial"); + $moreforfilter .= '<div class="divsearchfield">'; + $moreforfilter .= $langs->trans('ThirdPartiesOfSaleRepresentative').': '; + $moreforfilter .= $formother->select_salesrepresentatives($search_sale, 'search_sale', $user, 0, 1, 'maxwidth200'); + $moreforfilter .= '</div>'; + } + // If the user can view prospects other than his' + if ($user->rights->societe->client->voir || $socid) { $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('LinkedToSpecificUsers').': '; $moreforfilter .= $form->select_dolusers($search_user, 'search_user', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - $moreforfilter .= '</div>'; + $moreforfilter .= '</div>'; } // If the user can view prospects other than his' - if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) - { + if (!empty($conf->categorie->enabled) && $user->rights->categorie->lire && ($user->rights->produit->lire || $user->rights->service->lire)) { include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('IncludingProductWithTag').': '; @@ -799,8 +952,7 @@ if ($resql) $moreforfilter .= '</div>'; } - if (!empty($conf->categorie->enabled)) - { + if (!empty($conf->categorie->enabled)) { require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $moreforfilter .= '<div class="divsearchfield">'; $moreforfilter .= $langs->trans('SuppliersCategoriesShort').': '; @@ -809,19 +961,23 @@ if ($resql) } $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 (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; + } else { + $moreforfilter = $hookmanager->resPrint; + } - if ($moreforfilter) - { - print '<div class="liste_titre liste_titre_bydiv centpercent">'; + if ($moreforfilter) { + print '<div class="liste_titre liste_titre_bydiv centpercent">'; print $moreforfilter; print '</div>'; } $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); + if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); + } print '<div class="div-table-responsive">'; print '<table class="tagtable liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n"; @@ -829,22 +985,19 @@ if ($resql) // Line for filters print '<tr class="liste_titre_filter">'; // Ref - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print '<td class="liste_titre left">'; print '<input class="flat maxwidth50" type="text" name="search_ref" value="'.$search_ref.'">'; print '</td>'; } // Ref supplier - if (!empty($arrayfields['f.ref_supplier']['checked'])) - { + if (!empty($arrayfields['f.ref_supplier']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat maxwidth50" type="text" name="search_refsupplier" value="'.$search_refsupplier.'">'; print '</td>'; } // Type - if (!empty($arrayfields['f.type']['checked'])) - { + if (!empty($arrayfields['f.type']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone">'; $listtype = array( FactureFournisseur::TYPE_STANDARD=>$langs->trans("InvoiceStandard"), @@ -857,180 +1010,163 @@ if ($resql) { $listtype[Facture::TYPE_SITUATION] = $langs->trans("InvoiceSituation"); } - */ + */ //$listtype[Facture::TYPE_PROFORMA]=$langs->trans("InvoiceProForma"); // A proformat invoice is not an invoice but must be an order. print $form->selectarray('search_type', $listtype, $search_type, 1, 0, 0, '', 0, 0, 0, 'ASC', 'maxwidth100'); print '</td>'; } // Label - if (!empty($arrayfields['f.label']['checked'])) - { + if (!empty($arrayfields['f.label']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat maxwidth75" type="text" name="search_label" value="'.$search_label.'">'; print '</td>'; } // Date invoice - if (!empty($arrayfields['f.datef']['checked'])) - { + if (!empty($arrayfields['f.datef']['checked'])) { print '<td class="liste_titre nowraponall center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day" value="'.dol_escape_htmltag($day).'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day" value="'.dol_escape_htmltag($day).'">'; + } print '<input class="flat width25 valignmiddle" type="text" size="1" maxlength="2" name="month" value="'.$month.'">'; $formother->select_year($year ? $year : -1, 'year', 1, 20, 5); print '</td>'; } // Date due - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) - { + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { print '<td class="liste_titre nowraponall center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day_lim" value="'.dol_escape_htmltag($day_lim).'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="day_lim" value="'.dol_escape_htmltag($day_lim).'">'; + } print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="month_lim" value="'.$month_lim.'">'; $formother->select_year($year_lim ? $year_lim : -1, 'year_lim', 1, 20, 5); print '<br><input type="checkbox" name="option" value="late"'.($option == 'late' ? ' checked' : '').'> '.$langs->trans("Late"); print '</td>'; } // Project - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_project" value="'.$search_project.'"></td>'; } // Thirpdarty - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_company" value="'.$search_company.'"></td>'; } // Town - if (!empty($arrayfields['s.town']['checked'])) print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'"></td>'; + if (!empty($arrayfields['s.town']['checked'])) { + print '<td class="liste_titre"><input class="flat maxwidth50" type="text" name="search_town" value="'.dol_escape_htmltag($search_town).'"></td>'; + } // Zip - if (!empty($arrayfields['s.zip']['checked'])) print '<td class="liste_titre center"><input class="flat maxwidth50" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'"></td>'; + if (!empty($arrayfields['s.zip']['checked'])) { + print '<td class="liste_titre center"><input class="flat maxwidth50" type="text" name="search_zip" value="'.dol_escape_htmltag($search_zip).'"></td>'; + } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print '<td class="liste_titre">'; print '<input class="flat" size="4" type="text" name="search_state" value="'.dol_escape_htmltag($search_state).'">'; print '</td>'; } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="liste_titre center">'; print $form->select_country($search_country, 'search_country', '', 0, 'minwidth100imp maxwidth100'); print '</td>'; } // Company type - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone center">'; print $form->selectarray("search_type_thirdparty", $formcompany->typent_array(0), $search_type_thirdparty, 1, 0, 0, '', 0, 0, 0, (empty($conf->global->SOCIETE_SORT_ON_TYPEENT) ? 'ASC' : $conf->global->SOCIETE_SORT_ON_TYPEENT), '', 1); print '</td>'; } // Condition of payment - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { print '<td class="liste_titre left">'; $form->select_conditions_paiements($search_paymentcond, 'search_paymentcond', -1, 1, 1, 'maxwidth100'); print '</td>'; } // Payment mode - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { print '<td class="liste_titre left">'; $form->select_types_paiements($search_paymentmode, 'search_paymentmode', '', 0, 1, 1, 20, 1, 'maxwidth100'); print '</td>'; } - if (!empty($arrayfields['f.total_ht']['checked'])) - { + if (!empty($arrayfields['f.total_ht']['checked'])) { // Amount without tax print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_ht" value="'.dol_escape_htmltag($search_montant_ht).'">'; print '</td>'; } - if (!empty($arrayfields['f.total_vat']['checked'])) - { + if (!empty($arrayfields['f.total_vat']['checked'])) { // Amount vat print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_vat" value="'.dol_escape_htmltag($search_montant_vat).'">'; print '</td>'; } - if (!empty($arrayfields['f.total_localtax1']['checked'])) - { + if (!empty($arrayfields['f.total_localtax1']['checked'])) { // Amount tax 1 print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_localtax1" value="'.$search_montant_localtax1.'">'; print '</td>'; } - if (!empty($arrayfields['f.total_localtax2']['checked'])) - { + if (!empty($arrayfields['f.total_localtax2']['checked'])) { // Amount tax 2 - print '<td class="liste_titre right">'; + print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_localtax2" value="'.$search_montant_localtax2.'">'; print '</td>'; } - if (!empty($arrayfields['f.total_ttc']['checked'])) - { + if (!empty($arrayfields['f.total_ttc']['checked'])) { // Amount inc tac print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="5" name="search_montant_ttc" value="'.dol_escape_htmltag($search_montant_ttc).'">'; print '</td>'; } - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { // Author print '<td class="liste_titre" align="center">'; print '<input class="flat" size="4" type="text" name="search_login" value="'.dol_escape_htmltag($search_login).'">'; print '</td>'; } - if (!empty($arrayfields['dynamount_payed']['checked'])) - { + if (!empty($arrayfields['dynamount_payed']['checked'])) { print '<td class="liste_titre right">'; print '</td>'; } - if (!empty($arrayfields['rtp']['checked'])) - { + if (!empty($arrayfields['rtp']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['f.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_code']['checked'])) { // Currency print '<td class="liste_titre">'; print $form->selectMultiCurrency($search_multicurrency_code, 'search_multicurrency_code', 1); print '</td>'; } - if (!empty($arrayfields['f.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { // Currency rate print '<td class="liste_titre">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_tx" value="'.dol_escape_htmltag($search_multicurrency_tx).'">'; print '</td>'; } - if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ht" value="'.dol_escape_htmltag($search_multicurrency_montant_ht).'">'; print '</td>'; } - if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_vat" value="'.dol_escape_htmltag($search_multicurrency_montant_vat).'">'; print '</td>'; } - if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { // Amount print '<td class="liste_titre right">'; print '<input class="flat" type="text" size="4" name="search_multicurrency_montant_ttc" value="'.dol_escape_htmltag($search_multicurrency_montant_ttc).'">'; print '</td>'; } - if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) - { + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } - if (!empty($arrayfields['multicurrency_rtp']['checked'])) - { + if (!empty($arrayfields['multicurrency_rtp']['checked'])) { print '<td class="liste_titre right">'; print '</td>'; } @@ -1042,20 +1178,17 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListOption', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Date modification - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print '<td class="liste_titre">'; print '</td>'; } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '<td class="liste_titre maxwidthonsmartphone right">'; $liststatus = array('0'=>$langs->trans("Draft"), '1'=>$langs->trans("Unpaid"), '2'=>$langs->trans("Paid")); print $form->selectarray('search_status', $liststatus, $search_status, 1, 0, 0, '', 0, 0, 0, '', '', 1); @@ -1070,45 +1203,111 @@ if ($resql) print "</tr>\n"; print '<tr class="liste_titre">'; - if (!empty($arrayfields['f.ref']['checked'])) print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref,f.rowid', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.ref_supplier']['checked'])) print_liste_field_titre($arrayfields['f.ref_supplier']['label'], $_SERVER["PHP_SELF"], 'f.ref_supplier', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.type']['checked'])) print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.label']['checked'])) print_liste_field_titre($arrayfields['f.label']['label'], $_SERVER['PHP_SELF'], "f.libelle,f.rowid", '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.datef']['checked'])) print_liste_field_titre($arrayfields['f.datef']['label'], $_SERVER['PHP_SELF'], 'f.datef,f.rowid', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['p.ref']['checked'])) print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.nom']['checked'])) print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.town']['checked'])) print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['s.zip']['checked'])) print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['state.nom']['checked'])) print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['country.code_iso']['checked'])) print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['typent.code']['checked'])) print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder); - if (!empty($arrayfields['f.total_ht']['checked'])) print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.total_vat']['checked'])) print_liste_field_titre($arrayfields['f.total_vat']['label'], $_SERVER['PHP_SELF'], 'f.tva', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.total_localtax1']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.total_localtax2']['checked'])) print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['u.login']['checked'])) print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); - if (!empty($arrayfields['dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['rtp']['checked'])) print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); - if (!empty($arrayfields['f.multicurrency_code']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_code', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_tx']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_tx', '', $param, '', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) print_liste_field_titre($arrayfields['f.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) print_liste_field_titre($arrayfields['multicurrency_dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); - if (!empty($arrayfields['multicurrency_rtp']['checked'])) print_liste_field_titre($arrayfields['multicurrency_rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + if (!empty($arrayfields['f.ref']['checked'])) { + print_liste_field_titre($arrayfields['f.ref']['label'], $_SERVER['PHP_SELF'], 'f.ref,f.rowid', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.ref_supplier']['checked'])) { + print_liste_field_titre($arrayfields['f.ref_supplier']['label'], $_SERVER["PHP_SELF"], 'f.ref_supplier', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.type']['checked'])) { + print_liste_field_titre($arrayfields['f.type']['label'], $_SERVER["PHP_SELF"], 'f.type', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.label']['checked'])) { + print_liste_field_titre($arrayfields['f.label']['label'], $_SERVER['PHP_SELF'], "f.libelle,f.rowid", '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.datef']['checked'])) { + print_liste_field_titre($arrayfields['f.datef']['label'], $_SERVER['PHP_SELF'], 'f.datef,f.rowid', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.date_lim_reglement']['label'], $_SERVER['PHP_SELF'], "f.date_lim_reglement", '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['p.ref']['checked'])) { + print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.nom']['checked'])) { + print_liste_field_titre($arrayfields['s.nom']['label'], $_SERVER['PHP_SELF'], 's.nom', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.town']['checked'])) { + print_liste_field_titre($arrayfields['s.town']['label'], $_SERVER["PHP_SELF"], 's.town', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['s.zip']['checked'])) { + print_liste_field_titre($arrayfields['s.zip']['label'], $_SERVER["PHP_SELF"], 's.zip', '', $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['state.nom']['checked'])) { + print_liste_field_titre($arrayfields['state.nom']['label'], $_SERVER["PHP_SELF"], "state.nom", "", $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['country.code_iso']['checked'])) { + print_liste_field_titre($arrayfields['country.code_iso']['label'], $_SERVER["PHP_SELF"], "country.code_iso", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['typent.code']['checked'])) { + print_liste_field_titre($arrayfields['typent.code']['label'], $_SERVER["PHP_SELF"], "typent.code", "", $param, '', $sortfield, $sortorder, 'center '); + } + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_cond_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_cond_reglement", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_mode_reglement']['label'], $_SERVER["PHP_SELF"], "f.fk_mode_reglement", "", $param, "", $sortfield, $sortorder); + } + if (!empty($arrayfields['f.total_ht']['checked'])) { + print_liste_field_titre($arrayfields['f.total_ht']['label'], $_SERVER['PHP_SELF'], 'f.total_ht', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.total_vat']['checked'])) { + print_liste_field_titre($arrayfields['f.total_vat']['label'], $_SERVER['PHP_SELF'], 'f.tva', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.total_localtax1']['checked'])) { + print_liste_field_titre($arrayfields['f.total_localtax1']['label'], $_SERVER['PHP_SELF'], 'f.localtax1', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.total_localtax2']['checked'])) { + print_liste_field_titre($arrayfields['f.total_localtax2']['label'], $_SERVER['PHP_SELF'], 'f.localtax2', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['f.total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.total_ttc', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['u.login']['checked'])) { + print_liste_field_titre($arrayfields['u.login']['label'], $_SERVER["PHP_SELF"], 'u.login', '', $param, 'align="center"', $sortfield, $sortorder); + } + if (!empty($arrayfields['dynamount_payed']['checked'])) { + print_liste_field_titre($arrayfields['dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['rtp']['checked'])) { + print_liste_field_titre($arrayfields['rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'right '); + } + if (!empty($arrayfields['f.multicurrency_code']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_code']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_code', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_tx']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_tx', '', $param, '', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_total_ht']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ht', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_total_vat']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_tva', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { + print_liste_field_titre($arrayfields['f.multicurrency_total_ttc']['label'], $_SERVER['PHP_SELF'], 'f.multicurrency_total_ttc', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { + print_liste_field_titre($arrayfields['multicurrency_dynamount_payed']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } + if (!empty($arrayfields['multicurrency_rtp']['checked'])) { + print_liste_field_titre($arrayfields['multicurrency_rtp']['label'], $_SERVER['PHP_SELF'], '', '', $param, 'class="right"', $sortfield, $sortorder); + } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; - if (!empty($arrayfields['f.datec']['checked'])) print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.tms']['checked'])) print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); - if (!empty($arrayfields['f.fk_statut']['checked'])) print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "fk_statut,paye,type", "", $param, '', $sortfield, $sortorder, 'right '); + if (!empty($arrayfields['f.datec']['checked'])) { + print_liste_field_titre($arrayfields['f.datec']['label'], $_SERVER["PHP_SELF"], "f.datec", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.tms']['checked'])) { + print_liste_field_titre($arrayfields['f.tms']['label'], $_SERVER["PHP_SELF"], "f.tms", "", $param, '', $sortfield, $sortorder, 'center nowrap '); + } + if (!empty($arrayfields['f.fk_statut']['checked'])) { + print_liste_field_titre($arrayfields['f.fk_statut']['label'], $_SERVER["PHP_SELF"], "fk_statut,paye,type", "", $param, '', $sortfield, $sortorder, 'right '); + } print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'center maxwidthsearch '); print "</tr>\n"; @@ -1117,12 +1316,10 @@ if ($resql) $projectstatic = new Project($db); $userstatic = new User($db); - if ($num > 0) - { + if ($num > 0) { $i = 0; $totalarray = array(); - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); $datelimit = $db->jdate($obj->datelimite); @@ -1176,8 +1373,7 @@ if ($resql) } print '<tr class="oddeven">'; - if (!empty($arrayfields['f.ref']['checked'])) - { + if (!empty($arrayfields['f.ref']['checked'])) { print '<td class="nowrap">'; print '<table class="nobordernopadding"><tr class="nocellnopadd">'; @@ -1192,253 +1388,301 @@ if ($resql) print '</td></tr></table>'; print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Supplier ref - if (!empty($arrayfields['f.ref_supplier']['checked'])) - { + if (!empty($arrayfields['f.ref_supplier']['checked'])) { print '<td class="nowrap tdoverflowmax200">'; print $obj->ref_supplier; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type - if (!empty($arrayfields['f.type']['checked'])) - { + if (!empty($arrayfields['f.type']['checked'])) { print '<td class="nowrap">'; print $facturestatic->getLibType(); print "</td>"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Label - if (!empty($arrayfields['f.label']['checked'])) - { + if (!empty($arrayfields['f.label']['checked'])) { print '<td class="nowrap">'; print $obj->label; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date - if (!empty($arrayfields['f.datef']['checked'])) - { + if (!empty($arrayfields['f.datef']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->datef), 'day'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date limit - if (!empty($arrayfields['f.date_lim_reglement']['checked'])) - { + if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { print '<td class="center nowrap">'.dol_print_date($datelimit, 'day'); - if ($facturestatic->hasDelay()) - { + if ($facturestatic->hasDelay()) { print img_warning($langs->trans('Late')); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Project - if (!empty($arrayfields['p.ref']['checked'])) - { + if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="nowrap">'; - if ($obj->project_id > 0) - { + if ($obj->project_id > 0) { $projectstatic->id = $obj->project_id; $projectstatic->ref = $obj->project_ref; $projectstatic->title = $obj->project_label; print $projectstatic->getNomUrl(1); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Third party - if (!empty($arrayfields['s.nom']['checked'])) - { + if (!empty($arrayfields['s.nom']['checked'])) { print '<td class="tdoverflowmax200">'; print $thirdparty->getNomUrl(1, 'supplier'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Town - if (!empty($arrayfields['s.town']['checked'])) - { + if (!empty($arrayfields['s.town']['checked'])) { print '<td class="nocellnopadd">'; print $obj->town; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Zip - if (!empty($arrayfields['s.zip']['checked'])) - { + if (!empty($arrayfields['s.zip']['checked'])) { print '<td class="nocellnopadd center">'; print $obj->zip; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // State - if (!empty($arrayfields['state.nom']['checked'])) - { + if (!empty($arrayfields['state.nom']['checked'])) { print "<td>".$obj->state_name."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Country - if (!empty($arrayfields['country.code_iso']['checked'])) - { + if (!empty($arrayfields['country.code_iso']['checked'])) { print '<td class="center">'; $tmparray = getCountry($obj->fk_pays, 'all'); print $tmparray['label']; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Type ent - if (!empty($arrayfields['typent.code']['checked'])) - { + if (!empty($arrayfields['typent.code']['checked'])) { print '<td class="center">'; - if (empty($typenArray)) $typenArray = $formcompany->typent_array(1); + if (empty($typenArray)) { + $typenArray = $formcompany->typent_array(1); + } print $typenArray[$obj->typent_code]; print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment condition - if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_cond_reglement']['checked'])) { print '<td>'; $form->form_conditions_reglement($_SERVER['PHP_SELF'], $obj->fk_cond_reglement, 'none', '', -1); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Payment mode - if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) - { + if (!empty($arrayfields['f.fk_mode_reglement']['checked'])) { print '<td>'; $form->form_modes_reglement($_SERVER['PHP_SELF'], $obj->fk_mode_reglement, 'none', '', -1); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['f.total_ht']['checked'])) - { + if (!empty($arrayfields['f.total_ht']['checked'])) { print '<td class="right nowrap">'.price($obj->total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ht'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ht'; + } $totalarray['val']['f.total_ht'] += $obj->total_ht; } // Amount VAT - if (!empty($arrayfields['f.total_vat']['checked'])) - { + if (!empty($arrayfields['f.total_vat']['checked'])) { print '<td class="right nowrap">'.price($obj->total_vat)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_vat'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_vat'; + } $totalarray['val']['f.total_vat'] += $obj->total_vat; } // Amount LocalTax1 - if (!empty($arrayfields['f.total_localtax1']['checked'])) - { + if (!empty($arrayfields['f.total_localtax1']['checked'])) { print '<td class="right nowrap">'.price($obj->total_localtax1)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax1'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax1'; + } $totalarray['val']['f.total_localtax1'] += $obj->total_localtax1; } // Amount LocalTax2 - if (!empty($arrayfields['f.total_localtax2']['checked'])) - { + if (!empty($arrayfields['f.total_localtax2']['checked'])) { print '<td class="right nowrap">'.price($obj->total_localtax2)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax2'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_localtax2'; + } $totalarray['val']['f.total_localtax2'] += $obj->total_localtax2; } // Amount TTC - if (!empty($arrayfields['f.total_ttc']['checked'])) - { + if (!empty($arrayfields['f.total_ttc']['checked'])) { print '<td class="right nowrap">'.price($obj->total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'f.total_ttc'; + } $totalarray['val']['f.total_ttc'] += $obj->total_ttc; } // Author - if (!empty($arrayfields['u.login']['checked'])) - { + if (!empty($arrayfields['u.login']['checked'])) { $userstatic->id = $obj->fk_user_author; $userstatic->login = $obj->login; print '<td align="center">'; - if ($userstatic->id) print $userstatic->getLoginUrl(1); - else print '&nbsp;'; + if ($userstatic->id) { + print $userstatic->getLoginUrl(1); + } else { + print '&nbsp;'; + } print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['dynamount_payed']['checked'])) - { + if (!empty($arrayfields['dynamount_payed']['checked'])) { print '<td class="right nowrap">'.(!empty($totalpay) ?price($totalpay, 0, $langs) : '&nbsp;').'</td>'; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'totalam'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'totalam'; + } $totalarray['val']['totalam'] += $totalpay; } - if (!empty($arrayfields['rtp']['checked'])) - { + if (!empty($arrayfields['rtp']['checked'])) { print '<td class="right nowrap">'.(!empty($remaintopay) ?price($remaintopay, 0, $langs) : '&nbsp;').'</td>'; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; - if (!$i) $totalarray['pos'][$totalarray['nbfield']] = 'rtp'; + if (!$i) { + $totalarray['nbfield']++; + } + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 'rtp'; + } $totalarray['val']['rtp'] += $remaintopay; } // Currency - if (!empty($arrayfields['f.multicurrency_code']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_code']['checked'])) { print '<td class="nowrap">'.$obj->multicurrency_code.' - '.$langs->trans('Currency'.$obj->multicurrency_code)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Currency rate - if (!empty($arrayfields['f.multicurrency_tx']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_tx']['checked'])) { print '<td class="nowrap">'; $form->form_multicurrency_rate($_SERVER['PHP_SELF'].'?id='.$obj->rowid, $obj->multicurrency_tx, 'none', $obj->multicurrency_code); print "</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount HT - if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ht']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ht)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount VAT - if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_vat']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_vat)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount TTC - if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) - { + if (!empty($arrayfields['f.multicurrency_total_ttc']['checked'])) { print '<td class="right nowrap">'.price($obj->multicurrency_total_ttc)."</td>\n"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } - if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) - { + if (!empty($arrayfields['multicurrency_dynamount_payed']['checked'])) { print '<td class="right nowrap">'.(!empty($multicurrency_totalpay) ?price($multicurrency_totalpay, 0, $langs) : '&nbsp;').'</td>'; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Pending amount - if (!empty($arrayfields['multicurrency_rtp']['checked'])) - { + if (!empty($arrayfields['multicurrency_rtp']['checked'])) { print '<td class="right nowrap">'; print (!empty($multicurrency_remaintopay) ? price($multicurrency_remaintopay, 0, $langs) : '&nbsp;'); print '</td>'; // TODO Use a denormalized field - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } @@ -1449,40 +1693,46 @@ if ($resql) $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; // Date creation - if (!empty($arrayfields['f.datec']['checked'])) - { + if (!empty($arrayfields['f.datec']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_creation), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date modification - if (!empty($arrayfields['f.tms']['checked'])) - { + if (!empty($arrayfields['f.tms']['checked'])) { print '<td class="center nowrap">'; print dol_print_date($db->jdate($obj->date_update), 'dayhour', 'tzuser'); print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Status - if (!empty($arrayfields['f.fk_statut']['checked'])) - { + if (!empty($arrayfields['f.fk_statut']['checked'])) { print '<td class="right nowrap">'; print $facturestatic->LibStatut($obj->paye, $obj->fk_statut, 5, $paiement, $obj->type); print "</td>"; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Action column print '<td class="nowrap center">'; - if ($massactionbutton || $massaction) // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined - { + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; - if (in_array($obj->facid, $arrayofselected)) $selected = 1; + if (in_array($obj->facid, $arrayofselected)) { + $selected = 1; + } print '<input id="cb'.$obj->facid.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$obj->facid.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print "</tr>\n"; @@ -1505,7 +1755,9 @@ if ($resql) print "</form>\n"; $hidegeneratedfilelistifempty = 1; - if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) $hidegeneratedfilelistifempty = 0; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } // Show list of available documents $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; diff --git a/htdocs/fourn/facture/note.php b/htdocs/fourn/facture/note.php index c98ad3ba1d8..541121031ee 100644 --- a/htdocs/fourn/facture/note.php +++ b/htdocs/fourn/facture/note.php @@ -40,7 +40,9 @@ $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'aZ09'); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); $object = new FactureFournisseur($db); @@ -56,11 +58,12 @@ $permissionnote = $user->rights->fournisseur->facture->creer; // Used by the inc include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be include, not includ_once // Set label -if ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) -{ +if ($action == 'setlabel' && $user->rights->fournisseur->facture->creer) { $object->label = $_POST['label']; $result = $object->update($user); - if ($result < 0) dol_print_error($db); + if ($result < 0) { + dol_print_error($db); + } } @@ -74,8 +77,7 @@ $title = $langs->trans('SupplierInvoice')." - ".$langs->trans('Notes'); $helpurl = "EN:Module_Suppliers_Invoices|FR:Module_Fournisseurs_Factures|ES:Módulo_Facturas_de_proveedores"; llxHeader('', $title, $helpurl); -if ($object->id > 0) -{ +if ($object->id > 0) { $object->fetch_thirdparty(); $alreadypaid = $object->getSommePaiement(); @@ -94,14 +96,14 @@ if ($object->id > 0) $morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1); // Thirdparty $morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1); - if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) { + $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)'; + } // Project - if (!empty($conf->projet->enabled)) - { + if (!empty($conf->projet->enabled)) { $langs->load("projects"); $morehtmlref .= '<br>'.$langs->trans('Project').' '; - if ($user->rights->fournisseur->commande->creer) - { + if ($user->rights->fournisseur->commande->creer) { if ($action != 'classify') { // $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; $morehtmlref .= ' : '; @@ -143,36 +145,34 @@ if ($object->id > 0) // Type print '<tr><td class="titlefield">'.$langs->trans('Type').'</td><td>'; print $object->getLibType(); - if ($object->type == FactureFournisseur::TYPE_REPLACEMENT) - { + 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) - { + 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) - { + if (count($facidavoir) > 0) { print ' ('.$langs->transnoentities("InvoiceHasAvoir"); $i = 0; - foreach ($facidavoir as $fid) - { - if ($i == 0) print ' '; - else print ','; + foreach ($facidavoir as $fid) { + if ($i == 0) { + print ' '; + } else { + print ','; + } $facavoir = new FactureFournisseur($db); $facavoir->fetch($fid); print $facavoir->getNomUrl(1); } print ')'; } - if ($facidnext > 0) - { + if ($facidnext > 0) { $facthatreplace = new FactureFournisseur($db); $facthatreplace->fetch($facidnext); print ' ('.$langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)).')'; @@ -190,14 +190,12 @@ if ($object->id > 0) // Amount Local Taxes //TODO: Place into a function to control showing by country or study better option - if ($societe->localtax1_assuj == "1") //Localtax1 - { + if ($societe->localtax1_assuj == "1") { //Localtax1 print '<tr><td>'.$langs->transcountry("AmountLT1", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax1, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; } - if ($societe->localtax2_assuj == "1") //Localtax2 - { + if ($societe->localtax2_assuj == "1") { //Localtax2 print '<tr><td>'.$langs->transcountry("AmountLT2", $societe->country_code).'</td>'; print '<td>'.price($object->total_localtax2, 1, $langs, 0, -1, -1, $conf->currency).'</td>'; print '</tr>'; diff --git a/htdocs/fourn/facture/paiement.php b/htdocs/fourn/facture/paiement.php index 0592084f042..104e0e7efd2 100644 --- a/htdocs/fourn/facture/paiement.php +++ b/htdocs/fourn/facture/paiement.php @@ -64,12 +64,18 @@ $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 +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.rowid"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "p.rowid"; +} $amounts = array(); $amountsresttopay = array(); @@ -79,8 +85,7 @@ $multicurrency_amounts = array(); $multicurrency_amountsresttopay = array(); // Security check -if ($user->socid > 0) -{ +if ($user->socid > 0) { $socid = $user->socid; } @@ -103,8 +108,7 @@ $arrayfields = array(); * Actions */ -if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) // All tests are required to be compatible with all browsers -{ +if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers $search_ref = ""; $search_account = ""; $search_amount = ""; @@ -119,12 +123,12 @@ if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x' $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ - if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) - { +if (empty($reshook)) { + if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm == 'yes')) { $error = 0; $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); @@ -135,10 +139,8 @@ if (empty($reshook)) // Generate payment array and check if there is payment higher than invoice and payment date before invoice date $tmpinvoice = new FactureFournisseur($db); - foreach ($_POST as $key => $value) - { - if (substr($key, 0, 7) == 'amount_') - { + foreach ($_POST as $key => $value) { + if (substr($key, 0, 7) == 'amount_') { $cursorfacid = substr($key, 7); $amounts[$cursorfacid] = price2num(GETPOST($key)); if (!empty($amounts[$cursorfacid])) { @@ -150,19 +152,18 @@ if (empty($reshook)) } } $result = $tmpinvoice->fetch($cursorfacid); - if ($result <= 0) dol_print_error($db); + if ($result <= 0) { + dol_print_error($db); + } $amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement()); - if ($amounts[$cursorfacid]) - { + if ($amounts[$cursorfacid]) { // Check amount - if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) - { + if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) { $addwarning = 1; $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier"); } // Check date - if ($datepaye && ($datepaye < $tmpinvoice->date)) - { + if ($datepaye && ($datepaye < $tmpinvoice->date)) { $langs->load("errors"); //$error++; setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings'); @@ -170,26 +171,26 @@ if (empty($reshook)) } $formquestion[$i++] = array('type' => 'hidden', 'name' => $key, 'value' => $_POST[$key]); - } elseif (substr($key, 0, 21) == 'multicurrency_amount_') - { + } elseif (substr($key, 0, 21) == 'multicurrency_amount_') { $cursorfacid = substr($key, 21); $multicurrency_amounts[$cursorfacid] = (GETPOST($key) ? price2num(GETPOST($key)) : 0); $multicurrency_totalpayment += $multicurrency_amounts[$cursorfacid]; - if (!empty($multicurrency_amounts[$cursorfacid])) $atleastonepaymentnotnull++; + if (!empty($multicurrency_amounts[$cursorfacid])) { + $atleastonepaymentnotnull++; + } $result = $tmpinvoice->fetch($cursorfacid); - if ($result <= 0) dol_print_error($db); + if ($result <= 0) { + dol_print_error($db); + } $multicurrency_amountsresttopay[$cursorfacid] = price2num($tmpinvoice->total_ttc - $tmpinvoice->getSommePaiement(1)); - if ($multicurrency_amounts[$cursorfacid]) - { + if ($multicurrency_amounts[$cursorfacid]) { // Check amount - if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) - { + if ($multicurrency_amounts[$cursorfacid] && (abs($multicurrency_amounts[$cursorfacid]) > abs($multicurrency_amountsresttopay[$cursorfacid]))) { $addwarning = 1; $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPaySupplier")).' '.$langs->trans("HelpPaymentHigherThanReminderToPaySupplier"); } // Check date - if ($datepaye && ($datepaye < $tmpinvoice->date)) - { + if ($datepaye && ($datepaye < $tmpinvoice->date)) { $langs->load("errors"); //$error++; setEventMessages($langs->transnoentities("WarningPaymentDateLowerThanInvoiceDate", dol_print_date($datepaye, 'day'), dol_print_date($tmpinvoice->date, 'day'), $tmpinvoice->ref), null, 'warnings'); @@ -201,37 +202,31 @@ if (empty($reshook)) } // Check parameters - if ($_POST['paiementid'] <= 0) - { + if ($_POST['paiementid'] <= 0) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('PaymentMode')), null, 'errors'); $error++; } - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { // If bank module is on, account is required to enter a payment - if (GETPOST('accountid') <= 0) - { + if (GETPOST('accountid') <= 0) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('AccountToCredit')), null, 'errors'); $error++; } } - if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull)) - { + if (empty($totalpayment) && empty($multicurrency_totalpayment) && empty($atleastonepaymentnotnull)) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->trans('PaymentAmount')), null, 'errors'); $error++; } - if (empty($datepaye)) - { + if (empty($datepaye)) { setEventMessages($langs->transnoentities('ErrorFieldRequired', $langs->transnoentities('Date')), null, 'errors'); $error++; } // Check if payments in both currency - if ($totalpayment > 0 && $multicurrency_totalpayment > 0) - { + if ($totalpayment > 0 && $multicurrency_totalpayment > 0) { setEventMessages($langs->transnoentities('ErrorPaymentInBothCurrency'), null, 'errors'); $error++; } @@ -240,10 +235,8 @@ if (empty($reshook)) /* * Action add_paiement */ - if ($action == 'add_paiement') - { - if ($error) - { + if ($action == 'add_paiement') { + if ($error) { $action = 'create'; } // All the next of this action is displayed at the page's bottom. @@ -253,30 +246,25 @@ if (empty($reshook)) /* * Action confirm_paiement */ - if ($action == 'confirm_paiement' && $confirm == 'yes') - { + if ($action == 'confirm_paiement' && $confirm == 'yes') { $error = 0; $datepaye = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); // Clean parameters amount if payment is for a credit note - foreach ($amounts as $key => $value) // How payment is dispatched - { + foreach ($amounts as $key => $value) { // How payment is dispatched $tmpinvoice = new FactureFournisseur($db); $tmpinvoice->fetch($key); - if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $newvalue = price2num($value, 'MT'); $amounts[$key] = - abs($newvalue); } } - foreach ($multicurrency_amounts as $key => $value) // How payment is dispatched - { + foreach ($multicurrency_amounts as $key => $value) { // How payment is dispatched $tmpinvoice = new FactureFournisseur($db); $tmpinvoice->fetch($key); - if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($tmpinvoice->type == FactureFournisseur::TYPE_CREDIT_NOTE) { $newvalue = price2num($value, 'MT'); $multicurrency_amounts[$key] = - abs($newvalue); } @@ -286,12 +274,13 @@ if (empty($reshook)) //var_dump($multicurrency_amounts); //exit; - if (!$error) - { + if (!$error) { $db->begin(); $thirdparty = new Societe($db); - if ($socid > 0) $thirdparty->fetch($socid); + if ($socid > 0) { + $thirdparty->fetch($socid); + } // Creation of payment line $paiement = new PaiementFourn($db); @@ -305,43 +294,42 @@ if (empty($reshook)) $paiement->num_payment = $paiement->num_payment; $paiement->note_private = $paiement->note_private; - if (!$error) - { + if (!$error) { $paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices') == 'on' ? 1 : 0), $thirdparty); - if ($paiement_id < 0) - { + if ($paiement_id < 0) { setEventMessages($paiement->error, $paiement->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $result = $paiement->addPaymentToBank($user, 'payment_supplier', '(SupplierInvoicePayment)', $accountid, '', ''); - if ($result < 0) - { + if ($result < 0) { setEventMessages($paiement->error, $paiement->errors, 'errors'); $error++; } } - if (!$error) - { + if (!$error) { $db->commit(); // If payment dispatching on more than one invoice, we stay on summary page, otherwise go on invoice card $invoiceid = 0; - foreach ($paiement->amounts as $key => $amount) - { + foreach ($paiement->amounts as $key => $amount) { $facid = $key; - if (is_numeric($amount) && $amount <> 0) - { - if ($invoiceid != 0) $invoiceid = -1; // There is more than one invoice payed by this payment - else $invoiceid = $facid; + if (is_numeric($amount) && $amount <> 0) { + if ($invoiceid != 0) { + $invoiceid = -1; // There is more than one invoice payed by this payment + } else { + $invoiceid = $facid; + } } } - if ($invoiceid > 0) $loc = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$invoiceid; - else $loc = DOL_URL_ROOT.'/fourn/paiement/card.php?id='.$paiement_id; + if ($invoiceid > 0) { + $loc = DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$invoiceid; + } else { + $loc = DOL_URL_ROOT.'/fourn/paiement/card.php?id='.$paiement_id; + } header('Location: '.$loc); exit; } else { @@ -364,8 +352,7 @@ $invoicesupplierstatic = new FactureFournisseur($db); llxHeader('', $langs->trans('ListPayment')); -if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement') -{ +if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paiement') { $object = new FactureFournisseur($db); $result = $object->fetch($facid); @@ -374,26 +361,29 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $sql = 'SELECT s.nom as name, s.rowid as socid,'; $sql .= ' f.rowid, f.ref, f.ref_supplier, f.total_ttc as total, f.fk_mode_reglement, f.fk_account'; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", sc.fk_soc, sc.fk_user "; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", sc.fk_soc, sc.fk_user "; + } $sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s, '.MAIN_DB_PREFIX.'facture_fourn as f'; - if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; + } $sql .= ' WHERE f.fk_soc = s.rowid'; $sql .= ' AND f.rowid = '.$facid; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { $obj = $db->fetch_object($resql); $total = $obj->total; print load_fiche_titre($langs->trans('DoPayment')); // Add realtime total information - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print "\n".'<script type="text/javascript" language="javascript">'; print '$(document).ready(function () { @@ -491,8 +481,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print '<tr><td class="fieldrequired">'.$langs->trans('PaymentMode').'</td><td>'; $form->select_types_paiements(empty($_POST['paiementid']) ? $obj->fk_mode_reglement : $_POST['paiementid'], 'paiementid'); print '</td>'; - if (!empty($conf->banque->enabled)) - { + if (!empty($conf->banque->enabled)) { print '<tr><td class="fieldrequired">'.$langs->trans('Account').'</td><td>'; $form->select_comptes(empty($accountid) ? $obj->fk_account : $accountid, 'accountid', 0, '', 2); print '</td></tr>'; @@ -510,11 +499,10 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $parameters = array('facid'=>$facid, 'ref'=>$ref, 'objcanvas'=>$objcanvas); $reshook = $hookmanager->executeHooks('paymentsupplierinvoices', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks $error = $hookmanager->error; $errors = $hookmanager->errors; - if (empty($reshook)) - { + if (empty($reshook)) { /* - * All unpaid supplier invoices - */ + * All unpaid supplier invoices + */ $sql = 'SELECT f.rowid as facid, f.ref, f.ref_supplier, f.type, f.total_ht, f.total_ttc,'; $sql .= ' f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht, f.multicurrency_total_tva, f.multicurrency_total_ttc,'; $sql .= ' f.datef as df, f.date_lim_reglement as dlr,'; @@ -525,8 +513,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $sql .= ' AND f.fk_soc = '.$object->socid; $sql .= ' AND f.paye = 0'; $sql .= ' AND f.fk_statut = 1'; // Status=0 => unvalidated, Status=2 => canceled - if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) - { + if ($object->type != FactureFournisseur::TYPE_CREDIT_NOTE) { $sql .= ' AND f.type IN (0,1,3,5)'; // Standard invoice, replacement, deposit, situation } else { $sql .= ' AND f.type = 2'; // If paying back a credit note, we show all credit notes @@ -537,11 +524,9 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $sql .= ' ORDER BY f.datef ASC, f.ref ASC'; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num > 0) - { + if ($num > 0) { $i = 0; print '<br>'; @@ -582,12 +567,13 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $total = 0; $total_ttc = 0; $totalrecu = 0; - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $sign = 1; - if ($objp->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = -1; + if ($objp->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $sign = -1; + } $invoice = new FactureFournisseur($db); $invoice->fetch($objp->facid); @@ -629,13 +615,11 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } // Date Max Payment - if ($objp->dlr > 0) - { + if ($objp->dlr > 0) { print '<td class="center nowraponall">'; print dol_print_date($db->jdate($objp->dlr), 'day'); - if ($invoice->hasDelay()) - { + if ($invoice->hasDelay()) { print img_warning($langs->trans('Late')); } @@ -645,28 +629,24 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } // Multicurrency - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { // Currency print '<td class="center">'.$objp->multicurrency_code."</td>\n"; print '<td class="right">'; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) { print price($objp->multicurrency_total_ttc); } print '</td>'; print '<td class="right">'; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) { print price($objp->multicurrency_am); } print '</td>'; print '<td class="right">'; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) { print price($objp->multicurrency_total_ttc - $objp->multicurrency_am); } print '</td>'; @@ -675,8 +655,12 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print '<td class="right">'.price($sign * $objp->total_ttc).'</td>'; print '<td class="right">'.price($sign * $objp->am); - if ($creditnotes) print '+'.price($creditnotes); - if ($deposits) print '+'.price($deposits); + if ($creditnotes) { + print '+'.price($creditnotes); + } + if ($deposits) { + print '+'.price($deposits); + } print '</td>'; print '<td class="right">'.price($sign * $remaintopay).'</td>'; @@ -687,10 +671,10 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie $namef = 'amount_'.$objp->facid; $nameRemain = 'remain_'.$objp->facid; - if ($action != 'add_paiement') - { - if (!empty($conf->use_javascript_ajax)) + if ($action != 'add_paiement') { + if (!empty($conf->use_javascript_ajax)) { print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $remaintopay)."'"); + } print '<input type="hidden" class="remain" name="'.$nameRemain.'" value="'.$remaintopay.'">'; print '<input type="text" size="8" class="amount" name="'.$namef.'" value="'.dol_escape_htmltag(GETPOST($namef)).'">'; // class is requied to be used by javascript callForResult(); } else { @@ -700,20 +684,18 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie print "</td>"; // Multicurrency Price - if (!empty($conf->multicurrency->enabled)) - { + if (!empty($conf->multicurrency->enabled)) { print '<td class="right">'; // Add remind multicurrency amount $namef = 'multicurrency_amount_'.$objp->facid; $nameRemain = 'multicurrency_remain_'.$objp->facid; - if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) - { - if ($action != 'add_paiement') - { - if (!empty($conf->use_javascript_ajax)) + if ($objp->multicurrency_code && $objp->multicurrency_code != $conf->currency) { + if ($action != 'add_paiement') { + if (!empty($conf->use_javascript_ajax)) { print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmout' data-rowname='".$namef."' data-value='".($sign * $multicurrency_remaintopay)."'"); + } print '<input type=hidden class="multicurrency_remain" name="'.$nameRemain.'" value="'.$multicurrency_remaintopay.'">'; print '<input type="text" size="8" class="multicurrency_amount" name="'.$namef.'" value="'.$_POST[$namef].'">'; } else { @@ -744,8 +726,12 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } print '<td class="right"><b>'.price($sign * $total_ttc).'</b></td>'; print '<td class="right"><b>'.price($sign * $totalrecu); - if ($totalrecucreditnote) print '+'.price($totalrecucreditnote); - if ($totalrecudeposits) print '+'.price($totalrecudeposits); + if ($totalrecucreditnote) { + print '+'.price($totalrecucreditnote); + } + if ($totalrecudeposits) { + print '+'.price($totalrecudeposits); + } print '</b></td>'; print '<td class="right"><b>'.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits, 'MT')).'</b></td>'; print '<td class="center" id="result" style="font-weight: bold;"></td>'; // Autofilled @@ -765,25 +751,23 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } // Save Button - if ($action != 'add_paiement') - { + if ($action != 'add_paiement') { print '<br><div class="center"><input type="checkbox" checked name="closepaidinvoices"> '.$langs->trans("ClosePaidInvoicesAutomatically"); print '<br><input type="submit" class="button" value="'.$langs->trans('ToMakePayment').'"></div>'; } // Form to confirm payment - if ($action == 'add_paiement') - { + if ($action == 'add_paiement') { $preselectedchoice = $addwarning ? 'no' : 'yes'; print '<br>'; - if (!empty($totalpayment)) $text = $langs->trans('ConfirmSupplierPayment', price($totalpayment), $langs->trans("Currency".$conf->currency)); - if (!empty($multicurrency_totalpayment)) - { + if (!empty($totalpayment)) { + $text = $langs->trans('ConfirmSupplierPayment', price($totalpayment), $langs->trans("Currency".$conf->currency)); + } + if (!empty($multicurrency_totalpayment)) { $text .= '<br>'.$langs->trans('ConfirmSupplierPayment', price($multicurrency_totalpayment), $langs->trans("paymentInInvoiceCurrency")); } - if (GETPOST('closepaidinvoices')) - { + if (GETPOST('closepaidinvoices')) { $text .= '<br>'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed"); print '<input type="hidden" name="closepaidinvoices" value="'.GETPOST('closepaidinvoices').'">'; } diff --git a/htdocs/fourn/facture/rapport.php b/htdocs/fourn/facture/rapport.php index 9ae7970d7db..fe2bb78008d 100644 --- a/htdocs/fourn/facture/rapport.php +++ b/htdocs/fourn/facture/rapport.php @@ -32,36 +32,39 @@ $langs->loadLangs(array('bills')); // Security check $socid = ''; -if (!empty($user->socid)) $socid = $user->socid; +if (!empty($user->socid)) { + $socid = $user->socid; +} $result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture'); $action = GETPOST('action', 'aZ09'); $socid = 0; -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } $dir = $conf->fournisseur->facture->dir_output.'/payments'; -if (!$user->rights->societe->client->voir || $socid) $dir .= '/private/'.$user->id; // If user has no permission to see all, output dir is specific to user +if (!$user->rights->societe->client->voir || $socid) { + $dir .= '/private/'.$user->id; // If user has no permission to see all, output dir is specific to user +} $year = GETPOST("year", 'int'); -if (!$year) { $year = date("Y"); } +if (!$year) { + $year = date("Y"); +} /* * Actions */ -if ($action == 'builddoc') -{ +if ($action == 'builddoc') { $rap = new pdf_paiement_fourn($db); $outputlangs = $langs; - if (GETPOST('lang_id', 'aZ09')) - { + if (GETPOST('lang_id', 'aZ09')) { $outputlangs = new Translate("", $conf); $outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09')); } @@ -69,8 +72,7 @@ if ($action == 'builddoc') // We save charset_output to restore it because write_file can change it if needed for // output format that does not support UTF8. $sav_charset_output = $outputlangs->charset_output; - if ($rap->write_file($dir, GETPOST("remonth", 'int'), GETPOST("reyear", 'int'), $outputlangs) > 0) - { + if ($rap->write_file($dir, GETPOST("remonth", 'int'), GETPOST("reyear", 'int'), $outputlangs) > 0) { $outputlangs->charset_output = $sav_charset_output; } else { $outputlangs->charset_output = $sav_charset_output; @@ -114,15 +116,11 @@ clearstatcache(); // Show link on other years $linkforyear = array(); $found = 0; -if (is_dir($dir)) -{ +if (is_dir($dir)) { $handle = opendir($dir); - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (is_dir($dir.'/'.$file) && !preg_match('/^\./', $file) && is_numeric($file)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (is_dir($dir.'/'.$file) && !preg_match('/^\./', $file) && is_numeric($file)) { $found = 1; $linkforyear[] = $file; } @@ -130,18 +128,17 @@ if (is_dir($dir)) } } asort($linkforyear); -foreach ($linkforyear as $cursoryear) -{ +foreach ($linkforyear as $cursoryear) { print '<a href="'.$_SERVER["PHP_SELF"].'?year='.$cursoryear.'">'.$cursoryear.'</a> &nbsp;'; } -if ($year) -{ - if (is_dir($dir.'/'.$year)) - { +if ($year) { + if (is_dir($dir.'/'.$year)) { $handle = opendir($dir.'/'.$year); - if ($found) print '<br>'; + if ($found) { + print '<br>'; + } print '<br>'; print '<table width="100%" class="noborder">'; print '<tr class="liste_titre">'; @@ -150,12 +147,9 @@ if ($year) print '<td class="right">'.$langs->trans("Date").'</td>'; print '</tr>'; - if (is_resource($handle)) - { - while (($file = readdir($handle)) !== false) - { - if (preg_match('/^supplier_payment/i', $file)) - { + if (is_resource($handle)) { + while (($file = readdir($handle)) !== false) { + if (preg_match('/^supplier_payment/i', $file)) { $tfile = $dir.'/'.$year.'/'.$file; $relativepath = $year.'/'.$file; print '<tr class="oddeven"><td><a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?modulepart=facture_fournisseur&amp;file=payments/'.urlencode($relativepath).'">'.img_pdf().' '.$file.'</a>'.$formfile->showPreview($file, 'facture_fournisseur', 'payments/'.$relativepath, 0).'</td>'; diff --git a/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php b/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php index 4456d27c539..c3ca301ed45 100644 --- a/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php +++ b/htdocs/fourn/facture/tpl/linkedobjectblock.tpl.php @@ -19,8 +19,7 @@ */ // Protection to avoid direct call of template -if (empty($conf) || !is_object($conf)) -{ +if (empty($conf) || !is_object($conf)) { print "Error, template page can't be called as URL"; exit; } @@ -38,24 +37,26 @@ $linkedObjectBlock = $GLOBALS['linkedObjectBlock']; $langs->load("bills"); $total = 0; $ilink = 0; -foreach ($linkedObjectBlock as $key => $objectlink) -{ +foreach ($linkedObjectBlock as $key => $objectlink) { $ilink++; $trclass = 'oddeven'; - if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) $trclass .= ' liste_sub_total'; + if ($ilink == count($linkedObjectBlock) && empty($noMoreLinkedObjectBlockAfter) && count($linkedObjectBlock) <= 1) { + $trclass .= ' liste_sub_total'; + } ?> - <tr class="<?php echo $trclass; ?>"> - <td><?php echo $langs->trans("SupplierInvoice"); ?></td> - <td><a href="<?php echo DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowBill"), "bill").' '.$objectlink->ref; ?></a></td> - <td class="left"><?php echo $objectlink->ref_supplier; ?></td> - <td class="center"><?php echo dol_print_date($objectlink->date, 'day'); ?></td> - <td class="right"><?php + <tr class="<?php echo $trclass; ?>"> + <td><?php echo $langs->trans("SupplierInvoice"); ?></td> + <td><a href="<?php echo DOL_URL_ROOT.'/fourn/facture/card.php?facid='.$objectlink->id ?>"><?php echo img_object($langs->trans("ShowBill"), "bill").' '.$objectlink->ref; ?></a></td> + <td class="left"><?php echo $objectlink->ref_supplier; ?></td> + <td class="center"><?php echo dol_print_date($objectlink->date, 'day'); ?></td> + <td class="right"><?php if ($user->rights->fournisseur->facture->lire) { $sign = 1; - if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) $sign = -1; - if ($objectlink->statut != 3) - { + if ($object->type == FactureFournisseur::TYPE_CREDIT_NOTE) { + $sign = -1; + } + if ($objectlink->statut != 3) { // If not abandonned $total = $total + $sign * $objectlink->total_ht; echo price($objectlink->total_ht); @@ -63,24 +64,23 @@ foreach ($linkedObjectBlock as $key => $objectlink) echo '<strike>'.price($objectlink->total_ht).'</strike>'; } } ?></td> - <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> - <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> - </tr> - <?php + <td class="right"><?php echo $objectlink->getLibStatut(3); ?></td> + <td class="right"><a class="reposition" href="<?php echo $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=dellink&dellinkid='.$key; ?>"><?php echo img_picto($langs->transnoentitiesnoconv("RemoveLink"), 'unlink'); ?></a></td> + </tr> + <?php } -if (count($linkedObjectBlock) > 1) -{ +if (count($linkedObjectBlock) > 1) { ?> - <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> - <td><?php echo $langs->trans("Total"); ?></td> - <td></td> - <td class="center"></td> - <td class="center"></td> - <td class="right"><?php echo price($total); ?></td> - <td class="right"></td> - <td class="right"></td> - </tr> - <?php + <tr class="liste_total <?php echo (empty($noMoreLinkedObjectBlockAfter) ? 'liste_sub_total' : ''); ?>"> + <td><?php echo $langs->trans("Total"); ?></td> + <td></td> + <td class="center"></td> + <td class="center"></td> + <td class="right"><?php echo price($total); ?></td> + <td class="right"></td> + <td class="right"></td> + </tr> + <?php } print "<!-- END PHP TEMPLATE -->\n"; diff --git a/htdocs/fourn/index.php b/htdocs/fourn/index.php index 5d82021bf3c..54ed40e37b0 100644 --- a/htdocs/fourn/index.php +++ b/htdocs/fourn/index.php @@ -32,7 +32,9 @@ $langs->loadLangs(array("suppliers", "orders", "companies")); // Security check $socid = GETPOST("socid", 'int'); -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} $result = restrictedArea($user, 'societe', $socid, ''); @@ -58,15 +60,18 @@ print '<div class="fichecenter"><div class="fichethirdleft">'; $sql = "SELECT count(cf.rowid), cf.fk_statut"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf,"; $sql .= " ".MAIN_DB_PREFIX."societe as s"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; +} $sql .= " WHERE cf.fk_soc = s.rowid "; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND sc.fk_user = ".$user->id; +} $sql .= " AND cf.entity = ".$conf->entity; $sql .= " GROUP BY cf.fk_statut"; $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -74,8 +79,7 @@ if ($resql) print '<tr class="liste_titre"><td>'.$langs->trans("Orders").'</td><td class="center">'.$langs->trans("Nb").'</td><td>&nbsp;</td>'; print "</tr>\n"; - while ($i < $num) - { + while ($i < $num) { $row = $db->fetch_row($resql); print '<tr class="oddeven">'; @@ -95,35 +99,37 @@ if ($resql) // Draft orders -if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) -{ +if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_order->enabled)) { $langs->load("orders"); $sql = "SELECT cf.rowid, cf.ref, cf.total_ttc,"; $sql .= " s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."commande_fournisseur as cf"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + } $sql .= " WHERE cf.fk_soc = s.rowid"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND sc.fk_user = ".$user->id; + } $sql .= " AND cf.entity = ".$conf->entity; $sql .= " AND cf.fk_statut = 0"; - if ($socid) $sql .= " AND cf.fk_soc = ".$socid; + if ($socid) { + $sql .= " AND cf.fk_soc = ".$socid; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $total = 0; $num = $db->num_rows($resql); - if ($num) - { + if ($num) { print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<td colspan="3">'.$langs->trans("DraftOrders").'<span class="badge marginleftonlyshort">'.$num.'</span></td></tr>'; $i = 0; - while ($i < $num) - { + while ($i < $num) { $obj = $db->fetch_object($resql); print '<tr class="oddeven"><td class="nowrap">'; @@ -141,8 +147,7 @@ if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUP $i++; $total += $obj->total_ttc; } - if ($total > 0) - { + if ($total > 0) { print '<tr class="liste_total"><td>'.$langs->trans("Total").'</td><td colspan="2" class="right">'.price($total)."</td></tr>"; } print "</table>"; @@ -152,34 +157,36 @@ if (!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUP } // Draft invoices -if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) -{ +if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->fournisseur->facture->lire) { $sql = "SELECT ff.ref_supplier, ff.rowid, ff.total_ttc, ff.type"; $sql .= ", s.nom as name, s.rowid as socid"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as ff"; $sql .= ", ".MAIN_DB_PREFIX."societe as s"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe_commerciaux as sc ON s.rowid = sc.fk_soc"; + } $sql .= " WHERE s.rowid = ff.fk_soc"; - if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND sc.fk_user = ".$user->id; + if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND sc.fk_user = ".$user->id; + } $sql .= " AND ff.entity = ".$conf->entity; $sql .= " AND ff.fk_statut = 0"; - if ($socid) $sql .= " AND f.fk_soc = ".$socid; + if ($socid) { + $sql .= " AND f.fk_soc = ".$socid; + } $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); - if ($num) - { + if ($num) { print '<table class="noborder centpercent">'; print '<tr class="liste_titre">'; print '<td colspan="3">'.$langs->trans("DraftBills").'<span class="badge marginleftonlyshort">'.$num.'</span></td></tr>'; $i = 0; $tot_ttc = 0; - while ($i < $num && $i < 20) - { + while ($i < $num && $i < 20) { $obj = $db->fetch_object($resql); print '<tr class="oddeven"><td class="nowrap">'; @@ -226,18 +233,23 @@ $sql = "SELECT s.rowid as socid, s.nom as name, s.town, s.datec, s.tms, s.prefix $sql .= ", st.libelle as stcomm"; $sql .= " FROM ".MAIN_DB_PREFIX."societe as s"; $sql .= ", ".MAIN_DB_PREFIX."c_stcomm as st"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; +} $sql .= " WHERE s.fk_stcomm = st.id"; $sql .= " AND s.fournisseur = 1"; $sql .= " AND s.entity IN (".getEntity('societe').")"; -if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; -if ($socid) $sql .= " AND s.rowid = ".$socid; +if (!$user->rights->societe->client->voir && !$socid) { + $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id; +} +if ($socid) { + $sql .= " AND s.rowid = ".$socid; +} $sql .= " ORDER BY s.tms DESC"; $sql .= $db->plimit($max, 0); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $langs->load("boxes"); $num = $db->num_rows($resql); $i = 0; @@ -248,8 +260,7 @@ if ($resql) print '<td class="right">'.$langs->trans("DateModification")."</td>\n"; print "</tr>\n"; - while ($obj = $db->fetch_object($resql)) - { + while ($obj = $db->fetch_object($resql)) { print '<tr class="oddeven">'; print '<td><a href="card.php?socid='.$obj->socid.'">'.img_object($langs->trans("ShowSupplier"), "company").'</a>'; print "&nbsp;<a href=\"card.php?socid=".$obj->socid."\">".$obj->name."</a></td>\n"; @@ -271,8 +282,7 @@ if ($resql) $companystatic->LoadSupplierCateg(); $categstatic = new Categorie($db); -if (count($companystatic->SupplierCategories)) -{ +if (count($companystatic->SupplierCategories)) { print '<br>'; print '<table class="liste centpercent">'; @@ -280,8 +290,7 @@ if (count($companystatic->SupplierCategories)) print $langs->trans("Category"); print "</td></tr>\n"; - foreach ($companystatic->SupplierCategories as $rowid => $label) - { + foreach ($companystatic->SupplierCategories as $rowid => $label) { print '<tr class="oddeven">'."\n"; print '<td>'; $categstatic->id = $rowid; diff --git a/htdocs/fourn/js/lib_dispatch.js.php b/htdocs/fourn/js/lib_dispatch.js.php index b4090e8a34d..254fac29f28 100644 --- a/htdocs/fourn/js/lib_dispatch.js.php +++ b/htdocs/fourn/js/lib_dispatch.js.php @@ -21,13 +21,27 @@ * \brief File that include javascript functions used for dispatching qty/stock/lot */ -if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); -if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1); -if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1); -if (!defined('NOLOGIN')) define('NOLOGIN', 1); -if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', 1); -if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1); -if (!defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); +if (!defined('NOREQUIRESOC')) { + define('NOREQUIRESOC', '1'); +} +if (!defined('NOCSRFCHECK')) { + define('NOCSRFCHECK', 1); +} +if (!defined('NOTOKENRENEWAL')) { + define('NOTOKENRENEWAL', 1); +} +if (!defined('NOLOGIN')) { + define('NOLOGIN', 1); +} +if (!defined('NOREQUIREMENU')) { + define('NOREQUIREMENU', 1); +} +if (!defined('NOREQUIREHTML')) { + define('NOREQUIREHTML', 1); +} +if (!defined('NOREQUIREAJAX')) { + define('NOREQUIREAJAX', '1'); +} session_cache_limiter('public'); @@ -36,8 +50,11 @@ require_once '../../main.inc.php'; // Define javascript type top_httphead('text/javascript; charset=UTF-8'); // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access. -if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate'); -else header('Cache-Control: no-cache'); +if (empty($dolibarr_nocache)) { + header('Cache-Control: max-age=10800, public, must-revalidate'); +} else { + header('Cache-Control: no-cache'); +} ?> /** diff --git a/htdocs/fourn/paiement/card.php b/htdocs/fourn/paiement/card.php index 5dea09eaf09..66981436d7a 100644 --- a/htdocs/fourn/paiement/card.php +++ b/htdocs/fourn/paiement/card.php @@ -48,7 +48,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ $result = restrictedArea($user, $object->element, $object->id, 'paiementfourn', ''); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // Now check also permission on thirdparty of invoices of payments. Thirdparty were loaded by the fetch_object before based on first invoice. // It should be enough because all payments are done on invoices of the same thirdparty. if ($socid && $socid != $object->thirdparty->id) { @@ -60,14 +62,12 @@ if ($socid && $socid != $object->thirdparty->id) { * Actions */ -if ($action == 'setnote' && $user->rights->fournisseur->facture->creer) -{ +if ($action == 'setnote' && $user->rights->fournisseur->facture->creer) { $db->begin(); $object->fetch($id); $result = $object->update_note(GETPOST('note', 'restricthtml')); - if ($result > 0) - { + if ($result > 0) { $db->commit(); $action = ''; } else { @@ -76,14 +76,12 @@ if ($action == 'setnote' && $user->rights->fournisseur->facture->creer) } } -if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) -{ +if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) { $db->begin(); $object->fetch($id); $result = $object->delete(); - if ($result > 0) - { + if ($result > 0) { $db->commit(); header('Location: '.DOL_URL_ROOT.'/fourn/paiement/list.php'); exit; @@ -96,13 +94,11 @@ if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisse if ($action == 'confirm_validate' && $confirm == 'yes' && ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->facture->creer)) || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate))) -) -{ +) { $db->begin(); $object->fetch($id); - if ($object->validate() >= 0) - { + if ($object->validate() >= 0) { $db->commit(); header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id); exit; @@ -112,25 +108,21 @@ if ($action == 'confirm_validate' && $confirm == 'yes' && } } -if ($action == 'setnum_paiement' && !empty($_POST['num_paiement'])) -{ +if ($action == 'setnum_paiement' && !empty($_POST['num_paiement'])) { $object->fetch($id); $res = $object->update_num($_POST['num_paiement']); - if ($res === 0) - { + if ($res === 0) { setEventMessages($langs->trans('PaymentNumberUpdateSucceeded'), null, 'mesgs'); } else { setEventMessages($langs->trans('PaymentNumberUpdateFailed'), null, 'errors'); } } -if ($action == 'setdatep' && !empty($_POST['datepday'])) -{ +if ($action == 'setdatep' && !empty($_POST['datepday'])) { $object->fetch($id); $datepaye = dol_mktime(GETPOST('datephour', 'int'), GETPOST('datepmin', 'int'), GETPOST('datepsec', 'int'), GETPOST('datepmonth', 'int'), GETPOST('datepday', 'int'), GETPOST('datepyear', 'int')); $res = $object->update_date($datepaye); - if ($res === 0) - { + if ($res === 0) { setEventMessages($langs->trans('PaymentDateUpdateSucceeded'), null, 'mesgs'); } else { setEventMessages($langs->trans('PaymentDateUpdateFailed'), null, 'errors'); @@ -159,21 +151,18 @@ $head = payment_supplier_prepare_head($object); print dol_get_fiche_head($head, 'payment', $langs->trans('SupplierPayment'), -1, 'payment'); -if ($result > 0) -{ +if ($result > 0) { /* * Confirmation of payment's delete */ - if ($action == 'delete') - { + if ($action == 'delete') { print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete'); } /* * Confirmation of payment's validation */ - if ($action == 'validate') - { + if ($action == 'validate') { print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_validate'); } @@ -189,7 +178,7 @@ if ($result > 0) /*print '<tr>'; print '<td width="20%">'.$langs->trans('Ref').'</td><td>'; - print $form->showrefnav($object,'id','',1,'rowid','ref'); + print $form->showrefnav($object,'id','',1,'rowid','ref'); print '</td></tr>';*/ // Date of payment @@ -211,28 +200,24 @@ if ($result > 0) print '<td>'; print $form->editfieldval("Numero",'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded')); print '</td></tr>'; - */ + */ // Amount print '<tr><td>'.$langs->trans('Amount').'</td>'; print '<td>'.price($object->amount, '', $langs, 0, 0, -1, $conf->currency).'</td></tr>'; - if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) - { + if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) { print '<tr><td>'.$langs->trans('Status').'</td>'; print '<td>'.$object->getLibStatut(4).'</td></tr>'; } $allow_delete = 1; // Bank account - if (!empty($conf->banque->enabled)) - { - if ($object->fk_account) - { + if (!empty($conf->banque->enabled)) { + if ($object->fk_account) { $bankline = new AccountLine($db); $bankline->fetch($object->bank_line); - if ($bankline->rappro) - { + if ($bankline->rappro) { $allow_delete = 0; $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment")); } @@ -276,8 +261,7 @@ if ($result > 0) $sql .= ' WHERE pf.fk_facturefourn = f.rowid AND f.fk_soc = s.rowid'; $sql .= ' AND pf.fk_paiementfourn = '.$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); $i = 0; @@ -293,12 +277,10 @@ if ($result > 0) print '<td class="right">'.$langs->trans('Status').'</td>'; print "</tr>\n"; - if ($num > 0) - { + if ($num > 0) { $facturestatic = new FactureFournisseur($db); - while ($i < $num) - { + while ($i < $num) { $objp = $db->fetch_object($resql); $facturestatic->id = $objp->facid; @@ -328,8 +310,7 @@ if ($result > 0) print '<td class="right">'.$facturestatic->LibStatut($objp->paye, $objp->status, 6, 1).'</td>'; print "</tr>\n"; - if ($objp->paye == 1) - { + if ($objp->paye == 1) { $allow_delete = 0; $title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemovePaymentWithOneInvoicePaid")); } @@ -353,23 +334,17 @@ if ($result > 0) */ print '<div class="tabsAction">'; - if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) - { - if ($user->socid == 0 && $object->statut == 0 && $action == '') - { + if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) { + if ($user->socid == 0 && $object->statut == 0 && $action == '') { if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->facture->creer)) - || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate))) - { + || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate))) { print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=validate">'.$langs->trans('Valid').'</a>'; } } } - if ($user->socid == 0 && $action == '') - { - if ($user->rights->fournisseur->facture->supprimer) - { - if ($allow_delete) - { + if ($user->socid == 0 && $action == '') { + if ($user->rights->fournisseur->facture->supprimer) { + if ($allow_delete) { print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>'; } else { print '<a class="butActionRefused classfortooltip" href="#" title="'.$title_button.'">'.$langs->trans('Delete').'</a>'; @@ -385,8 +360,7 @@ if ($result > 0) include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php'; $modellist = ModelePDFSuppliersPayments::liste_modeles($db); - if (is_array($modellist)) - { + if (is_array($modellist)) { $ref = dol_sanitizeFileName($object->ref); $filedir = $conf->fournisseur->payment->dir_output.'/'.dol_sanitizeFileName($object->ref); $urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id; diff --git a/htdocs/fourn/paiement/info.php b/htdocs/fourn/paiement/info.php index 9ff0a86931e..8032b2b418f 100644 --- a/htdocs/fourn/paiement/info.php +++ b/htdocs/fourn/paiement/info.php @@ -40,7 +40,9 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ $result = restrictedArea($user, $object->element, $object->id, 'paiementfourn', ''); // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // Now check also permission on thirdparty of invoices of payments. Thirdparty were loaded by the fetch_object before based on first invoice. // It should be enough because all payments are done on invoices of the same thirdparty. if ($socid && $socid != $object->thirdparty->id) { diff --git a/htdocs/fourn/paiement/list.php b/htdocs/fourn/paiement/list.php index 1bf8984a6ee..02adee36149 100644 --- a/htdocs/fourn/paiement/list.php +++ b/htdocs/fourn/paiement/list.php @@ -35,7 +35,9 @@ require '../../main.inc.php'; // Security check -if ($user->socid) $socid = $user->socid; +if ($user->socid) { + $socid = $user->socid; +} // doesn't work :-( // restrictedArea($user, 'fournisseur'); @@ -78,13 +80,19 @@ $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 +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"; +if (!$sortorder) { + $sortorder = "DESC"; +} +if (!$sortfield) { + $sortfield = "p.datep"; +} $search_all = trim(GETPOSTISSET("search_all") ? GETPOST("search_all", 'alpha') : GETPOST('sall')); @@ -117,7 +125,9 @@ $object = new PaiementFourn($db); $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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} if (empty($reshook)) { include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; @@ -150,7 +160,9 @@ $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'; +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'; @@ -160,26 +172,48 @@ $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'; +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); +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."'"; +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."'"; +} -if ($search_all) $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} // Add where from extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; $sql .= ' GROUP BY p.rowid, p.ref, p.datep, p.amount, p.num_paiement, s.rowid, s.nom, s.email, c.code, c.libelle, ba.rowid, ba.label'; -if (!$user->rights->societe->client->voir) $sql .= ', sc.fk_soc, sc.fk_user'; +if (!$user->rights->societe->client->voir) { + $sql .= ', sc.fk_soc, sc.fk_user'; +} $sql .= $db->order($sortfield, $sortorder); @@ -207,24 +241,48 @@ $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 (!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); +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 '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; -if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; +} print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="list">'; print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">'; @@ -234,9 +292,10 @@ print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; print_barre_liste($langs->trans('SupplierPayments'), $page, $_SERVER['PHP_SELF'], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords, 'supplier_invoice', 0, '', '', $limit, 0, 0, 1); -if ($search_all) -{ - foreach ($fieldstosearchall as $key => $val) $fieldstosearchall[$key] = $langs->trans($val); +if ($search_all) { + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + } print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>'; } @@ -244,8 +303,11 @@ $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 (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} if ($moreforfilter) { print '<div class="liste_titre liste_titre_bydiv centpercent">'; @@ -255,7 +317,9 @@ if ($moreforfilter) { $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); +if ($massactionbutton) { + $selectedfields .= $form->showCheckAddButtons('checkforselect', 1); +} print '<div class="div-table-responsive">'; print '<table class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : '').'">'; @@ -272,7 +336,9 @@ if (!empty($arrayfields['p.ref']['checked'])) { // Filter: Date if (!empty($arrayfields['p.datep']['checked'])) { print '<td class="liste_titre center">'; - if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_day" value="'.dol_escape_htmltag($search_day).'">'; + if (!empty($conf->global->MAIN_LIST_FILTER_ON_DAY)) { + print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_day" value="'.dol_escape_htmltag($search_day).'">'; + } print '<input class="flat width25 valignmiddle" type="text" maxlength="2" name="search_month" value="'.dol_escape_htmltag($search_month).'">'; $formother->select_year($search_year ? $search_year : -1, 'search_year', 1, 20, 5); print '</td>'; @@ -326,14 +392,30 @@ print '</td>'; print '</tr>'; print '<tr class="liste_titre">'; -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 '); +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); @@ -368,21 +450,29 @@ while ($i < min($num, $limit)) { // No if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER_IN_LIST)) { print '<td>'.(($offset * $limit) + $i).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Ref if (!empty($arrayfields['p.ref']['checked'])) { print '<td class="nowrap">'.$paymentfournstatic->getNomUrl(1).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Date if (!empty($arrayfields['p.datep']['checked'])) { $dateformatforpayment = 'day'; - if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) $dateformatforpayment = 'dayhour'; + if (!empty($conf->global->INVOICE_USE_HOURS_FOR_PAYMENT)) { + $dateformatforpayment = 'dayhour'; + } print '<td class="nowrap center">'.dol_print_date($db->jdate($objp->datep), $dateformatforpayment).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Thirdparty @@ -392,43 +482,57 @@ while ($i < min($num, $limit)) { print $companystatic->getNomUrl(1, '', 24); } print '</td>'; - if (!$i) $totalarray['nbfield']++; + 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 '<td>'.$payment_type.' '.dol_trunc($objp->num_paiement, 32).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Cheque number (fund transfer) if (!empty($arrayfields['p.num_paiement']['checked'])) { print '<td>'.$objp->num_paiement.'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Account - if (!empty($arrayfields['ba.label']['checked'])) - { + if (!empty($arrayfields['ba.label']['checked'])) { print '<td>'; - if ($objp->bid) print '<a href="'.DOL_URL_ROOT.'/compta/bank/bankentries_list.php?account='.$objp->bid.'">'.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).'</a>'; - else print '&nbsp;'; + if ($objp->bid) { + print '<a href="'.DOL_URL_ROOT.'/compta/bank/bankentries_list.php?account='.$objp->bid.'">'.img_object($langs->trans("ShowAccount"), 'account').' '.dol_trunc($objp->label, 24).'</a>'; + } else { + print '&nbsp;'; + } print '</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } } // Amount if (!empty($arrayfields['p.amount']['checked'])) { print '<td class="right">'.price($objp->pamount).'</td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } $totalarray['pos'][$checkedCount] = 'amount'; $totalarray['val']['amount'] += $objp->pamount; } // Buttons print '<td></td>'; - if (!$i) $totalarray['nbfield']++; + if (!$i) { + $totalarray['nbfield']++; + } print '</tr>'; $i++; diff --git a/htdocs/fourn/product/list.php b/htdocs/fourn/product/list.php index 468352c72fe..32ddf769ce2 100644 --- a/htdocs/fourn/product/list.php +++ b/htdocs/fourn/product/list.php @@ -33,7 +33,9 @@ require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php'; $langs->loadLangs(array("products", "suppliers")); -if (!$user->rights->produit->lire && !$user->rights->service->lire) accessforbidden(); +if (!$user->rights->produit->lire && !$user->rights->service->lire) { + accessforbidden(); +} $sref = GETPOST('sref', 'alphanohtml'); $sRefSupplier = GETPOST('srefsupplier'); @@ -46,15 +48,23 @@ $limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1) { $page = 0; } // If $page is not defined, or '' or -1 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; -if (!$sortfield) $sortfield = "p.ref"; // Set here default search field -if (!$sortorder) $sortorder = "ASC"; +if (!$sortfield) { + $sortfield = "p.ref"; // Set here default search field +} +if (!$sortorder) { + $sortorder = "ASC"; +} $fourn_id = GETPOST('fourn_id', 'intcomma'); -if ($user->socid) $fourn_id = $user->socid; +if ($user->socid) { + $fourn_id = $user->socid; +} $catid = GETPOST('catid', 'intcomma'); @@ -71,22 +81,26 @@ $extrafields = new ExtraFields($db); * Put here all code to do according to value of "action" parameter */ -if (GETPOST('cancel', 'alpha')) { $action = 'list'; $massaction = ''; } -if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { $massaction = ''; } +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { // Selection of new fields 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 - { + 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 $sref = ''; $sRefSupplier = ''; $snom = ''; @@ -109,8 +123,7 @@ $companystatic = new Societe($db); $title = $langs->trans("ProductsAndServices"); -if ($fourn_id) -{ +if ($fourn_id) { $supplier = new Fournisseur($db); $supplier->fetch($fourn_id); } @@ -122,8 +135,12 @@ $arrayofmassactions = array( 'builddoc'=>$langs->trans("PDFMerge"), 'presend'=>$langs->trans("SendByMail"), ); -if ($user->rights->mymodule->supprimer) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); -if (in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); +if ($user->rights->mymodule->supprimer) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); +} +if (in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} $massactionbutton = $form->selectMassAction('', $arrayofmassactions); @@ -133,54 +150,52 @@ $sql .= " s.rowid as socid, s.nom as name"; // Add fields to SELECT from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object, $action); -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} $sql .= $hookmanager->resPrint; $sql .= " FROM ".MAIN_DB_PREFIX."product as p"; -if ($catid) $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON cp.fk_product = p.rowid"; +if ($catid) { + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."categorie_product as cp ON cp.fk_product = p.rowid"; +} $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_fournisseur_price as ppf ON p.rowid = ppf.fk_product"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON ppf.fk_soc = s.rowid"; $sql .= " WHERE p.entity IN (".getEntity('product').")"; -if ($sRefSupplier) -{ +if ($sRefSupplier) { $sql .= natural_search('ppf.ref_fourn', $sRefSupplier); } -if (GETPOST('type')) -{ +if (GETPOST('type')) { $sql .= " AND p.fk_product_type = ".GETPOST('type', 'int'); } -if ($sref) -{ +if ($sref) { $sql .= natural_search('p.ref', $sref); } -if ($snom) -{ +if ($snom) { $sql .= natural_search('p.label', $snom); } -if ($catid) -{ +if ($catid) { $sql .= " AND cp.fk_categorie = ".$catid; } -if ($fourn_id > 0) -{ +if ($fourn_id > 0) { $sql .= " AND ppf.fk_soc = ".$fourn_id; } // Add WHERE filters from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} $sql .= $hookmanager->resPrint; $sql .= $db->order($sortfield, $sortorder); // Count total nb of records without orderby and limit $nbtotalofrecords = ''; -if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) -{ +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 - { + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller then paging size (filtering), goto and load page 0 $page = 0; $offset = 0; } @@ -190,30 +205,32 @@ $sql .= $db->plimit($limit + 1, $offset); dol_syslog("fourn/product/list.php:", LOG_DEBUG); $resql = $db->query($sql); -if ($resql) -{ +if ($resql) { $num = $db->num_rows($resql); $i = 0; - if ($num == 1 && (GETPOST("mode") == 'search')) - { + if ($num == 1 && (GETPOST("mode") == 'search')) { $objp = $db->fetch_object($resql); header("Location: ".DOL_URL_ROOT."/product/card.php?id=".$objp->rowid); exit; } - if (!empty($supplier->id)) $texte = $langs->trans("ListOfSupplierProductForSupplier", $supplier->name); - else $texte = $langs->trans("List"); + if (!empty($supplier->id)) { + $texte = $langs->trans("ListOfSupplierProductForSupplier", $supplier->name); + } else { + $texte = $langs->trans("List"); + } llxHeader("", "", $texte); $param = "&sref=".$sref."&snom=".$snom."&fourn_id=".$fourn_id.(isset($type) ? "&amp;type=".$type : "").(empty($sRefSupplier) ? "" : "&amp;srefsupplier=".$sRefSupplier); - if ($optioncss != '') $param .= '&optioncss='.$optioncss; + if ($optioncss != '') { + $param .= '&optioncss='.$optioncss; + } print_barre_liste($texte, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, '', $num, $nbtotalofrecords); - if (!empty($catid)) - { + if (!empty($catid)) { print "<div id='ways'>"; $c = new Categorie($db); $ways = $c->print_all_ways(' &gt; ', 'fourn/product/list.php'); @@ -222,9 +239,13 @@ if ($resql) } print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">'; - if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + if ($optioncss != '') { + print '<input type="hidden" name="optioncss" value="'.$optioncss.'">'; + } print '<input type="hidden" name="token" value="'.newToken().'">'; - if ($fourn_id > 0) print '<input type="hidden" name="fourn_id" value="'.$fourn_id.'">'; + if ($fourn_id > 0) { + print '<input type="hidden" name="fourn_id" value="'.$fourn_id.'">'; + } print '<input type="hidden" name="sortfield" value="'.$sortfield.'">'; print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; print '<input type="hidden" name="page" value="'.$page.'">'; @@ -256,7 +277,9 @@ if ($resql) // add filters from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print '<td class="liste_titre maxwidthsearch">'; $searchpicto = $form->showFilterButtons(); @@ -276,13 +299,14 @@ if ($resql) // add header cells from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print_liste_field_titre('', $_SERVER["PHP_SELF"]); print "</tr>\n"; - while ($i < min($num, $limit)) - { + while ($i < min($num, $limit)) { $objp = $db->fetch_object($resql); $productstatic->id = $objp->rowid; @@ -307,7 +331,9 @@ if ($resql) $companystatic->name = $objp->name; $companystatic->id = $objp->socid; print '<td>'; - if ($companystatic->id > 0) print $companystatic->getNomUrl(1, 'supplier'); + if ($companystatic->id > 0) { + print $companystatic->getNomUrl(1, 'supplier'); + } print '</td>'; print '<td class="right">'.(isset($objp->price) ? price($objp->price) : '').'</td>'; @@ -319,7 +345,9 @@ if ($resql) // add additional columns from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $objp, $action); - if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } print $hookmanager->resPrint; print '<td class="right"></td>'; diff --git a/htdocs/fourn/recap-fourn.php b/htdocs/fourn/recap-fourn.php index 736a7bf4f90..06ad90ec858 100644 --- a/htdocs/fourn/recap-fourn.php +++ b/htdocs/fourn/recap-fourn.php @@ -32,8 +32,7 @@ $langs->loadLangs(array('bills', 'companies')); // Security check $socid = GETPOST("socid", 'int'); -if ($user->socid > 0) -{ +if ($user->socid > 0) { $action = ''; $socid = $user->socid; } @@ -51,22 +50,20 @@ $userstatic = new User($db); llxHeader(); -if ($socid > 0) -{ +if ($socid > 0) { $societe = new Societe($db); $societe->fetch($socid); /* - * Affichage onglets - */ + * Affichage onglets + */ $head = societe_prepare_head($societe); print dol_get_fiche_head($head, 'supplier', $langs->trans("ThirdParty"), 0, 'company'); dol_banner_tab($societe, 'socid', '', ($user->socid ? 0 : 1), 'rowid', 'nom'); print dol_get_fiche_end(); - if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->facture->lire) - { + if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) || !empty($conf->supplier_invoice->enabled)) && $user->rights->facture->lire) { // Invoice list print load_fiche_titre($langs->trans("SupplierPreview")); @@ -82,8 +79,7 @@ if ($socid > 0) $sql .= " ORDER BY f.datef DESC"; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num = $db->num_rows($resql); print '<tr class="liste_titre">'; @@ -96,22 +92,19 @@ if ($socid > 0) print '<td>&nbsp;</td>'; print '</tr>'; - if (!$num > 0) - { + if (!$num > 0) { print '<tr><td colspan="7">'.$langs->trans("NoInvoice").'</td></tr>'; } $solde = 0; // Boucle sur chaque facture - for ($i = 0; $i < $num; $i++) - { + for ($i = 0; $i < $num; $i++) { $objf = $db->fetch_object($resql); $fac = new FactureFournisseur($db); $ret = $fac->fetch($objf->facid); - if ($ret < 0) - { + if ($ret < 0) { print $fac->error."<br>"; continue; } @@ -144,13 +137,11 @@ if ($socid > 0) $sql .= " AND pf.fk_facturefourn = ".$fac->id; $resqlp = $db->query($sql); - if ($resqlp) - { + if ($resqlp) { $nump = $db->num_rows($resqlp); $j = 0; - while ($j < $nump) - { + while ($j < $nump) { $objp = $db->fetch_object($resqlp); // print '<tr class="oddeven">'; From 5d31a93bf0b4215e4b8009b63bf87bdf83915dbc Mon Sep 17 00:00:00 2001 From: daraelmin <daraelmin@gmail.com> Date: Fri, 26 Feb 2021 08:20:51 +0100 Subject: [PATCH 44/64] Fix #16420 - undefined $model_mail_selected_id Set $model_mail_selected_id to 0 when it is undefined --- htdocs/core/class/html.formmail.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index 2b551ed14d1..729be941d51 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -455,7 +455,7 @@ class FormMail extends Form // Zone to select email template if (count($modelmail_array) > 0) { - $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : $arraydefaultmessage->id; + $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : ( ($arraydefaultmessage->id) ? $arraydefaultmessage->id : 0 ); // If list of template is filled $out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n"; From e079ceb9c3d2e47ff4d00129ad37aa79fb9f421e Mon Sep 17 00:00:00 2001 From: daraelmin <daraelmin@gmail.com> Date: Fri, 26 Feb 2021 08:51:01 +0100 Subject: [PATCH 45/64] Fix #16420 undefined $model_mail_selected_id Set $model_mail_selected_id to 0 when it is undefined --- htdocs/core/class/html.formmail.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index e8b291ebfca..9c98a69d14a 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -488,7 +488,7 @@ class FormMail extends Form // Zone to select email template if (count($modelmail_array) > 0) { - $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : $arraydefaultmessage->id; + $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : ( ($arraydefaultmessage->id) ? $arraydefaultmessage->id : 0 ); // If list of template is filled $out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n"; From 8e8efce7d173346fe52c8374500b49190a83da6c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 10:23:53 +0100 Subject: [PATCH 46/64] Fix sql syntax --- htdocs/contact/class/contact.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 030d2417853..e0239da6142 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -1686,7 +1686,7 @@ class Contact extends CommonObject $this->db->begin(); - $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_soc=".intval($this->socid)." AND fk_socpeople=".$this->id; ; + $sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_contacts WHERE fk_soc=".((int) $this->socid)." AND fk_socpeople=".$this->id; dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); From 99a17cadb7377f82ecb409ee0304785c0fcc4675 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 10:25:08 +0100 Subject: [PATCH 47/64] Fix sql syntax --- htdocs/contact/class/contact.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index e0239da6142..06b436fc0c8 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -1704,7 +1704,7 @@ class Contact extends CommonObject $sql .= "fk_socpeople) "; $sql .= " VALUES (".$conf->entity.","; $sql .= "'".$this->db->idate(dol_now())."',"; - $sql .= $this->socid.", "; + $sql .= ((int) $this->socid).", "; $sql .= $valRoles." , "; $sql .= $this->id; $sql .= ")"; From 549136efebebdb1e33fbfe224c53b19a15afe6ed Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 10:25:30 +0100 Subject: [PATCH 48/64] Removed useless log --- htdocs/contact/class/contact.class.php | 1 - 1 file changed, 1 deletion(-) diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 06b436fc0c8..ac415afce6c 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -1708,7 +1708,6 @@ class Contact extends CommonObject $sql .= $valRoles." , "; $sql .= $this->id; $sql .= ")"; - dol_syslog(__METHOD__, LOG_DEBUG); $result = $this->db->query($sql); if (!$result) From 69c974800cf9b20e88a9ff0f175f4e52c4d9d543 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 10:30:30 +0100 Subject: [PATCH 49/64] Update html.formmail.class.php --- htdocs/core/class/html.formmail.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index 729be941d51..d505bd1fada 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -455,7 +455,7 @@ class FormMail extends Form // Zone to select email template if (count($modelmail_array) > 0) { - $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : ( ($arraydefaultmessage->id) ? $arraydefaultmessage->id : 0 ); + $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : (($arraydefaultmessage->id) ? $arraydefaultmessage->id : 0); // If list of template is filled $out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n"; From e0785ac5ef316cf737c6d5d7fcf200059646d52c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 10:31:02 +0100 Subject: [PATCH 50/64] Update html.formmail.class.php --- htdocs/core/class/html.formmail.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index d505bd1fada..46fcd5e331b 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -455,7 +455,7 @@ class FormMail extends Form // Zone to select email template if (count($modelmail_array) > 0) { - $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : (($arraydefaultmessage->id) ? $arraydefaultmessage->id : 0); + $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : ($arraydefaultmessage->id > 0 ? $arraydefaultmessage->id : 0); // If list of template is filled $out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n"; From e7ae2e65d7790afcf547da58bffc73dd14c57480 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 10:33:49 +0100 Subject: [PATCH 51/64] Update html.formmail.class.php --- htdocs/core/class/html.formmail.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php index 9c98a69d14a..4898e8d5872 100644 --- a/htdocs/core/class/html.formmail.class.php +++ b/htdocs/core/class/html.formmail.class.php @@ -488,7 +488,7 @@ class FormMail extends Form // Zone to select email template if (count($modelmail_array) > 0) { - $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : ( ($arraydefaultmessage->id) ? $arraydefaultmessage->id : 0 ); + $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : ($arraydefaultmessage->id > 0 ? $arraydefaultmessage->id : 0); // If list of template is filled $out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n"; From aba43b3e3560eecc333c705f29943a7deda367f3 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 10:44:52 +0100 Subject: [PATCH 52/64] Fix init before --- htdocs/core/ajax/objectonoff.php | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/htdocs/core/ajax/objectonoff.php b/htdocs/core/ajax/objectonoff.php index af8529cde28..05843abed9d 100644 --- a/htdocs/core/ajax/objectonoff.php +++ b/htdocs/core/ajax/objectonoff.php @@ -47,9 +47,19 @@ $id = GETPOST('id', 'int'); $value = GETPOST('value', 'int'); $field = GETPOST('field', 'alpha'); $element = GETPOST('element', 'alpha'); +$format = 'int'; $object = new GenericObject($db); +$tablename = $element; +if ($tablename == 'websitepage') { + $tablename = 'website_page'; +} + +$object->table_element = $tablename; +$object->id = $id; +$object->fields[$field] = array('type' => $format, 'enabled' => 1); + // Security check if (!empty($user->socid)) { $socid = $user->socid; @@ -69,9 +79,9 @@ top_httphead(); print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n"; if (in_array($field, array('status'))) { - $result = restrictedArea($user, $element, $id); + restrictedArea($user, $element, $id); } elseif ($element == 'product' && in_array($field, array('tosell', 'tobuy', 'tobatch'))) { // Special case for products - $result = restrictedArea($user, 'produit|service', $id, 'product&product', '', '', 'rowid'); + restrictedArea($user, 'produit|service', $id, 'product&product', '', '', 'rowid'); } else { accessforbidden("Bad value for combination of parameters element/field.", 0, 0, 1); exit; @@ -85,16 +95,5 @@ if (($action == 'set') && !empty($id)) { $triggerkey = 'COMPANY_UPDATE'; } - $tablename = $element; - if ($tablename == 'websitepage') { - $tablename = 'website_page'; - } - - $format = 'int'; - - $object->table_element = $tablename; - $object->id = $id; - $object->fields[$field] = array('type' => $format, 'enabled' => 1); - $object->setValueFrom($field, $value, $tablename, $id, $format, '', $user, $triggerkey); } From 2670d4fc17c70416074d190675fcaac30976eb9b Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 11:00:58 +0100 Subject: [PATCH 53/64] Look and feel v14 --- htdocs/core/class/html.form.class.php | 7 +++++++ htdocs/product/card.php | 1 - htdocs/product/list.php | 9 +-------- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php index 78342100fa3..483d356891c 100644 --- a/htdocs/core/class/html.form.class.php +++ b/htdocs/core/class/html.form.class.php @@ -316,6 +316,13 @@ class Form $arraylist[$tmp[0]] = $tmp[1]; } $ret .= $arraylist[$value]; + if ($htmlname == 'fk_product_type') { + if ($value == 0) { + $ret = img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"').$ret; + } else { + $ret = img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"').$ret; + } + } } elseif (preg_match('/^ckeditor/', $typeofdata)) { $tmpcontent = dol_htmlentitiesbr($value); if (!empty($conf->global->MAIN_DISABLE_NOTES_TAB)) { diff --git a/htdocs/product/card.php b/htdocs/product/card.php index 55c29aa1381..abf99c1b921 100644 --- a/htdocs/product/card.php +++ b/htdocs/product/card.php @@ -1813,7 +1813,6 @@ if (is_object($objcanvas) && $objcanvas->displayCanvasExists($action)) // Type if (!empty($conf->product->enabled) && !empty($conf->service->enabled)) { - // TODO change for compatibility with edit in place $typeformat = 'select;0:'.$langs->trans("Product").',1:'.$langs->trans("Service"); print '<tr><td class="titlefield">'; print (empty($conf->global->PRODUCT_DENY_CHANGE_PRODUCT_TYPE)) ? $form->editfieldkey("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat) : $langs->trans('Type'); diff --git a/htdocs/product/list.php b/htdocs/product/list.php index f7999860185..ff035dcdb9c 100644 --- a/htdocs/product/list.php +++ b/htdocs/product/list.php @@ -1113,17 +1113,10 @@ if ($resql) { print '<td class="center">'; $s = ''; - if ($obj->fk_product_type == 0) - { - //$s .= '<a class="product-type-back" title="'.$langs->trans("Product").'">'; + if ($obj->fk_product_type == 0) { $s .= img_picto($langs->trans("Product"), 'product', 'class="paddingleftonly paddingrightonly colorgrey"'); - //$s .= dol_substr($langs->trans("Product"), 0, 1); - //$s .= '</a>'; } else { - //$s .= '<span class="service-type-back" title="'.$langs->trans("Service").'">'; $s .= img_picto($langs->trans("Service"), 'service', 'class="paddingleftonly paddingrightonly colorgrey"'); - //$s .= dol_substr($langs->trans("Service"), 0, 1); - //$s .= '</a>'; } print $s; print '</td>'; From adc03135437dc19f6ed3c71f3c3a059990c65ebf Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 11:09:15 +0100 Subject: [PATCH 54/64] Fix lang --- htdocs/core/lib/product.lib.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/core/lib/product.lib.php b/htdocs/core/lib/product.lib.php index 9ce8d84d7e3..21ed3790418 100644 --- a/htdocs/core/lib/product.lib.php +++ b/htdocs/core/lib/product.lib.php @@ -381,7 +381,7 @@ function show_stats_for_company($product, $socid) $nblines++; $ret = $product->load_stats_proposal_supplier($socid); if ($ret < 0) dol_print_error($db); - $langs->load("propal"); + $langs->load("supplier_proposal"); print '<tr><td>'; print '<a href="supplier_proposal.php?id='.$product->id.'">'.img_object('', 'supplier_proposal').' '.$langs->trans("SupplierProposals").'</a>'; print '</td><td class="right">'; From 0f44bdb90fabecf66220ca9c2f41d0de2396b99c Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 11:27:03 +0100 Subject: [PATCH 55/64] Fix sql error --- htdocs/core/lib/product.lib.php | 24 ++++++++++++------------ htdocs/product/class/product.class.php | 2 +- htdocs/product/stats/bom.php | 4 ++-- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/htdocs/core/lib/product.lib.php b/htdocs/core/lib/product.lib.php index 21ed3790418..7012b6bff07 100644 --- a/htdocs/core/lib/product.lib.php +++ b/htdocs/core/lib/product.lib.php @@ -365,7 +365,7 @@ function show_stats_for_company($product, $socid) if ($ret < 0) dol_print_error($db); $langs->load("propal"); print '<tr><td>'; - print '<a href="propal.php?id='.$product->id.'">'.img_object('', 'propal').' '.$langs->trans("Proposals").'</a>'; + print '<a href="propal.php?id='.$product->id.'">'.img_object('', 'propal', 'class="paddingright"').$langs->trans("Proposals").'</a>'; print '</td><td class="right">'; print $product->stats_propale['customers']; print '</td><td class="right">'; @@ -383,7 +383,7 @@ function show_stats_for_company($product, $socid) if ($ret < 0) dol_print_error($db); $langs->load("supplier_proposal"); print '<tr><td>'; - print '<a href="supplier_proposal.php?id='.$product->id.'">'.img_object('', 'supplier_proposal').' '.$langs->trans("SupplierProposals").'</a>'; + print '<a href="supplier_proposal.php?id='.$product->id.'">'.img_object('', 'supplier_proposal', 'class="paddingright"').$langs->trans("SupplierProposals").'</a>'; print '</td><td class="right">'; print $product->stats_proposal_supplier['suppliers']; print '</td><td class="right">'; @@ -401,7 +401,7 @@ function show_stats_for_company($product, $socid) if ($ret < 0) dol_print_error($db); $langs->load("orders"); print '<tr><td>'; - print '<a href="commande.php?id='.$product->id.'">'.img_object('', 'order').' '.$langs->trans("CustomersOrders").'</a>'; + print '<a href="commande.php?id='.$product->id.'">'.img_object('', 'order', 'class="paddingright"').$langs->trans("CustomersOrders").'</a>'; print '</td><td class="right">'; print $product->stats_commande['customers']; print '</td><td class="right">'; @@ -419,7 +419,7 @@ function show_stats_for_company($product, $socid) if ($ret < 0) dol_print_error($db); $langs->load("orders"); print '<tr><td>'; - print '<a href="commande_fournisseur.php?id='.$product->id.'">'.img_object('', 'supplier_order').' '.$langs->trans("SuppliersOrders").'</a>'; + print '<a href="commande_fournisseur.php?id='.$product->id.'">'.img_object('', 'supplier_order', 'class="paddingright"').$langs->trans("SuppliersOrders").'</a>'; print '</td><td class="right">'; print $product->stats_commande_fournisseur['suppliers']; print '</td><td class="right">'; @@ -455,7 +455,7 @@ function show_stats_for_company($product, $socid) if ($ret < 0) dol_print_error($db); $langs->load("bills"); print '<tr><td>'; - print '<a href="facture_fournisseur.php?id='.$product->id.'">'.img_object('', 'supplier_invoice').' '.$langs->trans("SuppliersInvoices").'</a>'; + print '<a href="facture_fournisseur.php?id='.$product->id.'">'.img_object('', 'supplier_invoice', 'class="paddingright"').$langs->trans("SuppliersInvoices").'</a>'; print '</td><td class="right">'; print $product->stats_facture_fournisseur['suppliers']; print '</td><td class="right">'; @@ -474,7 +474,7 @@ function show_stats_for_company($product, $socid) if ($ret < 0) dol_print_error($db); $langs->load("contracts"); print '<tr><td>'; - print '<a href="contrat.php?id='.$product->id.'">'.img_object('', 'contract').' '.$langs->trans("Contracts").'</a>'; + print '<a href="contrat.php?id='.$product->id.'">'.img_object('', 'contract', 'class="paddingright"').$langs->trans("Contracts").'</a>'; print '</td><td class="right">'; print $product->stats_contrat['customers']; print '</td><td class="right">'; @@ -496,15 +496,15 @@ function show_stats_for_company($product, $socid) $langs->load("mrp"); print '<tr><td>'; - print '<a href="bom.php?id='.$product->id.'">'.img_object('', 'mrp').' '.$langs->trans("BOM").'</a>'; + print '<a href="bom.php?id='.$product->id.'">'.img_object('', 'bom', 'class="paddingright"').$langs->trans("BOM").'</a>'; print '</td><td class="right">'; print '</td><td class="right">'; - print $form->textwithpicto($product->stats_bom['nb_toproduce'], $langs->trans("QtyToProduce")); - print $form->textwithpicto($product->stats_bom['nb_toconsume'], $langs->trans("ToConsume")); + print $form->textwithpicto($product->stats_bom['nb_toconsume'], $langs->trans("RowMaterial")); + print $form->textwithpicto($product->stats_bom['nb_toproduce'], $langs->trans("Finished")); print '</td><td class="right">'; - print $form->textwithpicto($product->stats_bom['qty_toproduce'], $langs->trans("QtyToProduce")); - print $form->textwithpicto($product->stats_bom['qty_toconsume'], $langs->trans("ToConsume")); + print $form->textwithpicto($product->stats_bom['qty_toconsume'], $langs->trans("RowMaterial")); + print $form->textwithpicto($product->stats_bom['qty_toproduce'], $langs->trans("Finished")); print '</td>'; print '</tr>'; } @@ -519,7 +519,7 @@ function show_stats_for_company($product, $socid) } $langs->load("mrp"); print '<tr><td>'; - print '<a href="mo.php?id='.$product->id.'">'.img_object('', 'mrp').' '.$langs->trans("MO").'</a>'; + print '<a href="mo.php?id='.$product->id.'">'.img_object('', 'mrp', 'class="paddingright"').$langs->trans("MO").'</a>'; print '</td><td class="right">'; print $form->textwithpicto($product->stats_mo['customers_toconsume'], $langs->trans("ToConsume")); print $form->textwithpicto($product->stats_mo['customers_consumed'], $langs->trans("QtyAlreadyConsumed")); diff --git a/htdocs/product/class/product.class.php b/htdocs/product/class/product.class.php index f8286216e57..3be810a2e8e 100644 --- a/htdocs/product/class/product.class.php +++ b/htdocs/product/class/product.class.php @@ -2464,7 +2464,7 @@ class Product extends CommonObject $this->stats_bom['qty_toconsume'] = 0; $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,"; - $sql .= " b.qty as qty_toproduce"; + $sql .= " SUM(b.qty) as qty_toproduce"; $sql .= " FROM ".MAIN_DB_PREFIX."bom_bom as b"; $sql .= " INNER JOIN ".MAIN_DB_PREFIX."bom_bomline as bl ON bl.fk_bom=b.rowid"; $sql .= " WHERE "; diff --git a/htdocs/product/stats/bom.php b/htdocs/product/stats/bom.php index 1582646cd8a..d1254a65b1e 100644 --- a/htdocs/product/stats/bom.php +++ b/htdocs/product/stats/bom.php @@ -244,8 +244,8 @@ if ($id > 0 || !empty($ref)) print '<tr class="liste_titre">'; print_liste_field_titre("Ref", $_SERVER["PHP_SELF"], "b.rowid", "", "&amp;id=".$product->id, '', $sortfield, $sortorder); print_liste_field_titre("Date", $_SERVER["PHP_SELF"], "b.date_valid", "", "&amp;id=".$product->id, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre("ToConsume", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); - print_liste_field_titre("QtyToProduce", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre("RowMaterial", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); + print_liste_field_titre("Finished", $_SERVER["PHP_SELF"], "", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "b.status", "", "&amp;id=".$product->id, '', $sortfield, $sortorder, 'center '); print "</tr>\n"; From 60016cc3f3c50944708f3c01d3418e49063a11ab Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 11:29:16 +0100 Subject: [PATCH 56/64] Fix phpcs --- htdocs/main.inc.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/htdocs/main.inc.php b/htdocs/main.inc.php index 740323a644b..f72a933c688 100644 --- a/htdocs/main.inc.php +++ b/htdocs/main.inc.php @@ -425,7 +425,7 @@ if (!defined('NOTOKENRENEWAL')) { // Check token if ((!defined('NOCSRFCHECK') && empty($dolibarr_nocsrfcheck) && !empty($conf->global->MAIN_SECURITY_CSRF_WITH_TOKEN)) || defined('CSRFCHECK_WITH_TOKEN')) { // Check validity of token, only if option MAIN_SECURITY_CSRF_WITH_TOKEN enabled or if constant CSRFCHECK_WITH_TOKEN is set into page -// Check all cases that need a token (all POST actions, all actions and mass actions on pages with CSRFCHECK_WITH_TOKEN set, all sensitive GET actions) + // Check all cases that need a token (all POST actions, all actions and mass actions on pages with CSRFCHECK_WITH_TOKEN set, all sensitive GET actions) if ($_SERVER['REQUEST_METHOD'] == 'POST' || ((GETPOSTISSET('action') || GETPOSTISSET('massaction')) && defined('CSRFCHECK_WITH_TOKEN')) || in_array(GETPOST('action', 'aZ09'), array('add', 'addtimespent', 'update', 'install', 'delete', 'deletefilter', 'deleteoperation', 'deleteprof', 'deletepayment', 'confirm_create_user', 'confirm_create_thirdparty', 'confirm_reject_check'))) { @@ -712,7 +712,7 @@ if (!defined('NOLOGIN')) { // End test login / passwords if (!$login || (in_array('ldap', $authmode) && empty($passwordtotest))) { // With LDAP we refused empty password because some LDAP are "opened" for anonymous access so connexion is a success. - // No data to test login, so we show the login page. + // No data to test login, so we show the login page. dol_syslog("--- Access to ".$_SERVER["PHP_SELF"]." - action=".GETPOST('action', 'aZ09')." - actionlogin=".GETPOST('actionlogin', 'aZ09')." - showing the login form and exit"); if (defined('NOREDIRECTBYMAINTOLOGIN')) { return 'ERROR_NOT_LOGGED'; @@ -1051,7 +1051,7 @@ if (!empty($conf->dol_use_jmobile) && in_array($conf->theme, array('bureau2crea' if (!defined('NOREQUIRETRAN')) { if (!GETPOST('lang', 'aZ09')) { // If language was not forced on URL - // If user has chosen its own language + // If user has chosen its own language if (!empty($user->conf->MAIN_LANG_DEFAULT)) { // If different than current language //print ">>>".$langs->getDefaultLang()."-".$user->conf->MAIN_LANG_DEFAULT; @@ -3073,7 +3073,7 @@ if (!function_exists("llxFooter")) { if (strpos('alpha', DOL_VERSION) > 0 && !$forceping) { print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. It is an alpha version -->\n"; } elseif (empty($_COOKIE['DOLINSTALLNOPING_'.$hash_unique_id]) || $forceping) { // Cookie is set when we uncheck the checkbox in the installation wizard. - // MAIN_LAST_PING_KO_DATE + // MAIN_LAST_PING_KO_DATE // Disable ping if MAIN_LAST_PING_KO_DATE is set and is recent if (!empty($conf->global->MAIN_LAST_PING_KO_DATE) && substr($conf->global->MAIN_LAST_PING_KO_DATE, 0, 6) == dol_print_date(dol_now(), '%Y%m') && !$forceping) { print "\n<!-- NO JS CODE TO ENABLE the anonymous Ping. An error already occured this month, we will try later. -->\n"; From badd46e2897b49ac777695e3dbf43a842c964781 Mon Sep 17 00:00:00 2001 From: Juanjo Menent <jmenent@2byte.es> Date: Fri, 26 Feb 2021 11:53:23 +0100 Subject: [PATCH 57/64] FIX: Bad project filter in ticket list --- htdocs/ticket/list.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/ticket/list.php b/htdocs/ticket/list.php index 565d1279037..1a276c75f5f 100644 --- a/htdocs/ticket/list.php +++ b/htdocs/ticket/list.php @@ -352,7 +352,7 @@ foreach ($search as $key => $val) if (count($newarrayofstatus)) $sql .= natural_search($key, join(',', $newarrayofstatus), 2); continue; } - if ($key == 'fk_user_assign' || $key == 'fk_user_create' || $key = 'fk_project') + if ($key == 'fk_user_assign' || $key == 'fk_user_create' || $key == 'fk_project') { if ($search[$key] > 0) $sql .= natural_search($key, $search[$key], 2); continue; From 256001ebd6522b6780dc5737d769739bb3d099bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= <frederic.france@free.fr> Date: Fri, 26 Feb 2021 12:03:07 +0100 Subject: [PATCH 58/64] code syntax website directory --- htdocs/website/class/website.class.php | 228 ++- htdocs/website/class/websitepage.class.php | 98 +- htdocs/website/index.php | 1753 +++++++++----------- htdocs/website/samples/wrapper.php | 148 +- htdocs/website/websiteaccount_card.php | 162 +- 5 files changed, 1161 insertions(+), 1228 deletions(-) diff --git a/htdocs/website/class/website.class.php b/htdocs/website/class/website.class.php index d0ffc3ccc03..fe2e6aab4cf 100644 --- a/htdocs/website/class/website.class.php +++ b/htdocs/website/class/website.class.php @@ -244,7 +244,9 @@ class Website extends CommonObject if (is_array($tmplangarray)) { dol_mkdir($conf->website->dir_output.'/'.$this->ref); foreach ($tmplangarray as $val) { - if (trim($val) == $this->lang) continue; + if (trim($val) == $this->lang) { + continue; + } dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val)); } } @@ -540,7 +542,9 @@ class Website extends CommonObject if (is_array($tmplangarray)) { dol_mkdir($conf->website->dir_output.'/'.$this->ref); foreach ($tmplangarray as $val) { - if (trim($val) == $this->lang) continue; + if (trim($val) == $this->lang) { + continue; + } dol_mkdir($conf->website->dir_output.'/'.$this->ref.'/'.trim($val)); } } @@ -603,8 +607,7 @@ class Website extends CommonObject } } - if (!$error && !empty($this->ref)) - { + if (!$error && !empty($this->ref)) { $pathofwebsite = DOL_DATA_ROOT.'/website/'.$this->ref; dol_delete_dir_recursive($pathofwebsite); @@ -645,8 +648,7 @@ class Website extends CommonObject $object = new self($this->db); // Check no site with ref exists - if ($object->fetch(0, $newref) > 0) - { + if ($object->fetch(0, $newref) > 0) { $this->error = 'ErrorNewRefIsAlreadyUsed'; return -1; } @@ -678,7 +680,9 @@ class Website extends CommonObject $object->fk_user_creat = $user->id; $object->position = ((int) $object->position) + 1; $object->status = self::STATUS_DRAFT; - if (empty($object->lang)) $object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages + if (empty($object->lang)) { + $object->lang = substr($langs->defaultlang, 0, 2); // Should not happen. Protection for corrupted site with no languages + } // Create clone $object->context['createfromclone'] = 'createfromclone'; @@ -690,15 +694,13 @@ class Website extends CommonObject dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR); } - if (!$error) - { + if (!$error) { dolCopyDir($pathofwebsiteold, $pathofwebsitenew, $conf->global->MAIN_UMASK, 0, null, 2); // Check symlink to medias and restore it if ko $pathtomedias = DOL_DATA_ROOT.'/medias'; // Target $pathtomediasinwebsite = $pathofwebsitenew.'/medias'; // Source / Link name - if (!is_link(dol_osencode($pathtomediasinwebsite))) - { + if (!is_link(dol_osencode($pathtomediasinwebsite))) { dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); @@ -718,8 +720,7 @@ class Website extends CommonObject // Duplicate pages $objectpages = new WebsitePage($this->db); $listofpages = $objectpages->fetchAll($fromid); - foreach ($listofpages as $pageid => $objectpageold) - { + foreach ($listofpages as $pageid => $objectpageold) { // Delete old file $filetplold = $pathofwebsitenew.'/page'.$pageid.'.tpl.php'; dol_delete_file($filetplold); @@ -728,43 +729,41 @@ class Website extends CommonObject $objectpagenew = $objectpageold->createFromClone($user, $pageid, $objectpageold->pageurl, '', 0, $object->id, 1); //print $pageid.' = '.$objectpageold->pageurl.' -> '.$objectpagenew->id.' = '.$objectpagenew->pageurl.'<br>'; - if (is_object($objectpagenew) && $objectpagenew->pageurl) - { + if (is_object($objectpagenew) && $objectpagenew->pageurl) { $filealias = $pathofwebsitenew.'/'.$objectpagenew->pageurl.'.php'; $filetplnew = $pathofwebsitenew.'/page'.$objectpagenew->id.'.tpl.php'; // Save page alias $result = dolSavePageAlias($filealias, $object, $objectpagenew); - if (!$result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.$filealias, null, 'errors'); + } $result = dolSavePageContent($filetplnew, $object, $objectpagenew); - if (!$result) setEventMessages('Failed to write file '.$filetplnew, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.$filetplnew, null, 'errors'); + } - if ($pageid == $oldidforhome) - { + if ($pageid == $oldidforhome) { $newidforhome = $objectpagenew->id; } - } - else { + } else { setEventMessages($objectpageold->error, $objectpageold->errors, 'errors'); $error++; } } } - if (!$error) - { + if (!$error) { // Restore id of home page $object->fk_default_home = $newidforhome; $res = $object->update($user); - if (!($res > 0)) - { + if (!($res > 0)) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } - if (!$error) - { + if (!$error) { $filetpl = $pathofwebsitenew.'/page'.$newidforhome.'.tpl.php'; $filewrapper = $pathofwebsitenew.'/wrapper.php'; @@ -821,10 +820,11 @@ class Website extends CommonObject $linkstart = $linkend = ''; - if ($withpicto) - { + if ($withpicto) { $result .= ($linkstart.img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? '' : 'class="classfortooltip"')).$linkend); - if ($withpicto != 2) $result .= ' '; + if ($withpicto != 2) { + $result .= ' '; + } } $result .= $linkstart.$this->ref.$linkend; return $result; @@ -854,8 +854,7 @@ class Website extends CommonObject // phpcs:enable global $langs; - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled'); @@ -865,7 +864,9 @@ class Website extends CommonObject } $statusType = 'status5'; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } @@ -909,16 +910,14 @@ class Website extends CommonObject $website = $this; - if (empty($website->id) || empty($website->ref)) - { + if (empty($website->id) || empty($website->ref)) { setEventMessages("Website id or ref is not defined", null, 'errors'); return ''; } dol_syslog("Create temp dir ".$conf->website->dir_temp); dol_mkdir($conf->website->dir_temp); - if (!is_writable($conf->website->dir_temp)) - { + if (!is_writable($conf->website->dir_temp)) { setEventMessages("Temporary dir ".$conf->website->dir_temp." is not writable", null, 'errors'); return ''; } @@ -928,8 +927,7 @@ class Website extends CommonObject dol_syslog("Clear temp dir ".$destdir); $count = 0; $countreallydeleted = 0; $counttodelete = dol_delete_dir_recursive($destdir, $count, 1, 0, $countreallydeleted); - if ($counttodelete != $countreallydeleted) - { + if ($counttodelete != $countreallydeleted) { setEventMessages("Failed to clean temp directory ".$destdir, null, 'errors'); return ''; } @@ -987,8 +985,7 @@ class Website extends CommonObject // Build sql file $filesql = $conf->website->dir_temp.'/'.$website->ref.'/website_pages.sql'; $fp = fopen($filesql, "w"); - if (empty($fp)) - { + if (empty($fp)) { setEventMessages("Failed to create file ".$filesql, null, 'errors'); return ''; } @@ -998,20 +995,16 @@ class Website extends CommonObject // Assign ->newid and ->newfk_page $i = 1; - foreach ($listofpages as $pageid => $objectpageold) - { + foreach ($listofpages as $pageid => $objectpageold) { $objectpageold->newid = $i; $i++; } $i = 1; - foreach ($listofpages as $pageid => $objectpageold) - { + foreach ($listofpages as $pageid => $objectpageold) { // Search newid $newfk_page = 0; - foreach ($listofpages as $pageid2 => $objectpageold2) - { - if ($pageid2 == $objectpageold->fk_page) - { + foreach ($listofpages as $pageid2 => $objectpageold2) { + if ($pageid2 == $objectpageold->fk_page) { $newfk_page = $objectpageold2->newid; break; } @@ -1019,8 +1012,7 @@ class Website extends CommonObject $objectpageold->newfk_page = $newfk_page; $i++; } - foreach ($listofpages as $pageid => $objectpageold) - { + foreach ($listofpages as $pageid => $objectpageold) { $allaliases = $objectpageold->pageurl; $allaliases .= ($objectpageold->aliasalt ? ','.$objectpageold->aliasalt : ''); @@ -1081,8 +1073,7 @@ class Website extends CommonObject // Add line to update home page id during import //var_dump($this->fk_default_home.' - '.$objectpageold->id.' - '.$objectpageold->newid);exit; - if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) // This is the record with home page - { + if ($this->fk_default_home > 0 && ($objectpageold->id == $this->fk_default_home) && ($objectpageold->newid > 0)) { // This is the record with home page // Warning: We must keep llx_ here. It is a generic SQL. $line = "UPDATE llx_website SET fk_default_home = ".($objectpageold->newid > 0 ? $this->db->escape($objectpageold->newid)."__+MAX_llx_website_page__" : "null")." WHERE rowid = __WEBSITE_ID__;"; $line .= "\n"; @@ -1091,8 +1082,9 @@ class Website extends CommonObject } fclose($fp); - if (!empty($conf->global->MAIN_UMASK)) + if (!empty($conf->global->MAIN_UMASK)) { @chmod($filesql, octdec($conf->global->MAIN_UMASK)); + } // Build zip file $filedir = $conf->website->dir_temp.'/'.$website->ref.'/.'; @@ -1102,11 +1094,9 @@ class Website extends CommonObject dol_delete_file($fileglob, 0); $result = dol_compress_file($filedir, $filename, 'zip'); - if ($result > 0) - { + if ($result > 0) { return $filename; - } - else { + } else { global $errormsg; $this->error = $errormsg; return ''; @@ -1127,8 +1117,7 @@ class Website extends CommonObject $error = 0; $object = $this; - if (empty($object->ref)) - { + if (empty($object->ref)) { $this->error = 'Function importWebSite called on object not loaded (object->ref is empty)'; return -1; } @@ -1137,16 +1126,14 @@ class Website extends CommonObject dol_mkdir($conf->website->dir_temp.'/'.$object->ref); $filename = basename($pathtofile); - if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) - { + if (!preg_match('/^website_(.*)-(.*)$/', $filename, $reg)) { $this->errors[] = 'Bad format for filename '.$filename.'. Must be website_XXX-VERSION.'; return -1; } $result = dol_uncompress($pathtofile, $conf->website->dir_temp.'/'.$object->ref); - if (!empty($result['error'])) - { + if (!empty($result['error'])) { $this->errors[] = 'Failed to unzip file '.$pathtofile.'.'; return -1; } @@ -1172,8 +1159,7 @@ class Website extends CommonObject // Now generate the master.inc.php page $filemaster = $conf->website->dir_output.'/'.$object->ref.'/master.inc.php'; $result = dolSaveMasterFile($filemaster); - if (!$result) - { + if (!$result) { $this->errors[] = 'Failed to write file '.$filemaster; $error++; } @@ -1190,16 +1176,14 @@ class Website extends CommonObject // Search the $maxrowid because we need it later $sqlgetrowid = 'SELECT MAX(rowid) as max from '.MAIN_DB_PREFIX.'website_page'; $resql = $this->db->query($sqlgetrowid); - if ($resql) - { + if ($resql) { $obj = $this->db->fetch_object($resql); $maxrowid = $obj->max; } // Load sql record $runsql = run_sql($sqlfile, 1, '', 0, '', 'none', 0, 1); // The maxrowid of table is searched into this function two - if ($runsql <= 0) - { + if ($runsql <= 0) { $this->errors[] = 'Failed to load sql file '.$sqlfile; $error++; } @@ -1208,16 +1192,13 @@ class Website extends CommonObject // Make replacement of IDs $fp = fopen($sqlfile, "r"); - if ($fp) - { - while (!feof($fp)) - { + if ($fp) { + while (!feof($fp)) { $reg = array(); // Warning fgets with second parameter that is null or 0 hang. $buf = fgets($fp, 65000); - if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) - { + if (preg_match('/^-- Page ID (\d+)\s[^\s]+\s(\d+).*Aliases\s(.*)\s--;/i', $buf, $reg)) { $oldid = $reg[1]; $newid = ($reg[2] + $maxrowid); $aliasesarray = explode(',', $reg[3]); @@ -1237,12 +1218,9 @@ class Website extends CommonObject } // Regenerate alternative aliases pages - if (is_array($aliasesarray)) - { - foreach ($aliasesarray as $aliasshortcuttocreate) - { - if (trim($aliasshortcuttocreate)) - { + if (is_array($aliasesarray)) { + foreach ($aliasesarray as $aliasshortcuttocreate) { + if (trim($aliasshortcuttocreate)) { $filealias = $conf->website->dir_output.'/'.$object->ref.'/'.trim($aliasshortcuttocreate).'.php'; $result = dolSavePageAlias($filealias, $object, $objectpagestatic); if (!$result) { @@ -1274,12 +1252,10 @@ class Website extends CommonObject $pathofwebsite = $conf->website->dir_output.'/'.$object->ref; dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$object->fk_default_home.'.tpl.php', $pathofwebsite.'/wrapper.php'); - if ($error) - { + if ($error) { $this->db->rollback(); return -1; - } - else { + } else { $this->db->commit(); return $object->id; } @@ -1298,8 +1274,7 @@ class Website extends CommonObject $error = 0; $object = $this; - if (empty($object->ref)) - { + if (empty($object->ref)) { $this->error = 'Function rebuildWebSiteFiles called on object not loaded (object->ref is empty)'; return -1; } @@ -1386,7 +1361,9 @@ class Website extends CommonObject { global $websitepagefile, $website; - if (!is_object($weblangs)) return 'ERROR componentSelectLang called with parameter $weblangs not defined'; + if (!is_object($weblangs)) { + return 'ERROR componentSelectLang called with parameter $weblangs not defined'; + } $arrayofspecialmainlanguages = array( 'en'=>'en_US', @@ -1419,51 +1396,55 @@ class Website extends CommonObject $tmppage = new WebsitePage($this->db); $pageid = 0; - if (!empty($websitepagefile)) - { + if (!empty($websitepagefile)) { $websitepagefileshort = basename($websitepagefile); - if ($websitepagefileshort == 'index.php') $pageid = $website->fk_default_home; - else $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort); - if ($pageid > 0) - { + if ($websitepagefileshort == 'index.php') { + $pageid = $website->fk_default_home; + } else { + $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), $websitepagefileshort); + } + if ($pageid > 0) { $tmppage->fetch($pageid); } } // Fill $languagecodes array with existing translation, nothing if none - if (!is_array($languagecodes) && $pageid > 0) - { + if (!is_array($languagecodes) && $pageid > 0) { $languagecodes = array(); $sql = "SELECT wp.rowid, wp.lang, wp.pageurl, wp.fk_page"; $sql .= " FROM ".MAIN_DB_PREFIX."website_page as wp"; $sql .= " WHERE wp.fk_website = ".$website->id; $sql .= " AND (wp.fk_page = ".$pageid." OR wp.rowid = ".$pageid; - if ($tmppage->fk_page > 0) $sql .= " OR wp.fk_page = ".$tmppage->fk_page." OR wp.rowid = ".$tmppage->fk_page; + if ($tmppage->fk_page > 0) { + $sql .= " OR wp.fk_page = ".$tmppage->fk_page." OR wp.rowid = ".$tmppage->fk_page; + } $sql .= ")"; $resql = $this->db->query($sql); - if ($resql) - { - while ($obj = $this->db->fetch_object($resql)) - { + if ($resql) { + while ($obj = $this->db->fetch_object($resql)) { $newlang = $obj->lang; - if ($obj->rowid == $pageid) $newlang = $obj->lang; - if (!in_array($newlang, $languagecodes)) $languagecodes[] = $newlang; + if ($obj->rowid == $pageid) { + $newlang = $obj->lang; + } + if (!in_array($newlang, $languagecodes)) { + $languagecodes[] = $newlang; + } } } } // Now $languagecodes is always an array. Example array('en', 'fr', 'es'); $languagecodeselected = substr($weblangs->defaultlang, 0, 2); // Because we must init with a value, but real value is the lang of main parent container - if (!empty($websitepagefile)) - { + if (!empty($websitepagefile)) { $pageid = str_replace(array('.tpl.php', 'page'), array('', ''), basename($websitepagefile)); - if ($pageid > 0) - { + if ($pageid > 0) { $pagelang = substr($tmppage->lang, 0, 2); $languagecodeselected = substr($pagelang, 0, 2); - if (!in_array($pagelang, $languagecodes)) $languagecodes[] = $pagelang; // We add language code of page into combo list + if (!in_array($pagelang, $languagecodes)) { + $languagecodes[] = $pagelang; // We add language code of page into combo list + } } } @@ -1474,7 +1455,9 @@ class Website extends CommonObject $url = preg_replace('/(\?|&)l=([a-zA-Z_]*)/', '', $url); // We remove param l from url //$url = preg_replace('/(\?|&)lang=([a-zA-Z_]*)/', '', $url); // We remove param lang from url $url .= (preg_match('/\?/', $url) ? '&' : '?').'l='; - if (!preg_match('/^\//', $url)) $url = '/'.$url; + if (!preg_match('/^\//', $url)) { + $url = '/'.$url; + } $HEIGHTOPTION = 40; $MAXHEIGHT = 4 * $HEIGHTOPTION; @@ -1504,8 +1487,7 @@ class Website extends CommonObject $out .= '</style>'; $out .= '<ul class="componentSelectLang'.$htmlname.($morecss ? ' '.$morecss : '').'">'; - if ($languagecodeselected) - { + if ($languagecodeselected) { // Convert $languagecodeselected into a long language code if (strlen($languagecodeselected) == 2) { $languagecodeselected = (empty($arrayofspecialmainlanguages[$languagecodeselected]) ? $languagecodeselected.'_'.strtoupper($languagecodeselected) : $arrayofspecialmainlanguages[$languagecodeselected]); @@ -1513,28 +1495,34 @@ class Website extends CommonObject $countrycode = strtolower(substr($languagecodeselected, -2)); $label = $weblangs->trans("Language_".$languagecodeselected); - if ($countrycode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); + if ($countrycode == 'us') { + $label = preg_replace('/\s*\(.*\)/', '', $label); + } $out .= '<a href="'.$url.substr($languagecodeselected, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>'; $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />'; $out .= '</li></a>'; } $i = 0; - if (is_array($languagecodes)) - { - foreach ($languagecodes as $languagecode) - { + if (is_array($languagecodes)) { + foreach ($languagecodes as $languagecode) { // Convert $languagecode into a long language code if (strlen($languagecode) == 2) { $languagecode = (empty($arrayofspecialmainlanguages[$languagecode]) ? $languagecode.'_'.strtoupper($languagecode) : $arrayofspecialmainlanguages[$languagecode]); } - if ($languagecode == $languagecodeselected) continue; // Already output + if ($languagecode == $languagecodeselected) { + continue; // Already output + } $countrycode = strtolower(substr($languagecode, -2)); $label = $weblangs->trans("Language_".$languagecode); - if ($countrycode == 'us') $label = preg_replace('/\s*\(.*\)/', '', $label); + if ($countrycode == 'us') { + $label = preg_replace('/\s*\(.*\)/', '', $label); + } $out .= '<a href="'.$url.substr($languagecode, 0, 2).'"><li><img height="12px" src="/medias/image/common/flags/'.$countrycode.'.png" style="margin-right: 5px;"/><span class="websitecomponentlilang">'.$label.'</span>'; - if (empty($i) && empty($languagecodeselected)) $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />'; + if (empty($i) && empty($languagecodeselected)) { + $out .= '<span class="fa fa-caret-down" style="padding-left: 5px;" />'; + } $out .= '</li></a>'; $i++; } diff --git a/htdocs/website/class/websitepage.class.php b/htdocs/website/class/websitepage.class.php index bacc4664791..c6c4d81d04e 100644 --- a/htdocs/website/class/websitepage.class.php +++ b/htdocs/website/class/websitepage.class.php @@ -106,9 +106,9 @@ class WebsitePage extends CommonObject */ public $author_alias; - /** - * @var string path of external object - */ + /** + * @var string path of external object + */ public $object_type; /** @@ -229,7 +229,9 @@ class WebsitePage extends CommonObject { $this->description = dol_trunc($this->description, 255, 'right', 'utf-8', 1); $this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1); - if ($this->aliasalt) $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + if ($this->aliasalt) { + $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + } // Remove spaces and be sure we have main language only $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en @@ -281,12 +283,12 @@ class WebsitePage extends CommonObject $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t'; //$sql .= ' WHERE entity IN ('.getEntity('website').')'; // entity is on website level $sql .= ' WHERE 1 = 1'; - if ($id > 0) - { + if ($id > 0) { $sql .= ' AND t.rowid = '.$id; - } - else { - if ($id < 0) $sql .= ' AND t.rowid <> '.abs($id); + } else { + if ($id < 0) { + $sql .= ' AND t.rowid <> '.abs($id); + } if (null !== $website_id) { $sql .= " AND t.fk_website = '".$this->db->escape($website_id)."'"; if ($page) { @@ -295,12 +297,18 @@ class WebsitePage extends CommonObject $tmppage = explode('/', $page); if (!empty($tmppage[1])) { $pagetouse = $tmppage[1]; - if (strlen($tmppage[0])) $langtouse = $tmppage[0]; + if (strlen($tmppage[0])) { + $langtouse = $tmppage[0]; + } } $sql .= " AND t.pageurl = '".$this->db->escape($pagetouse)."'"; - if ($langtouse) $sql .= " AND t.lang = '".$this->db->escape($langtouse)."'"; + if ($langtouse) { + $sql .= " AND t.lang = '".$this->db->escape($langtouse)."'"; + } + } + if ($aliasalt) { + $sql .= " AND (t.aliasalt LIKE '%,".$this->db->escape($aliasalt).",%' OR t.aliasalt LIKE '%, ".$this->db->escape($aliasalt).",%')"; } - if ($aliasalt) $sql .= " AND (t.aliasalt LIKE '%,".$this->db->escape($aliasalt).",%' OR t.aliasalt LIKE '%, ".$this->db->escape($aliasalt).",%')"; } } $sql .= $this->db->plimit(1); @@ -419,7 +427,9 @@ class WebsitePage extends CommonObject $listoflang[] = "'".$this->db->escape(substr(str_replace("'", '', $tmpvalue), 0, 2))."'"; } $stringtouse = $key." IN (".join(',', $listoflang).")"; - if ($foundnull) $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; + if ($foundnull) { + $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; + } $sqlwhere[] = $stringtouse; } else { $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; @@ -441,8 +451,7 @@ class WebsitePage extends CommonObject if ($resql) { $num = $this->db->num_rows($resql); - while ($obj = $this->db->fetch_object($resql)) - { + while ($obj = $this->db->fetch_object($resql)) { $record = new self($this->db); $record->id = $obj->rowid; @@ -520,7 +529,9 @@ class WebsitePage extends CommonObject $listoflang[] = "'".$this->db->escape(substr(str_replace("'", '', $tmpvalue), 0, 2))."'"; } $stringtouse = $key." IN (".join(',', $listoflang).")"; - if ($foundnull) $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; + if ($foundnull) { + $stringtouse = '('.$stringtouse.' OR '.$key.' IS NULL)'; + } $sqlwhere[] = $stringtouse; } else { $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\''; @@ -561,7 +572,9 @@ class WebsitePage extends CommonObject { $this->description = dol_trunc($this->description, 255, 'right', 'utf-8', 1); $this->keywords = dol_trunc($this->keywords, 255, 'right', 'utf-8', 1); - if ($this->aliasalt) $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + if ($this->aliasalt) { + $this->aliasalt = ','.preg_replace('/,+$/', '', preg_replace('/^,+/', '', $this->aliasalt)).','; // content in database must be ',xxx,...,yyy,' + } // Remove spaces and be sure we have main language only $this->lang = preg_replace('/[_-].*$/', '', trim($this->lang)); // en_US or en-US -> en @@ -595,8 +608,7 @@ class WebsitePage extends CommonObject // Delete all child tables if (!$error) { - foreach ($this->childtablesoncascade as $table) - { + foreach ($this->childtablesoncascade as $table) { $sql = "DELETE FROM ".MAIN_DB_PREFIX.$table; $sql .= " WHERE fk_website_page = ".(int) $this->id; @@ -611,19 +623,16 @@ class WebsitePage extends CommonObject if (!$error) { $result = $this->deleteCommon($user, $trigger); - if ($result <= 0) - { + if ($result <= 0) { $error++; } } - if (!$error) - { + if (!$error) { $websiteobj = new Website($this->db); $result = $websiteobj->fetch($this->fk_website); - if ($result > 0) - { + if ($result > 0) { global $dolibarr_main_data_root; $pathofwebsite = $dolibarr_main_data_root.'/website/'.$websiteobj->ref; @@ -696,10 +705,17 @@ class WebsitePage extends CommonObject $object->date_creation = $now; $object->title = ($newtitle == '1' ? $object->title : ($newtitle ? $newtitle : $object->title)); $object->description = $object->title; - if (!empty($newlang)) $object->lang = $newlang; - if ($istranslation) $object->fk_page = $fromid; - else $object->fk_page = 0; - if (!empty($newwebsite)) $object->fk_website = $newwebsite; + if (!empty($newlang)) { + $object->lang = $newlang; + } + if ($istranslation) { + $object->fk_page = $fromid; + } else { + $object->fk_page = 0; + } + if (!empty($newwebsite)) { + $object->fk_website = $newwebsite; + } $object->import_key = ''; // Create clone @@ -755,17 +771,16 @@ class WebsitePage extends CommonObject $url = DOL_URL_ROOT.'/website/index.php?websiteid='.$this->fk_website.'&pageid='.$this->id; $linkclose = ''; - if (empty($notooltip)) - { - if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) - { + if (empty($notooltip)) { + if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) { $label = $langs->trans("ShowMyObject"); $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"'; } $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"'; $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"'; + } else { + $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); } - else $linkclose = ($morecss ? ' class="'.$morecss.'"' : ''); $linkstart = '<a href="'.$url.'"'; $linkstart .= $linkclose.'>'; @@ -774,8 +789,12 @@ class WebsitePage extends CommonObject //$linkstart = $linkend = ''; $result .= $linkstart; - if ($withpicto) $result .= img_picto(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); - if ($withpicto != 2) $result .= $this->ref; + if ($withpicto) { + $result .= img_picto(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1); + } + if ($withpicto != 2) { + $result .= $this->ref; + } $result .= $linkend; return $result; @@ -805,8 +824,7 @@ class WebsitePage extends CommonObject // phpcs:enable global $langs; - if (empty($this->labelStatus) || empty($this->labelStatusShort)) - { + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { global $langs; //$langs->load("mymodule"); $this->labelStatus[self::STATUS_DRAFT] = $langs->trans('Disabled'); @@ -816,7 +834,9 @@ class WebsitePage extends CommonObject } $statusType = 'status5'; - if ($status == self::STATUS_VALIDATED) $statusType = 'status4'; + if ($status == self::STATUS_VALIDATED) { + $statusType = 'status4'; + } return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode); } diff --git a/htdocs/website/index.php b/htdocs/website/index.php index 46dfd49ed0a..425af726c24 100644 --- a/htdocs/website/index.php +++ b/htdocs/website/index.php @@ -44,7 +44,9 @@ require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; $langs->loadLangs(array("admin", "other", "website", "errors")); -if (!$user->rights->website->read) accessforbidden(); +if (!$user->rights->website->read) { + accessforbidden(); +} $conf->dol_hide_leftmenu = 1; // Force hide of left menu. @@ -70,38 +72,78 @@ $section_dir = GETPOST('section_dir', 'alpha'); $file_manager = GETPOST('file_manager', 'alpha'); $replacesite = GETPOST('replacesite', 'alpha'); -if (GETPOST('deletesite', 'alpha')) { $action = 'deletesite'; } -if (GETPOST('delete', 'alpha')) { $action = 'delete'; } -if (GETPOST('preview', 'alpha')) $action = 'preview'; -if (GETPOST('createsite', 'alpha')) { $action = 'createsite'; } -if (GETPOST('createcontainer', 'alpha')) { $action = 'createcontainer'; } -if (GETPOST('editcss', 'alpha')) { $action = 'editcss'; } -if (GETPOST('editmenu', 'alpha')) { $action = 'editmenu'; } -if (GETPOST('setashome', 'alpha')) { $action = 'setashome'; } -if (GETPOST('editmeta', 'alpha')) { $action = 'editmeta'; } -if (GETPOST('editsource', 'alpha')) { $action = 'editsource'; } -if (GETPOST('editcontent', 'alpha')) { $action = 'editcontent'; } -if (GETPOST('exportsite', 'alpha')) { $action = 'exportsite'; } -if (GETPOST('importsite', 'alpha')) { $action = 'importsite'; } -if (GETPOST('createfromclone', 'alpha')) { $action = 'createfromclone'; } -if (GETPOST('createpagefromclone', 'alpha')) { $action = 'createpagefromclone'; } -if (empty($action) && $file_manager) $action = 'file_manager'; -if (empty($action) && $replacesite) $action = 'replacesite'; -if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x')) $pageid = 0; +if (GETPOST('deletesite', 'alpha')) { + $action = 'deletesite'; +} +if (GETPOST('delete', 'alpha')) { + $action = 'delete'; +} +if (GETPOST('preview', 'alpha')) { + $action = 'preview'; +} +if (GETPOST('createsite', 'alpha')) { + $action = 'createsite'; +} +if (GETPOST('createcontainer', 'alpha')) { + $action = 'createcontainer'; +} +if (GETPOST('editcss', 'alpha')) { + $action = 'editcss'; +} +if (GETPOST('editmenu', 'alpha')) { + $action = 'editmenu'; +} +if (GETPOST('setashome', 'alpha')) { + $action = 'setashome'; +} +if (GETPOST('editmeta', 'alpha')) { + $action = 'editmeta'; +} +if (GETPOST('editsource', 'alpha')) { + $action = 'editsource'; +} +if (GETPOST('editcontent', 'alpha')) { + $action = 'editcontent'; +} +if (GETPOST('exportsite', 'alpha')) { + $action = 'exportsite'; +} +if (GETPOST('importsite', 'alpha')) { + $action = 'importsite'; +} +if (GETPOST('createfromclone', 'alpha')) { + $action = 'createfromclone'; +} +if (GETPOST('createpagefromclone', 'alpha')) { + $action = 'createpagefromclone'; +} +if (empty($action) && $file_manager) { + $action = 'file_manager'; +} +if (empty($action) && $replacesite) { + $action = 'replacesite'; +} +if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x')) { + $pageid = 0; +} // Load variable for pagination $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 +if (empty($page) || $page == -1) { + $page = 0; +} // If $page is not defined, or '' or -1 $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; //if (! $sortfield) $sortfield='name'; //if (! $sortorder) $sortorder='ASC'; -if (empty($action)) $action = 'preview'; +if (empty($action)) { + $action = 'preview'; +} $object = new Website($db); $objectpage = new WebsitePage($db); @@ -109,16 +151,13 @@ $objectpage = new WebsitePage($db); $object->fetchAll('ASC', 'position'); // Init $object->records with list of websites // If website not defined, we take first found -if (!($websiteid > 0) && empty($websitekey) && $action != 'createsite') -{ - foreach ($object->records as $key => $valwebsite) - { +if (!($websiteid > 0) && empty($websitekey) && $action != 'createsite') { + foreach ($object->records as $key => $valwebsite) { $websitekey = $valwebsite->ref; break; } } -if ($websiteid > 0 || $websitekey) -{ +if ($websiteid > 0 || $websitekey) { $res = $object->fetch($websiteid, $websitekey); $websitekey = $object->ref; } @@ -126,38 +165,33 @@ if ($websiteid > 0 || $websitekey) $website = $object; // Check pageid received as parameter -if ($pageid < 0) $pageid = 0; -if (($pageid > 0 || $pageref) && $action != 'addcontainer') -{ +if ($pageid < 0) { + $pageid = 0; +} +if (($pageid > 0 || $pageref) && $action != 'addcontainer') { $res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), $pageref); - if ($res == 0) - { + if ($res == 0) { $res = $objectpage->fetch($pageid, ($object->id > 0 ? $object->id : null), null, $pageref); } // Check if pageid is inside the new website, if not we reset param pageid - if ($res >= 0 && $object->id > 0) - { - if ($objectpage->fk_website != $object->id) // We have a bad page that does not belong to web site - { - if ($object->fk_default_home > 0) - { + if ($res >= 0 && $object->id > 0) { + if ($objectpage->fk_website != $object->id) { // We have a bad page that does not belong to web site + if ($object->fk_default_home > 0) { $res = $objectpage->fetch($object->fk_default_home, $object->id, ''); // We search first page of web site - if ($res > 0) $pageid = $object->fk_default_home; - } - else { - $res = $objectpage->fetch(0, $object->id, ''); // We search first page of web site - if ($res == 0) // Page was not found, we reset it - { - $objectpage = new WebsitePage($db); + if ($res > 0) { + $pageid = $object->fk_default_home; } - else // We found a page, we set pageid to it. + } else { + $res = $objectpage->fetch(0, $object->id, ''); // We search first page of web site + if ($res == 0) { // Page was not found, we reset it + $objectpage = new WebsitePage($db); + } else // We found a page, we set pageid to it. { $pageid = $objectpage->id; } } - } - else // We have a valid page. We force pageid for the case we got the page with a fetch on ref. + } else // We have a valid page. We force pageid for the case we got the page with a fetch on ref. { $pageid = $objectpage->id; } @@ -165,20 +199,23 @@ if (($pageid > 0 || $pageref) && $action != 'addcontainer') } // Define pageid if pageid and pageref not received as parameter or was wrong -if (empty($pageid) && empty($pageref) && $object->id > 0 && $action != 'createcontainer') -{ +if (empty($pageid) && empty($pageref) && $object->id > 0 && $action != 'createcontainer') { $pageid = $object->fk_default_home; - if (empty($pageid)) - { + if (empty($pageid)) { $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); - if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + if (!is_array($array) && $array < 0) { + dol_print_error('', $objectpage->error, $objectpage->errors); + } $atleastonepage = (is_array($array) && count($array) > 0); $firstpageid = 0; $homepageid = 0; - foreach ($array as $key => $valpage) - { - if (empty($firstpageid)) $firstpageid = $valpage->id; - if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid = $valpage->id; + foreach ($array as $key => $valpage) { + if (empty($firstpageid)) { + $firstpageid = $valpage->id; + } + if ($object->fk_default_home && $key == $object->fk_default_home) { + $homepageid = $valpage->id; + } } $pageid = ($homepageid ? $homepageid : $firstpageid); // We choose home page and if not defined yet, we take first page } @@ -267,9 +304,15 @@ $manifestjsoncontentdefault .= '{ $listofpages = array(); $algo = ''; -if (GETPOST('optionmeta')) $algo .= 'meta'; -if (GETPOST('optioncontent')) $algo .= 'content'; -if (GETPOST('optionsitefiles')) $algo .= 'sitefiles'; +if (GETPOST('optionmeta')) { + $algo .= 'meta'; +} +if (GETPOST('optioncontent')) { + $algo .= 'content'; +} +if (GETPOST('optionsitefiles')) { + $algo .= 'sitefiles'; +} if (empty($sortfield)) { if ($action == 'file_manager') { @@ -301,43 +344,49 @@ $permissiontodelete = $user->rights->website->delete; */ // Protections -if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) -{ +if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) { $action = 'preview'; // To avoid to make an action on another page or another site when we click on button to select another site or page. } -if (GETPOST('refreshsite', 'alpha') || GETPOST('refreshsite.x', 'alpha') || GETPOST('refreshsite_x', 'alpha')) // If we change the site, we reset the pageid and cancel addsite action. -{ - if ($action == 'addsite') $action = 'preview'; - if ($action == 'updatesource') $action = 'preview'; +if (GETPOST('refreshsite', 'alpha') || GETPOST('refreshsite.x', 'alpha') || GETPOST('refreshsite_x', 'alpha')) { // If we change the site, we reset the pageid and cancel addsite action. + if ($action == 'addsite') { + $action = 'preview'; + } + if ($action == 'updatesource') { + $action = 'preview'; + } $pageid = $object->fk_default_home; - if (empty($pageid)) - { + if (empty($pageid)) { $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); - if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + if (!is_array($array) && $array < 0) { + dol_print_error('', $objectpage->error, $objectpage->errors); + } $atleastonepage = (is_array($array) && count($array) > 0); $firstpageid = 0; $homepageid = 0; - foreach ($array as $key => $valpage) - { - if (empty($firstpageid)) $firstpageid = $valpage->id; - if ($object->fk_default_home && $key == $object->fk_default_home) $homepageid = $valpage->id; + foreach ($array as $key => $valpage) { + if (empty($firstpageid)) { + $firstpageid = $valpage->id; + } + if ($object->fk_default_home && $key == $object->fk_default_home) { + $homepageid = $valpage->id; + } } $pageid = ($homepageid ? $homepageid : $firstpageid); // We choose home page and if not defined yet, we take first page } } -if (GETPOST('refreshpage', 'alpha') && !in_array($action, array('updatecss'))) $action = 'preview'; +if (GETPOST('refreshpage', 'alpha') && !in_array($action, array('updatecss'))) { + $action = 'preview'; +} if ($cancel && $action == 'renamefile') { $cancel = ''; } // Cancel -if ($cancel) -{ +if ($cancel) { $action = 'preview'; - if ($backtopage) - { + if ($backtopage) { header("Location: ".$backtopage); exit; } @@ -345,8 +394,12 @@ if ($cancel) $savbacktopage = $backtopage; $backtopage = $_SERVER["PHP_SELF"].'?file_manager=1&website='.$websitekey.'&pageid='.$pageid.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : ''); // used after a confirm_deletefile into actions_linkedfiles.inc.php -if ($sortfield) $backtopage .= '&sortfield='.$sortfield; -if ($sortorder) $backtopage .= '&sortorder='.$sortorder; +if ($sortfield) { + $backtopage .= '&sortfield='.$sortfield; +} +if ($sortorder) { + $backtopage .= '&sortorder='.$sortorder; +} include DOL_DOCUMENT_ROOT.'/core/actions_linkedfiles.inc.php'; $backtopage = $savbacktopage; @@ -354,43 +407,37 @@ if ($action == 'renamefile') { // Must be after include DOL_DOCUMENT_ROOT.'/core $action = 'file_manager'; } -if ($action == 'seteditinline') -{ +if ($action == 'seteditinline') { dolibarr_set_const($db, 'WEBSITE_EDITINLINE', 1); setEventMessages($langs->trans("FeatureNotYetAvailable"), null, 'warnings'); //dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 0); // Force disable of 'Include dynamic content' header("Location: ".$_SERVER["PHP_SELF"].'?website='.GETPOST('website', 'alphanohtml').'&pageid='.GETPOST('pageid', 'int')); exit; } -if ($action == 'unseteditinline') -{ +if ($action == 'unseteditinline') { dolibarr_del_const($db, 'WEBSITE_EDITINLINE'); header("Location: ".$_SERVER["PHP_SELF"].'?website='.GETPOST('website', 'alphanohtml').'&pageid='.GETPOST('pageid', 'int')); exit; } -if ($action == 'setshowsubcontainers') -{ +if ($action == 'setshowsubcontainers') { dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 1); //dolibarr_set_const($db, 'WEBSITE_EDITINLINE', 0); // Force disable of edit inline header("Location: ".$_SERVER["PHP_SELF"].'?website='.GETPOST('website', 'alphanohtml').'&pageid='.GETPOST('pageid', 'int')); exit; } -if ($action == 'unsetshowsubcontainers') -{ +if ($action == 'unsetshowsubcontainers') { dolibarr_del_const($db, 'WEBSITE_SUBCONTAINERSINLINE'); header("Location: ".$_SERVER["PHP_SELF"].'?website='.GETPOST('website', 'alphanohtml').'&pageid='.GETPOST('pageid', 'int')); exit; } -if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha') && !$searchkey) -{ +if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha') && !$searchkey) { $action = 'replacesite'; $massaction = ''; } // Set category -if ($massaction == 'setcategory' && GETPOST('confirmmassaction', 'alpha') && $usercanedit) -{ +if ($massaction == 'setcategory' && GETPOST('confirmmassaction', 'alpha') && $usercanedit) { $error = 0; $nbupdate = 0; @@ -429,17 +476,14 @@ if ($massaction == 'setcategory' && GETPOST('confirmmassaction', 'alpha') && $us } // Replacement of string into pages -if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha')) -{ +if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha')) { $replacestring = GETPOST('replacestring', 'none'); if (empty($user->rights->website->writephp)) { setEventMessages("NotAllowedToAddDynamicContent", null, 'errors'); - } - elseif (!$replacestring) { + } elseif (!$replacestring) { setEventMessages("ErrorReplaceStringEmpty", null, 'errors'); - } - else { + } else { $nbreplacement = 0; foreach ($toselect as $keyselected) { @@ -461,15 +505,13 @@ if ($massaction == 'replace' && GETPOST('confirmmassaction', 'alpha')) // Save page alias $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) - { + if (!$result) { setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); } // Save page of content $result = dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { + if ($result) { $nbreplacement++; //var_dump($objectpage->content);exit; $objectpage->update($user); @@ -524,31 +566,26 @@ if ($action == 'adddir' && $permtouploadfile) */ // Add site -if ($action == 'addsite') -{ +if ($action == 'addsite') { $db->begin(); - if (GETPOST('virtualhost', 'alpha') && !preg_match('/^http/', GETPOST('virtualhost', 'alpha'))) - { + if (GETPOST('virtualhost', 'alpha') && !preg_match('/^http/', GETPOST('virtualhost', 'alpha'))) { $error++; setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors'); } - if (!$error && !GETPOST('WEBSITE_REF', 'alpha')) - { + if (!$error && !GETPOST('WEBSITE_REF', 'alpha')) { $error++; $langs->load("errors"); setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities("Ref")), null, 'errors'); } - if (!$error && !preg_match('/^[a-z0-9_\-\.]+$/i', GETPOST('WEBSITE_REF', 'alpha'))) - { + if (!$error && !preg_match('/^[a-z0-9_\-\.]+$/i', GETPOST('WEBSITE_REF', 'alpha'))) { $error++; $langs->load("errors"); setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities("Ref")), null, 'errors'); } - if (!$error) - { + if (!$error) { $arrayotherlang = explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml')); foreach ($arrayotherlang as $key => $val) { $arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only @@ -562,75 +599,64 @@ if ($action == 'addsite') $tmpobject->virtualhost = GETPOST('virtualhost', 'alpha'); $result = $tmpobject->create($user); - if ($result <= 0) - { + if ($result <= 0) { $error++; setEventMessages($tmpobject->error, $tmpobject->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SiteAdded", $object->ref), null, 'mesgs'); $action = ''; header("Location: ".$_SERVER["PHP_SELF"].'?website='.$tmpobject->ref); exit; - } - else { + } else { $db->rollback(); $action = 'createsite'; } - if (!$error) - { + if (!$error) { $action = 'preview'; $id = $object->id; } } // Add page/container -if ($action == 'addcontainer') -{ +if ($action == 'addcontainer') { dol_mkdir($pathofwebsite); $db->begin(); $objectpage->fk_website = $object->id; - if (GETPOSTISSET('fetchexternalurl')) // Fetch from external url - { + if (GETPOSTISSET('fetchexternalurl')) { // Fetch from external url $urltograb = GETPOST('externalurl', 'alpha'); $grabimages = GETPOST('grabimages', 'alpha'); $grabimagesinto = GETPOST('grabimagesinto', 'alpha'); include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; - if (empty($urltograb)) - { + if (empty($urltograb)) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("URL")), null, 'errors'); $action = 'createcontainer'; - } - elseif (!preg_match('/^http/', $urltograb)) - { + } elseif (!preg_match('/^http/', $urltograb)) { $error++; $langs->load("errors"); setEventMessages('Error URL must start with http:// or https://', null, 'errors'); $action = 'createcontainer'; } - if (!$error) - { + if (!$error) { // Clean url to grab, so url can be // http://www.example.com/ or http://www.example.com/dir1/ or http://www.example.com/dir1/aaa $urltograbwithoutdomainandparam = preg_replace('/^https?:\/\/[^\/]+\/?/i', '', $urltograb); //$urltograbwithoutdomainandparam = preg_replace('/^file:\/\/[^\/]+\/?/i', '', $urltograb); $urltograbwithoutdomainandparam = preg_replace('/\?.*$/', '', $urltograbwithoutdomainandparam); - if (empty($urltograbwithoutdomainandparam) && !preg_match('/\/$/', $urltograb)) - { + if (empty($urltograbwithoutdomainandparam) && !preg_match('/\/$/', $urltograb)) { $urltograb .= '/'; } $pageurl = dol_sanitizeFileName(preg_replace('/[\/\.]/', '-', preg_replace('/\/+$/', '', $urltograbwithoutdomainandparam))); @@ -642,34 +668,27 @@ if ($action == 'addcontainer') } // Check pageurl is not already used - if ($pageurl) - { + if ($pageurl) { $tmpwebsitepage = new WebsitePage($db); $result = $tmpwebsitepage->fetch(0, $object->id, $pageurl); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("AliasPageAlreadyExists", $pageurl), null, 'errors'); $error++; $action = 'createcontainer'; } } - if (!$error) - { + if (!$error) { $tmp = getURLContent($urltograb); - if ($tmp['curl_error_no']) - { + if ($tmp['curl_error_no']) { $error++; setEventMessages('Error getting '.$urltograb.': '.$tmp['curl_error_msg'], null, 'errors'); $action = 'createcontainer'; - } - elseif ($tmp['http_code'] != '200') - { + } elseif ($tmp['http_code'] != '200') { $error++; setEventMessages('Error getting '.$urltograb.': '.$tmp['http_code'], null, 'errors'); $action = 'createcontainer'; - } - else { + } else { // Remove comments $tmp['content'] = removeHtmlComment($tmp['content']); @@ -679,36 +698,34 @@ if ($action == 'addcontainer') $head = $regs[1]; $objectpage->type_container = 'page'; - $objectpage->pageurl = $pageurl; - if (empty($objectpage->pageurl)) - { - $tmpdomain = getDomainFromURL($urltograb); - $objectpage->pageurl = $tmpdomain.'-home'; - } + $objectpage->pageurl = $pageurl; + if (empty($objectpage->pageurl)) { + $tmpdomain = getDomainFromURL($urltograb); + $objectpage->pageurl = $tmpdomain.'-home'; + } - $objectpage->aliasalt = ''; + $objectpage->aliasalt = ''; - if (preg_match('/^(\d+)\-/', basename($urltograb), $regs)) $objectpage->aliasalt = $regs[1]; + if (preg_match('/^(\d+)\-/', basename($urltograb), $regs)) { + $objectpage->aliasalt = $regs[1]; + } - $regtmp = array(); - if (preg_match('/<title>(.*)<\/title>/ims', $head, $regtmp)) - { + $regtmp = array(); + if (preg_match('/<title>(.*)<\/title>/ims', $head, $regtmp)) { $objectpage->title = $regtmp[1]; } - if (preg_match('/<meta name="title"[^"]+content="([^"]+)"/ims', $head, $regtmp)) - { - if (empty($objectpage->title)) $objectpage->title = $regtmp[1]; // If title not found into <title>, we get it from <meta title> + if (preg_match('/<meta name="title"[^"]+content="([^"]+)"/ims', $head, $regtmp)) { + if (empty($objectpage->title)) { + $objectpage->title = $regtmp[1]; // If title not found into <title>, we get it from <meta title> + } } - if (preg_match('/<meta name="description"[^"]+content="([^"]+)"/ims', $head, $regtmp)) - { + if (preg_match('/<meta name="description"[^"]+content="([^"]+)"/ims', $head, $regtmp)) { $objectpage->description = $regtmp[1]; } - if (preg_match('/<meta name="keywords"[^"]+content="([^"]+)"/ims', $head, $regtmp)) - { + if (preg_match('/<meta name="keywords"[^"]+content="([^"]+)"/ims', $head, $regtmp)) { $objectpage->keywords = $regtmp[1]; } - if (preg_match('/<html\s+lang="([^"]+)"/ims', $tmp['content'], $regtmp)) - { + if (preg_match('/<html\s+lang="([^"]+)"/ims', $tmp['content'], $regtmp)) { $tmplang = explode('-', $regtmp[1]); $objectpage->lang = $tmplang[0].($tmplang[1] ? '_'.strtoupper($tmplang[1]) : ''); } @@ -749,22 +766,18 @@ if ($action == 'addcontainer') // We grab files found into <script> tags preg_match_all('/<script([^\.>]+)src=["\']([^"\'>]+)["\']([^>]*)><\/script>/i', $objectpage->htmlheader, $regs); $errorforsubresource = 0; - foreach ($regs[0] as $key => $val) - { + foreach ($regs[0] as $key => $val) { dol_syslog("We will grab the script resource found into script tag ".$regs[2][$key]); $linkwithoutdomain = $regs[2][$key]; - if (preg_match('/^\//', $regs[2][$key])) - { + if (preg_match('/^\//', $regs[2][$key])) { $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot - } - else { + } else { $urltograbbis = $urltograbdirwithoutslash.'/'.$regs[2][$key]; // We use dir of grabbed file } //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; - if (preg_match('/^http/', $regs[2][$key])) - { + if (preg_match('/^http/', $regs[2][$key])) { $urltograbbis = $regs[2][$key]; $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]); //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; @@ -776,17 +789,19 @@ if ($action == 'addcontainer') // Test if this is an external URL of grabbed web site. If yes, we do not load resource $domaintograb = getDomainFromURL($urltograbdirwithoutslash); $domaintograbbis = getDomainFromURL($urltograbbis); - if ($domaintograb != $domaintograbbis) continue; + if ($domaintograb != $domaintograbbis) { + continue; + } /* - $tmpgeturl = getURLContent($urltograbbis); - if ($tmpgeturl['curl_error_no']) - { - $error++; - setEventMessages('Error getting script url '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors'); - $errorforsubresource++; - $action='createcontainer'; - } + $tmpgeturl = getURLContent($urltograbbis); + if ($tmpgeturl['curl_error_no']) + { + $error++; + setEventMessages('Error getting script url '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors'); + $errorforsubresource++; + $action='createcontainer'; + } elseif ($tmpgeturl['http_code'] != '200') { $error++; @@ -795,15 +810,15 @@ if ($action == 'addcontainer') $action='createcontainer'; } else - { - dol_mkdir(dirname($filetosave)); + { + dol_mkdir(dirname($filetosave)); - $fp = fopen($filetosave, "w"); - fputs($fp, $tmpgeturl['content']); - fclose($fp); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($file, octdec($conf->global->MAIN_UMASK)); - } + $fp = fopen($filetosave, "w"); + fputs($fp, $tmpgeturl['content']); + fclose($fp); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($file, octdec($conf->global->MAIN_UMASK)); + } */ //$filename = 'image/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; @@ -817,22 +832,18 @@ if ($action == 'addcontainer') preg_match_all('/<link([^\.>]+)href=["\']([^"\'>]+\.css[^"\'>]*)["\']([^>]*)>/i', $objectpage->htmlheader, $regs); $errorforsubresource = 0; - foreach ($regs[0] as $key => $val) - { + foreach ($regs[0] as $key => $val) { dol_syslog("We will grab the css resources found into link tag ".$regs[2][$key]); $linkwithoutdomain = $regs[2][$key]; - if (preg_match('/^\//', $regs[2][$key])) - { + if (preg_match('/^\//', $regs[2][$key])) { $urltograbbis = $urltograbdirrootwithoutslash.$regs[2][$key]; // We use dirroot - } - else { + } else { $urltograbbis = $urltograbdirwithoutslash.'/'.$regs[2][$key]; // We use dir of grabbed file } //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $regs[2][$key])?'':'/').$regs[2][$key]; - if (preg_match('/^http/', $regs[2][$key])) - { + if (preg_match('/^http/', $regs[2][$key])) { $urltograbbis = $regs[2][$key]; $linkwithoutdomain = preg_replace('/^https?:\/\/[^\/]+\//i', '', $regs[2][$key]); //$filetosave = $conf->medias->multidir_output[$conf->entity].'/css/'.$object->ref.'/'.$objectpage->pageurl.(preg_match('/^\//', $linkwithoutdomain)?'':'/').$linkwithoutdomain; @@ -844,24 +855,22 @@ if ($action == 'addcontainer') // Test if this is an external URL of grabbed web site. If yes, we do not load resource $domaintograb = getDomainFromURL($urltograbdirwithoutslash); $domaintograbbis = getDomainFromURL($urltograbbis); - if ($domaintograb != $domaintograbbis) continue; + if ($domaintograb != $domaintograbbis) { + continue; + } $tmpgeturl = getURLContent($urltograbbis); - if ($tmpgeturl['curl_error_no']) - { + if ($tmpgeturl['curl_error_no']) { $errorforsubresource++; setEventMessages('Error getting link tag url '.$urltograbbis.': '.$tmpgeturl['curl_error_msg'], null, 'errors'); dol_syslog('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg']); $action = 'createcontainer'; - } - elseif ($tmpgeturl['http_code'] != '200') - { + } elseif ($tmpgeturl['http_code'] != '200') { $errorforsubresource++; setEventMessages('Error getting link tag url '.$urltograbbis.': '.$tmpgeturl['http_code'], null, 'errors'); dol_syslog('Error getting '.$urltograbbis.': '.$tmpgeturl['curl_error_msg']); $action = 'createcontainer'; - } - else { + } else { // Clean some comment //$tmpgeturl['content'] = dol_string_is_good_iso($tmpgeturl['content'], 1); //$tmpgeturl['content'] = utf8_encode(utf8_decode($tmpgeturl['content'])); @@ -959,7 +968,9 @@ if ($action == 'addcontainer') $objectpage->fk_page = $pageidfortranslation; $sample = GETPOST('sample', 'alpha'); - if (empty($sample)) $sample = 'empty'; + if (empty($sample)) { + $sample = 'empty'; + } $pathtosample = DOL_DOCUMENT_ROOT.'/website/samples/page-sample-'.dol_sanitizeFileName($sample).'.html'; @@ -967,38 +978,31 @@ if ($action == 'addcontainer') $objectpage->content = make_substitutions(@file_get_contents($pathtosample), $substitutionarray); } - if (!$error) - { - if (empty($objectpage->pageurl)) - { + if (!$error) { + if (empty($objectpage->pageurl)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_PAGENAME")), null, 'errors'); $error++; $action = 'createcontainer'; - } - elseif (!preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) - { + } elseif (!preg_match('/^[a-z0-9\-\_]+$/i', $objectpage->pageurl)) { $langs->load("errors"); setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors'); $error++; $action = 'createcontainer'; } - if (empty($objectpage->title)) - { + if (empty($objectpage->title)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("WEBSITE_TITLE")), null, 'errors'); $error++; $action = 'createcontainer'; } - if ($objectpage->fk_page > 0 && empty($objectpage->lang)) - { + if ($objectpage->fk_page > 0 && empty($objectpage->lang)) { $langs->load("errors"); setEventMessages($langs->trans("ErrorLanguageRequiredIfPageIsTranslationOfAnother"), null, 'errors'); $error++; $action = 'createcontainer'; } - if ($objectpage->fk_page > 0 && !empty($objectpage->lang)) - { + if ($objectpage->fk_page > 0 && !empty($objectpage->lang)) { if ($objectpage->lang == $website->lang) { $langs->load("errors"); setEventMessages($langs->trans("ErrorLanguageMustNotBeSourceLanguageIfPageIsTranslationOfAnother"), null, 'errors'); @@ -1008,8 +1012,7 @@ if ($action == 'addcontainer') } } - if (!$error) - { + if (!$error) { $pageid = $objectpage->create($user); if ($pageid <= 0) { $error++; @@ -1022,8 +1025,7 @@ if ($action == 'addcontainer') // Website categories association $categoriesarray = GETPOST('categories', 'array'); $result = $objectpage->setCategories($categoriesarray); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } @@ -1034,8 +1036,7 @@ if ($action == 'addcontainer') if (empty($object->fk_default_home)) { $object->fk_default_home = $pageid; $res = $object->update($user); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } else { @@ -1044,50 +1045,44 @@ if ($action == 'addcontainer') // Generate the index.php page (to be the home page) and wrapper.php file $result = dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper); - if ($result <= 0) setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + if ($result <= 0) { + setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + } } } } - if (!$error) - { - if (!empty($objectpage->content)) - { + if (!$error) { + if (!empty($objectpage->content)) { $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php'; $filetpl = $pathofwebsite.'/page'.$objectpage->id.'.tpl.php'; // Save page alias $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) - { + if (!$result) { setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); } // Save page of content $result = dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { + if ($result) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); - } - else { + } else { setEventMessages('Failed to write file '.$filetpl, null, 'errors'); $action = 'createcontainer'; } } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageAdded", $objectpage->pageurl), null, 'mesgs'); $action = ''; - } - else { + } else { $db->rollback(); } - if (!$error) - { + if (!$error) { $pageid = $objectpage->id; // To generate the CSS, robot and htmlheader file. @@ -1095,64 +1090,54 @@ if ($action == 'addcontainer') // Check symlink to medias and restore it if ko $pathtomedias = DOL_DATA_ROOT.'/medias'; $pathtomediasinwebsite = $pathofwebsite.'/medias'; - if (!is_link(dol_osencode($pathtomediasinwebsite))) - { + if (!is_link(dol_osencode($pathtomediasinwebsite))) { dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); } // Now generate the master.inc.php page if it does not exists yet - if (!dol_is_file($filemaster)) - { + if (!dol_is_file($filemaster)) { $result = dolSaveMasterFile($filemaster); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filemaster, null, 'errors'); } } - if (!dol_is_file($filehtmlheader)) - { + if (!dol_is_file($filehtmlheader)) { $htmlheadercontent = "<html>\n"; $htmlheadercontent .= $htmlheadercontentdefault; $htmlheadercontent .= "</html>"; $result = dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); } - if (!dol_is_file($filecss)) - { + if (!dol_is_file($filecss)) { $csscontent = "/* CSS content (all pages) */\nbody.bodywebsite { margin: 0; font-family: 'Open Sans', sans-serif; }\n.bodywebsite h1 { margin-top: 0; margin-bottom: 0; padding: 10px;}"; $result = dolSaveCssFile($filecss, $csscontent); } - if (!dol_is_file($filejs)) - { + if (!dol_is_file($filejs)) { $jscontent = "/* JS content (all pages) */\n"; $result = dolSaveJsFile($filejs, $jscontent); } - if (!dol_is_file($filerobot)) - { + if (!dol_is_file($filerobot)) { $robotcontent = "# Robot file. Generated with Dolibarr\nUser-agent: *\nAllow: /public/\nDisallow: /administrator/"; $result = dolSaveRobotFile($filerobot, $robotcontent); } - if (!dol_is_file($filehtaccess)) - { + if (!dol_is_file($filehtaccess)) { $htaccesscontent = "# Order allow,deny\n# Deny from all"; $result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent); } - if (!dol_is_file($filemanifestjson)) - { + if (!dol_is_file($filemanifestjson)) { $manifestjsoncontent = ""; $result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent); } - if (!dol_is_file($filereadme)) - { + if (!dol_is_file($filereadme)) { $readmecontent = "Website generated by Dolibarr ERP CRM"; $result = dolSaveReadme($filereadme, $readmecontent); } @@ -1162,8 +1147,7 @@ if ($action == 'addcontainer') } // Delete site -if ($action == 'confirm_deletesite' && $confirm == 'yes') -{ +if ($action == 'confirm_deletesite' && $confirm == 'yes') { $error = 0; $db->begin(); @@ -1171,40 +1155,33 @@ if ($action == 'confirm_deletesite' && $confirm == 'yes') $res = $object->fetch(GETPOST('id', 'int')); $website = $object; - if ($res > 0) - { + if ($res > 0) { $res = $object->delete($user); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } - if (!$error) - { - if (GETPOST('delete_also_js', 'alpha') == 'on') - { + if (!$error) { + if (GETPOST('delete_also_js', 'alpha') == 'on') { $pathofwebsitejs = DOL_DATA_ROOT.'/medias/js/'.$object->ref; dol_delete_dir_recursive($pathofwebsitejs); } - if (GETPOST('delete_also_medias', 'alpha') == 'on') - { + if (GETPOST('delete_also_medias', 'alpha') == 'on') { $pathofwebsitemedias = DOL_DATA_ROOT.'/medias/image/'.$object->ref; dol_delete_dir_recursive($pathofwebsitemedias); } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("SiteDeleted", $object->ref), null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"].'?id='.$object->id); exit; - } - else { + } else { $db->rollback(); dol_print_error($db); } @@ -1221,25 +1198,21 @@ if (GETPOSTISSET('pageid') && $action == 'delete' && $permissiontodelete) { $res = $objectpage->fetch($pageid, $object->id); - if ($res > 0) - { + if ($res > 0) { $res = $objectpage->delete($user); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); setEventMessages($langs->trans("PageDeleted", $objectpage->pageurl, $websitekey), null, 'mesgs'); header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey); exit; - } - else { + } else { $db->rollback(); dol_print_error($db); } @@ -1250,25 +1223,23 @@ if (!GETPOSTISSET('pageid')) { // Add part of code from actions_massactions.inc.php // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before) - if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) - { + if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permissiontodelete) { $db->begin(); $objecttmp = new $objectclass($db); $nbok = 0; - foreach ($toselect as $toselectid) - { + foreach ($toselect as $toselectid) { $result = $objecttmp->fetch($toselectid); - if ($result > 0) - { + if ($result > 0) { $result = $objecttmp->delete($user); - if ($result <= 0) - { + if ($result <= 0) { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; break; - } else $nbok++; + } else { + $nbok++; + } } else { setEventMessages($objecttmp->error, $objecttmp->errors, 'errors'); $error++; @@ -1276,10 +1247,12 @@ if (!GETPOSTISSET('pageid')) { } } - if (!$error) - { - if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); - else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + if (!$error) { + if ($nbok > 1) { + setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs'); + } else { + setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs'); + } $db->commit(); } else { $db->rollback(); @@ -1302,29 +1275,23 @@ if (!GETPOSTISSET('pageid')) { } // Update css Update site properties -if ($action == 'updatecss') -{ +if ($action == 'updatecss') { // If we tried to reload another site/page, we stay on editcss mode. - if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) - { + if (GETPOST('refreshsite') || GETPOST('refreshsite_x') || GETPOST('refreshsite.x') || GETPOST('refreshpage') || GETPOST('refreshpage_x') || GETPOST('refreshpage.x')) { $action = 'editcss'; - } - else { + } else { $res = $object->fetch(0, $websitekey); $website = $object; - if (GETPOSTISSET('virtualhost')) - { + if (GETPOSTISSET('virtualhost')) { $tmpvirtualhost = preg_replace('/\/$/', '', GETPOST('virtualhost', 'alpha')); - if ($tmpvirtualhost && !preg_match('/^http/', $tmpvirtualhost)) - { + if ($tmpvirtualhost && !preg_match('/^http/', $tmpvirtualhost)) { $error++; setEventMessages($langs->trans('ErrorURLMustStartWithHttp', $langs->transnoentitiesnoconv("VirtualHost")), null, 'errors'); $action = 'editcss'; } - if (!$error) - { + if (!$error) { $arrayotherlang = explode(',', GETPOST('WEBSITE_OTHERLANG', 'alphanohtml')); foreach ($arrayotherlang as $key => $val) { $arrayotherlang[$key] = substr(trim($val), 0, 2); // Kept short language code only @@ -1336,8 +1303,7 @@ if ($action == 'updatecss') $object->use_manifest = GETPOST('use_manifest', 'alpha'); $result = $object->update($user); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); $action = 'editcss'; @@ -1345,8 +1311,7 @@ if ($action == 'updatecss') } } - if (!$error) - { + if (!$error) { // Save master.inc.php file dol_syslog("Save master file ".$filemaster); @@ -1354,8 +1319,7 @@ if ($action == 'updatecss') // Now generate the master.inc.php page $result = dolSaveMasterFile($filemaster); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filemaster, null, 'errors'); } @@ -1365,26 +1329,25 @@ if ($action == 'updatecss') $htmlheadercontent = ''; /* We disable php code since htmlheader is never executed as an include but only read by fgets_content. - $htmlheadercontent.= "<?php // BEGIN PHP\n"; - $htmlheadercontent.= '$websitekey=basename(__DIR__);'."\n"; - $htmlheadercontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n"; - $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $htmlheadercontent.= "ob_start();\n"; - // $htmlheadercontent.= "header('Content-type: text/html');\n"; // Not required. htmlheader.html is never call as a standalone page - $htmlheadercontent.= "// END PHP ?>\n";*/ + $htmlheadercontent.= "<?php // BEGIN PHP\n"; + $htmlheadercontent.= '$websitekey=basename(__DIR__);'."\n"; + $htmlheadercontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n"; + $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $htmlheadercontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $htmlheadercontent.= "ob_start();\n"; + // $htmlheadercontent.= "header('Content-type: text/html');\n"; // Not required. htmlheader.html is never call as a standalone page + $htmlheadercontent.= "// END PHP ?>\n";*/ $htmlheadercontent .= preg_replace(array('/<html>\n*/ims', '/<\/html>\n*/ims'), array('', ''), GETPOST('WEBSITE_HTML_HEADER', 'none')); /*$htmlheadercontent.= "\n".'<?php // BEGIN PHP'."\n"; - $htmlheadercontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n"; - $htmlheadercontent.= "// END PHP ?>"."\n";*/ + $htmlheadercontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp);'."\n"; + $htmlheadercontent.= "// END PHP ?>"."\n";*/ $htmlheadercontent = trim($htmlheadercontent)."\n"; $result = dolSaveHtmlHeader($filehtmlheader, $htmlheadercontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filehtmlheader, null, 'errors'); } @@ -1414,8 +1377,7 @@ if ($action == 'updatecss') dol_syslog("Save css content into ".$filecss); $result = dolSaveCssFile($filecss, $csscontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filecss, null, 'errors'); } @@ -1441,8 +1403,7 @@ if ($action == 'updatecss') $jscontent .= "// END PHP ?>\n"; $result = dolSaveJsFile($filejs, $jscontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filejs, null, 'errors'); } @@ -1452,24 +1413,23 @@ if ($action == 'updatecss') $robotcontent = ''; /*$robotcontent.= "<?php // BEGIN PHP\n"; - $robotcontent.= '$websitekey=basename(__DIR__);'."\n"; - $robotcontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n"; - $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $robotcontent.= "ob_start();\n"; - $robotcontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; - $robotcontent.= "header('Content-type: text/css');\n"; - $robotcontent.= "// END PHP ?>\n";*/ + $robotcontent.= '$websitekey=basename(__DIR__);'."\n"; + $robotcontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load env if not already loaded"."\n"; + $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $robotcontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $robotcontent.= "ob_start();\n"; + $robotcontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; + $robotcontent.= "header('Content-type: text/css');\n"; + $robotcontent.= "// END PHP ?>\n";*/ $robotcontent .= trim(GETPOST('WEBSITE_ROBOT', 'restricthtml'))."\n"; /*$robotcontent.= "\n".'<?php // BEGIN PHP'."\n"; - $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "robot");'."\n"; - $robotcontent.= "// END PHP ?>"."\n";*/ + $robotcontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "robot");'."\n"; + $robotcontent.= "// END PHP ?>"."\n";*/ $result = dolSaveRobotFile($filerobot, $robotcontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filerobot, null, 'errors'); } @@ -1480,87 +1440,80 @@ if ($action == 'updatecss') $htaccesscontent .= trim(GETPOST('WEBSITE_HTACCESS', 'restricthtml'))."\n"; $result = dolSaveHtaccessFile($filehtaccess, $htaccesscontent); - if (!$result) - { + if (!$result) { $error++; setEventMessages('Failed to write file '.$filehtaccess, null, 'errors'); } - // manifest.json file - $manifestjsoncontent = ''; + // manifest.json file + $manifestjsoncontent = ''; - $manifestjsoncontent .= "<?php // BEGIN PHP\n"; - $manifestjsoncontent .= '$websitekey=basename(__DIR__);'."\n"; - $manifestjsoncontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file. - $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $manifestjsoncontent .= "ob_start();\n"; - $manifestjsoncontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; - $manifestjsoncontent .= "header('Content-type: application/manifest+json');\n"; - $manifestjsoncontent .= "// END PHP ?>\n"; + $manifestjsoncontent .= "<?php // BEGIN PHP\n"; + $manifestjsoncontent .= '$websitekey=basename(__DIR__);'."\n"; + $manifestjsoncontent .= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded\n"; // For the css, we need to set path of master using the dirname of css file. + $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $manifestjsoncontent .= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $manifestjsoncontent .= "ob_start();\n"; + $manifestjsoncontent .= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; + $manifestjsoncontent .= "header('Content-type: application/manifest+json');\n"; + $manifestjsoncontent .= "// END PHP ?>\n"; - $manifestjsoncontent .= trim(GETPOST('WEBSITE_MANIFEST_JSON', 'none'))."\n"; + $manifestjsoncontent .= trim(GETPOST('WEBSITE_MANIFEST_JSON', 'none'))."\n"; - $manifestjsoncontent .= '<?php // BEGIN PHP'."\n"; - $manifestjsoncontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n"; - $manifestjsoncontent .= "// END PHP ?>\n"; + $manifestjsoncontent .= '<?php // BEGIN PHP'."\n"; + $manifestjsoncontent .= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n"; + $manifestjsoncontent .= "// END PHP ?>\n"; - $result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent); - if (!$result) - { - $error++; - setEventMessages('Failed to write file '.$filemanifestjson, null, 'errors'); - } + $result = dolSaveManifestJson($filemanifestjson, $manifestjsoncontent); + if (!$result) { + $error++; + setEventMessages('Failed to write file '.$filemanifestjson, null, 'errors'); + } - // README.md file - $readmecontent = ''; + // README.md file + $readmecontent = ''; - /*$readmecontent.= "<?php // BEGIN PHP\n"; - $readmecontent.= '$websitekey=basename(__DIR__);'."\n"; - $readmecontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded"."\n"; // For the css, we need to set path of master using the dirname of css file. - $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; - $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; - $readmecontent.= "ob_start();\n"; - $readmecontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; - $readmecontent.= "header('Content-type: application/manifest+json');\n"; - $readmecontent.= "// END PHP ?>\n";*/ + /*$readmecontent.= "<?php // BEGIN PHP\n"; + $readmecontent.= '$websitekey=basename(__DIR__);'."\n"; + $readmecontent.= "if (! defined('USEDOLIBARRSERVER') && ! defined('USEDOLIBARREDITOR')) { require_once __DIR__.'/master.inc.php'; } // Load env if not already loaded"."\n"; // For the css, we need to set path of master using the dirname of css file. + $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';\n"; + $readmecontent.= "require_once DOL_DOCUMENT_ROOT.'/core/website.inc.php';\n"; + $readmecontent.= "ob_start();\n"; + $readmecontent.= "header('Cache-Control: max-age=3600, public, must-revalidate');\n"; + $readmecontent.= "header('Content-type: application/manifest+json');\n"; + $readmecontent.= "// END PHP ?>\n";*/ - $readmecontent .= trim(GETPOST('WEBSITE_README', 'restricthtml'))."\n"; + $readmecontent .= trim(GETPOST('WEBSITE_README', 'restricthtml'))."\n"; - /*$readmecontent.= '<?php // BEGIN PHP'."\n"; - $readmecontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n"; - $readmecontent.= "// END PHP ?>"."\n";*/ + /*$readmecontent.= '<?php // BEGIN PHP'."\n"; + $readmecontent.= '$tmp = ob_get_contents(); ob_end_clean(); dolWebsiteOutput($tmp, "manifest");'."\n"; + $readmecontent.= "// END PHP ?>"."\n";*/ - $result = dolSaveReadme($filereadme, $readmecontent); - if (!$result) - { - $error++; - setEventMessages('Failed to write file '.$filereadme, null, 'errors'); - } + $result = dolSaveReadme($filereadme, $readmecontent); + if (!$result) { + $error++; + setEventMessages('Failed to write file '.$filereadme, null, 'errors'); + } - // Save wrapper.php + // Save wrapper.php $result = dolSaveIndexPage($pathofwebsite, '', '', $filewrapper); // Message if no error - if (!$error) - { + if (!$error) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); } - if (!GETPOSTISSET('updateandstay')) // If we click on "Save And Stay", we don not make the redirect - { + if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we don not make the redirect $action = 'preview'; - if ($backtopage) - { + if ($backtopage) { header("Location: ".$backtopage); exit; } - } - else { + } else { $action = 'editcss'; } } @@ -1568,22 +1521,19 @@ if ($action == 'updatecss') } // Update page -if ($action == 'setashome') -{ +if ($action == 'setashome') { $db->begin(); $object->fetch(0, $websitekey); $website = $object; $object->fk_default_home = $pageid; $res = $object->update($user); - if (! ($res > 0)) - { + if (! ($res > 0)) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } - if (!$error) - { + if (!$error) { $db->commit(); $filetpl = $pathofwebsite.'/page'.$pageid.'.tpl.php'; @@ -1591,19 +1541,20 @@ if ($action == 'setashome') // Generate the index.php page to be the home page $result = dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper); - if ($result) setEventMessages($langs->trans("Saved"), null, 'mesgs'); - else setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + if ($result) { + setEventMessages($langs->trans("Saved"), null, 'mesgs'); + } else { + setEventMessages('Failed to write file '.$fileindex, null, 'errors'); + } $action = 'preview'; - } - else { + } else { $db->rollback(); } } // Update page properties (meta) -if ($action == 'updatemeta') -{ +if ($action == 'updatemeta') { $db->begin(); $result = $object->fetch(0, $websitekey); @@ -1612,8 +1563,7 @@ if ($action == 'updatemeta') $objectpage->fk_website = $object->id; // Check parameters - if (!preg_match('/^[a-z0-9\-\_]+$/i', GETPOST('WEBSITE_PAGENAME', 'alpha'))) - { + if (!preg_match('/^[a-z0-9\-\_]+$/i', GETPOST('WEBSITE_PAGENAME', 'alpha'))) { $error++; $langs->load("errors"); setEventMessages($langs->transnoentities("ErrorFieldCanNotContainSpecialCharacters", $langs->transnoentities('WEBSITE_PAGENAME')), null, 'errors'); @@ -1621,38 +1571,32 @@ if ($action == 'updatemeta') } $res = $objectpage->fetch($pageid, $object->id); - if ($res <= 0) - { + if ($res <= 0) { $error++; setEventMessages('Page not found '.$objectpage->error, $objectpage->errors, 'errors'); } // Check alias not exists - if (!$error && GETPOST('WEBSITE_PAGENAME', 'alpha')) - { + if (!$error && GETPOST('WEBSITE_PAGENAME', 'alpha')) { $websitepagetemp = new WebsitePage($db); $result = $websitepagetemp->fetch(-1 * $objectpage->id, $object->id, GETPOST('WEBSITE_PAGENAME', 'alpha')); - if ($result < 0) - { + if ($result < 0) { $error++; $langs->load("errors"); setEventMessages($websitepagetemp->error, $websitepagetemp->errors, 'errors'); $action = 'editmeta'; } - if ($result > 0) - { + if ($result > 0) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists", $websitepagetemp->pageurl), null, 'errors'); $action = 'editmeta'; } } - if (!$error && GETPOST('WEBSITE_ALIASALT', 'alpha')) - { + if (!$error && GETPOST('WEBSITE_ALIASALT', 'alpha')) { $arrayofaliastotest = explode(',', GETPOST('WEBSITE_ALIASALT', 'alpha')); $websitepagetemp = new WebsitePage($db); - foreach ($arrayofaliastotest as $aliastotest) - { + foreach ($arrayofaliastotest as $aliastotest) { // Disallow alias name pageX (already used to save the page with id) if (preg_match('/^page\d+/i', $aliastotest)) { $error++; @@ -1662,16 +1606,14 @@ if ($action == 'updatemeta') break; } else { $result = $websitepagetemp->fetch(-1 * $objectpage->id, $object->id, $aliastotest); - if ($result < 0) - { + if ($result < 0) { $error++; $langs->load("errors"); setEventMessages($websitepagetemp->error, $websitepagetemp->errors, 'errors'); $action = 'editmeta'; break; } - if ($result > 0) - { + if ($result > 0) { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists", $websitepagetemp->pageurl), null, 'errors'); @@ -1682,8 +1624,7 @@ if ($action == 'updatemeta') } } - if (!$error) - { + if (!$error) { $objectpage->old_object = clone $objectpage; $objectpage->title = str_replace(array('<', '>'), '', GETPOST('WEBSITE_TITLE', 'alphanohtml')); @@ -1703,20 +1644,19 @@ if ($action == 'updatemeta') $objectpage->fk_object = GETPOST('WEBSITE_OBJECTID', 'aZ09'); $newdatecreation = dol_mktime(GETPOST('datecreationhour', 'int'), GETPOST('datecreationmin', 'int'), GETPOST('datecreationsec', 'int'), GETPOST('datecreationmonth', 'int'), GETPOST('datecreationday', 'int'), GETPOST('datecreationyear', 'int')); - if ($newdatecreation) $objectpage->date_creation = $newdatecreation; + if ($newdatecreation) { + $objectpage->date_creation = $newdatecreation; + } $res = $objectpage->update($user); - if (!($res > 0)) - { + if (!($res > 0)) { $langs->load("errors"); - if ($db->lasterrno == 'DB_ERROR_RECORD_ALREADY_EXISTS') - { + if ($db->lasterrno == 'DB_ERROR_RECORD_ALREADY_EXISTS') { $error++; $langs->load("errors"); setEventMessages($langs->trans("ErrorAPageWithThisNameOrAliasAlreadyExists"), null, 'errors'); $action = 'editmeta'; - } - else { + } else { $error++; $langs->load("errors"); setEventMessages($objectpage->error, $objectpage->errors, 'errors'); @@ -1729,23 +1669,19 @@ if ($action == 'updatemeta') // Website categories association $categoriesarray = GETPOST('categories', 'array'); $result = $objectpage->setCategories($categoriesarray); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($object->error, $object->errors, 'errors'); } } - if (!$error) - { + if (!$error) { $db->commit(); - } - else { + } else { $db->rollback(); } - if (!$error) - { + if (!$error) { $filemaster = $pathofwebsite.'/master.inc.php'; $fileoldalias = $pathofwebsite.'/'.$objectpage->old_object->pageurl.'.php'; $filealias = $pathofwebsite.'/'.$objectpage->pageurl.'.php'; @@ -1754,11 +1690,12 @@ if ($action == 'updatemeta') // Now generate the master.inc.php page $result = dolSaveMasterFile($filemaster); - if (!$result) setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.$filemaster, null, 'errors'); + } // Now delete the alias.php page - if (!empty($fileoldalias)) - { + if (!empty($fileoldalias)) { dol_syslog("We delete old alias page name=".$fileoldalias." to build a new alias page=".$filealias); dol_delete_file($fileoldalias); @@ -1774,13 +1711,10 @@ if ($action == 'updatemeta') } } // Now delete the alternative alias.php pages - if (!empty($objectpage->old_object->aliasalt)) - { + if (!empty($objectpage->old_object->aliasalt)) { $tmpaltaliases = explode(',', $objectpage->old_object->aliasalt); - if (is_array($tmpaltaliases)) - { - foreach ($tmpaltaliases as $tmpaliasalt) - { + if (is_array($tmpaltaliases)) { + foreach ($tmpaltaliases as $tmpaliasalt) { dol_syslog("We delete old alt alias pages name=".trim($tmpaliasalt)); dol_delete_file($pathofwebsite.'/'.trim($tmpaliasalt).'.php'); @@ -1800,20 +1734,20 @@ if ($action == 'updatemeta') // Save page main alias $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) setEventMessages('Failed to write file '.$filealias, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.$filealias, null, 'errors'); + } // Save alt aliases - if (!empty($objectpage->aliasalt)) - { + if (!empty($objectpage->aliasalt)) { $tmpaltaliases = explode(',', $objectpage->aliasalt); - if (is_array($tmpaltaliases)) - { - foreach ($tmpaltaliases as $tmpaliasalt) - { - if (trim($tmpaliasalt)) - { + if (is_array($tmpaltaliases)) { + foreach ($tmpaltaliases as $tmpaliasalt) { + if (trim($tmpaliasalt)) { $filealias = $pathofwebsite.'/'.trim($tmpaliasalt).'.php'; $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); + if (!$result) { + setEventMessages('Failed to write file '.basename($filealias), null, 'errors'); + } } } } @@ -1822,24 +1756,20 @@ if ($action == 'updatemeta') // Save page of content $result = dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { + if ($result) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); - if (!GETPOSTISSET('updateandstay')) // If we click on "Save And Stay", we do not make the redirect - { + if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we do not make the redirect //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid); //exit; $action = 'preview'; - } - else { + } else { $action = 'editmeta'; } - } - else { + } else { setEventMessages('Failed to write file '.$filetpl, null, 'errors'); //header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid); - //exit; + //exit; $action = 'preview'; } } @@ -1847,27 +1777,23 @@ if ($action == 'updatemeta') // Update page if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'confirm_createfromclone' || $action == 'confirm_createpagefromclone') - || ($action == 'preview' && (GETPOST('refreshsite') || GETPOST('refreshpage') || GETPOST('preview')))) -{ + || ($action == 'preview' && (GETPOST('refreshsite') || GETPOST('refreshpage') || GETPOST('preview')))) { $object->fetch(0, $websitekey); $website = $object; - if ($action == 'confirm_createfromclone') - { + if ($action == 'confirm_createfromclone') { $db->begin(); $objectnew = new Website($db); $result = $objectnew->createFromClone($user, GETPOST('id', 'int'), GETPOST('siteref', 'aZ09'), (GETPOST('newlang', 'aZ09') ?GETPOST('newlang', 'aZ09') : '')); - if ($result < 0) - { + if ($result < 0) { $error++; setEventMessages($objectnew->error, $objectnew->errors, 'errors'); $action = 'preview'; $db->rollback(); - } - else { + } else { $object = $objectnew; $id = $object->id; $pageid = $object->fk_default_home; @@ -1877,12 +1803,10 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf } } - if ($action == 'confirm_createpagefromclone') - { + if ($action == 'confirm_createpagefromclone') { $istranslation = (GETPOST('is_a_translation', 'aZ09') == 'on' ? 1 : 0); // Protection if it is a translation page - if ($istranslation) - { + if ($istranslation) { if (GETPOST('newlang', 'aZ09') == $objectpage->lang || !GETPOST('newlang', 'aZ09')) { $error++; setEventMessages($langs->trans("LanguageMustNotBeSameThanClonedPage"), null, 'errors'); @@ -1895,27 +1819,23 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf } } - if (!$error) - { + if (!$error) { $db->begin(); $newwebsiteid = GETPOST('newwebsite', 'int'); $pathofwebsitenew = $pathofwebsite; $tmpwebsite = new Website($db); - if ($newwebsiteid > 0 && $newwebsiteid != $object->id) - { + if ($newwebsiteid > 0 && $newwebsiteid != $object->id) { $tmpwebsite->fetch($newwebsiteid); $pathofwebsitenew = $dolibarr_main_data_root.'/website/'.$tmpwebsite->ref; - } - else { + } else { $tmpwebsite = $object; } $objectpage = new WebsitePage($db); $resultpage = $objectpage->createFromClone($user, $pageid, GETPOST('newpageurl', 'aZ09'), (GETPOST('newlang', 'aZ09') ? GETPOST('newlang', 'aZ09') : ''), $istranslation, $newwebsiteid, GETPOST('newtitle', 'alphanohtml')); - if ($resultpage < 0) - { + if ($resultpage < 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); $action = 'createpagefromclone'; @@ -1933,8 +1853,7 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf dolSavePageContent($filetpl, $tmpwebsite, $resultpage); // Switch on the new page if web site of new page/container is same - if (empty($newwebsiteid) || $newwebsiteid == $object->id) - { + if (empty($newwebsiteid) || $newwebsiteid == $object->id) { $pageid = $resultpage->id; } @@ -1945,47 +1864,39 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf $res = 0; - if (!$error) - { + if (!$error) { // Check symlink to medias and restore it if ko $pathtomedias = DOL_DATA_ROOT.'/medias'; $pathtomediasinwebsite = $pathofwebsite.'/medias'; - if (!is_link(dol_osencode($pathtomediasinwebsite))) - { + if (!is_link(dol_osencode($pathtomediasinwebsite))) { dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); } /*if (GETPOST('savevirtualhost') && $object->virtualhost != GETPOST('previewsite')) - { - $object->virtualhost = GETPOST('previewsite', 'alpha'); - $object->update($user); - }*/ + { + $object->virtualhost = GETPOST('previewsite', 'alpha'); + $object->update($user); + }*/ $objectpage->fk_website = $object->id; - if ($pageid > 0) - { + if ($pageid > 0) { $res = $objectpage->fetch($pageid); - } - else { + } else { $res = 0; - if ($object->fk_default_home > 0) - { + if ($object->fk_default_home > 0) { $res = $objectpage->fetch($object->fk_default_home); } - if (!($res > 0)) - { + if (!($res > 0)) { $res = $objectpage->fetch(0, $object->id); } } } - if (!$error && $res > 0) - { - if ($action == 'updatesource' || $action == 'updatecontent') - { + if (!$error && $res > 0) { + if ($action == 'updatesource' || $action == 'updatecontent') { $db->begin(); $phpfullcodestringold = dolKeepOnlyPhpCode($objectpage->content); @@ -1996,29 +1907,32 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf $phpfullcodestring = dolKeepOnlyPhpCode($objectpage->content); //print dol_escape_htmltag($phpfullcodestring);exit; $forbiddenphpcommands = array("exec", "passthru", "system", "shell_exec", "proc_open"); - if (empty($conf->global->WEBSITE_PHP_ALLOW_WRITE)) // If option is not on, we disallow functions to write files - { + if (empty($conf->global->WEBSITE_PHP_ALLOW_WRITE)) { // If option is not on, we disallow functions to write files $forbiddenphpcommands = array_merge($forbiddenphpcommands, array("fopen", "file_put_contents", "fputs", "fputscsv", "fwrite", "fpassthru", "unlink", "mkdir", "rmdir", "symlink", "touch", "umask")); } - foreach ($forbiddenphpcommands as $forbiddenphpcommand) - { - if (preg_match('/'.$forbiddenphpcommand.'\s*\(/ms', $phpfullcodestring)) - { + foreach ($forbiddenphpcommands as $forbiddenphpcommand) { + if (preg_match('/'.$forbiddenphpcommand.'\s*\(/ms', $phpfullcodestring)) { $error++; setEventMessages($langs->trans("DynamicPHPCodeContainsAForbiddenInstruction", $forbiddenphpcommand), null, 'errors'); - if ($action == 'updatesource') $action = 'editsource'; - if ($action == 'updatecontent') $action = 'editcontent'; + if ($action == 'updatesource') { + $action = 'editsource'; + } + if ($action == 'updatecontent') { + $action = 'editcontent'; + } } } - if (empty($user->rights->website->writephp)) - { - if ($phpfullcodestringold != $phpfullcodestring) - { + if (empty($user->rights->website->writephp)) { + if ($phpfullcodestringold != $phpfullcodestring) { $error++; setEventMessages($langs->trans("NotAllowedToAddDynamicContent"), null, 'errors'); - if ($action == 'updatesource') $action = 'editsource'; - if ($action == 'updatecontent') $action = 'editcontent'; + if ($action == 'updatesource') { + $action = 'editsource'; + } + if ($action == 'updatecontent') { + $action = 'editcontent'; + } } } @@ -2028,16 +1942,18 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf $res = $objectpage->update($user); - if ($res < 0) - { + if ($res < 0) { $error++; setEventMessages($objectpage->error, $objectpage->errors, 'errors'); - if ($action == 'updatesource') $action = 'editsource'; - if ($action == 'updatecontent') $action = 'editcontent'; + if ($action == 'updatesource') { + $action = 'editsource'; + } + if ($action == 'updatecontent') { + $action = 'editcontent'; + } } - if (!$error) - { + if (!$error) { $db->commit(); $filemaster = $pathofwebsite.'/master.inc.php'; @@ -2049,7 +1965,9 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf // Now generate the master.inc.php page $result = dolSaveMasterFile($filemaster); - if (!$result) setEventMessages('Failed to write the master file file '.$filemaster, null, 'errors'); + if (!$result) { + setEventMessages('Failed to write the master file file '.$filemaster, null, 'errors'); + } // Now delete the old alias.php page if we removed one /*if (!empty($fileoldalias)) @@ -2071,16 +1989,16 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf // Save page alias $result = dolSavePageAlias($filealias, $object, $objectpage); - if (!$result) setEventMessages('Failed to write the alias file '.basename($filealias), null, 'errors'); + if (!$result) { + setEventMessages('Failed to write the alias file '.basename($filealias), null, 'errors'); + } // Save page content $result = dolSavePageContent($filetpl, $object, $objectpage); - if ($result) - { + if ($result) { setEventMessages($langs->trans("Saved"), null, 'mesgs'); - if (!GETPOSTISSET('updateandstay')) // If we click on "Save And Stay", we do not make the redirect - { + if (!GETPOSTISSET('updateandstay')) { // If we click on "Save And Stay", we do not make the redirect if ($backtopage) { header("Location: ".$backtopage); exit; @@ -2089,13 +2007,17 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf exit; } } else { - if ($action == 'updatesource') $action = 'editsource'; - if ($action == 'updatecontent') $action = 'editcontent'; + if ($action == 'updatesource') { + $action = 'editsource'; + } + if ($action == 'updatecontent') { + $action = 'editcontent'; + } } } else { setEventMessages('Failed to write file '.$filetpl, null, 'errors'); header("Location: ".$_SERVER["PHP_SELF"].'?website='.$websitekey.'&pageid='.$pageid); - exit; + exit; } } else { $db->rollback(); @@ -2105,10 +2027,8 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf exit; } } else { - if (!$error) - { - if (empty($websitekey) || $websitekey == '-1') - { + if (!$error) { + if (empty($websitekey) || $websitekey == '-1') { setEventMessages($langs->trans("NoWebSiteCreateOneFirst"), null, 'warnings'); } else { setEventMessages($langs->trans("NoPageYet"), null, 'warnings'); @@ -2119,12 +2039,10 @@ if (($action == 'updatesource' || $action == 'updatecontent' || $action == 'conf } // Export site -if ($action == 'exportsite') -{ +if ($action == 'exportsite') { $fileofzip = $object->exportWebSite(); - if ($fileofzip) - { + if ($fileofzip) { $file_name = basename($fileofzip); header("Content-Type: application/zip"); @@ -2133,19 +2051,16 @@ if ($action == 'exportsite') readfile($fileofzip); exit; - } - else { + } else { setEventMessages($object->error, $object->errors, 'errors'); $action = 'preview'; } } // Regenerate site -if ($action == 'regeneratesite') -{ +if ($action == 'regeneratesite') { $result = $object->rebuildWebSiteFiles(); - if ($result > 0) - { + if ($result > 0) { setEventMessages($langs->trans("PagesRegenerated", $result), null, 'mesgs'); $action = 'preview'; } else { @@ -2155,83 +2070,68 @@ if ($action == 'regeneratesite') } // Import site -if ($action == 'importsiteconfirm') -{ - if (empty($_FILES) && !GETPOSTISSET('templateuserfile')) - { +if ($action == 'importsiteconfirm') { + if (empty($_FILES) && !GETPOSTISSET('templateuserfile')) { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors'); $action = 'importsite'; - } - else { - if (!empty($_FILES) || GETPOSTISSET('templateuserfile')) - { + } else { + if (!empty($_FILES) || GETPOSTISSET('templateuserfile')) { // Check symlink to medias and restore it if ko $pathtomedias = DOL_DATA_ROOT.'/medias'; $pathtomediasinwebsite = $pathofwebsite.'/medias'; - if (!is_link(dol_osencode($pathtomediasinwebsite))) - { + if (!is_link(dol_osencode($pathtomediasinwebsite))) { dol_syslog("Create symlink for ".$pathtomedias." into name ".$pathtomediasinwebsite); dol_mkdir(dirname($pathtomediasinwebsite)); // To be sure dir for website exists $result = symlink($pathtomedias, $pathtomediasinwebsite); - if (!$result) - { + if (!$result) { setEventMessages($langs->trans("ErrorFieldToCreateSymLinkToMedias", $pathtomediasinwebsite, $pathtomedias), null, 'errors'); $action = 'importsite'; } } $fileofzip = ''; - if (GETPOSTISSET('templateuserfile')) - { + if (GETPOSTISSET('templateuserfile')) { $fileofzip = DOL_DATA_ROOT.'/doctemplates/websites/'.GETPOST('templateuserfile', 'alpha'); - } - elseif (!empty($_FILES)) - { - if (is_array($_FILES['userfile']['tmp_name'])) $userfiles = $_FILES['userfile']['tmp_name']; - else $userfiles = array($_FILES['userfile']['tmp_name']); + } elseif (!empty($_FILES)) { + if (is_array($_FILES['userfile']['tmp_name'])) { + $userfiles = $_FILES['userfile']['tmp_name']; + } else { + $userfiles = array($_FILES['userfile']['tmp_name']); + } - foreach ($userfiles as $key => $userfile) - { - if (empty($_FILES['userfile']['tmp_name'][$key])) - { + foreach ($userfiles as $key => $userfile) { + if (empty($_FILES['userfile']['tmp_name'][$key])) { $error++; if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) { setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors'); $action = 'importsite'; - } - else { + } else { setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors'); $action = 'importsite'; } } } - if (!$error) - { + if (!$error) { $upload_dir = $conf->website->dir_temp; $result = dol_add_file_process($upload_dir, 1, -1, 'userfile', ''); } // Get name of file (take last one if several name provided) $fileofzip = $upload_dir.'/unknown'; - foreach ($_FILES as $key => $ifile) - { - foreach ($ifile['name'] as $key2 => $ifile2) - { + foreach ($_FILES as $key => $ifile) { + foreach ($ifile['name'] as $key2 => $ifile2) { $fileofzip = $upload_dir.'/'.$ifile2; } } } - if (!$error) - { + if (!$error) { $result = $object->importWebSite($fileofzip); - if ($result < 0) - { + if ($result < 0) { setEventMessages($object->error, $object->errors, 'errors'); $action = 'importsite'; - } - else { + } else { // Force mode dynamic on dolibarr_set_const($db, 'WEBSITE_SUBCONTAINERSINLINE', 1, 'chaine', 0, '', $conf->entity); @@ -2271,7 +2171,9 @@ $moreheadjs = ''; $arrayofjs[] = 'includes/jquery/plugins/blockUI/jquery.blockUI.js'; $arrayofjs[] = 'core/js/blockUI.js'; // Used by ecm/tpl/enabledfiletreeajax.tpl.php -if (empty($conf->global->MAIN_ECM_DISABLE_JS)) $arrayofjs[] = "includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js"; +if (empty($conf->global->MAIN_ECM_DISABLE_JS)) { + $arrayofjs[] = "includes/jquery/plugins/jqueryFileTree/jqueryFileTree.js"; +} $moreheadjs .= '<script type="text/javascript">'."\n"; $moreheadjs .= 'var indicatorBlockUI = \''.DOL_URL_ROOT."/theme/".$conf->theme."/img/working.gif".'\';'."\n"; @@ -2284,56 +2186,43 @@ print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST" enctype="multipart/ print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; -if ($action == 'createsite') -{ +if ($action == 'createsite') { print '<input type="hidden" name="action" value="addsite">'; } -if ($action == 'createcontainer') -{ +if ($action == 'createcontainer') { print '<input type="hidden" name="action" value="addcontainer">'; } -if ($action == 'editcss') -{ +if ($action == 'editcss') { print '<input type="hidden" name="action" value="updatecss">'; } -if ($action == 'editmenu') -{ +if ($action == 'editmenu') { print '<input type="hidden" name="action" value="updatemenu">'; } -if ($action == 'setashome') -{ +if ($action == 'setashome') { print '<input type="hidden" name="action" value="updateashome">'; } -if ($action == 'editmeta') -{ +if ($action == 'editmeta') { print '<input type="hidden" name="action" value="updatemeta">'; } -if ($action == 'editsource') -{ +if ($action == 'editsource') { print '<input type="hidden" name="action" value="updatesource">'; } -if ($action == 'editcontent') -{ +if ($action == 'editcontent') { print '<input type="hidden" name="action" value="updatecontent">'; } -if ($action == 'edit') -{ +if ($action == 'edit') { print '<input type="hidden" name="action" value="update">'; } -if ($action == 'importsite') -{ +if ($action == 'importsite') { print '<input type="hidden" name="action" value="importsiteconfirm">'; } -if ($action == 'file_manager') -{ +if ($action == 'file_manager') { print '<input type="hidden" name="action" value="file_manager">'; } -if ($action == 'replacesite') -{ +if ($action == 'replacesite') { print '<input type="hidden" name="action" value="replacesiteconfirm">'; } -if ($action == 'replacesiteconfirm') -{ +if ($action == 'replacesiteconfirm') { print '<input type="hidden" name="action" value="replacesiteconfirm">'; } @@ -2341,28 +2230,33 @@ print '<div>'; // Add a margin under toolbar ? $style = ''; -if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource' && !GETPOST('createpagefromclone', 'alphanohtml')) $style = ' margin-bottom: 5px;'; +if ($action != 'preview' && $action != 'editcontent' && $action != 'editsource' && !GETPOST('createpagefromclone', 'alphanohtml')) { + $style = ' margin-bottom: 5px;'; +} -if (!GETPOST('hide_websitemenu')) -{ +if (!GETPOST('hide_websitemenu')) { $disabled = ''; - if (empty($user->rights->website->write)) $disabled = ' disabled="disabled"'; + if (empty($user->rights->website->write)) { + $disabled = ' disabled="disabled"'; + } - if ($websitekey) - { + if ($websitekey) { $virtualurl = ''; $dataroot = DOL_DATA_ROOT.'/website/'.$websitekey; - if (!empty($object->virtualhost)) $virtualurl = $object->virtualhost; + if (!empty($object->virtualhost)) { + $virtualurl = $object->virtualhost; + } } $array = array(); - if ($object->id > 0) - { + if ($object->id > 0) { $array = $objectpage->fetchAll($object->id, 'ASC,ASC', 'type_container,pageurl'); $object->lines = $array; } - if (!is_array($array) && $array < 0) dol_print_error('', $objectpage->error, $objectpage->errors); + if (!is_array($array) && $array < 0) { + dol_print_error('', $objectpage->error, $objectpage->errors); + } $atleastonepage = (is_array($array) && count($array) > 0); @@ -2390,21 +2284,26 @@ if (!GETPOST('hide_websitemenu')) print '<span class="websiteselection">'; $out = ''; $out .= '<select name="website" class="minwidth100 width200 maxwidth150onsmartphone" id="website">'; - if (empty($object->records)) $out .= '<option value="-1">&nbsp;</option>'; + if (empty($object->records)) { + $out .= '<option value="-1">&nbsp;</option>'; + } if (!empty($conf->use_javascript_ajax)) { $valueoption = '<span class="classlink">'.img_picto('', 'add', 'class="paddingrightonly"').$langs->trans("AddWebsite").'</span>'; $out .= '<option value="-2" data-html="'.dol_escape_htmltag($valueoption).'">'.$valueoption.'</option>'; } // Loop on each sites $i = 0; - foreach ($object->records as $key => $valwebsite) - { + foreach ($object->records as $key => $valwebsite) { if (empty($websitekey)) { - if ($action != 'createsite') $websitekey = $valwebsite->ref; + if ($action != 'createsite') { + $websitekey = $valwebsite->ref; + } } $out .= '<option value="'.$valwebsite->ref.'"'; - if ($websitekey == $valwebsite->ref) $out .= ' selected'; // To preselect a value + if ($websitekey == $valwebsite->ref) { + $out .= ' selected'; // To preselect a value + } //$outoption = $valwebsite->getLibStatut(3).' '.$valwebsite->ref.' '; $outoption = (($valwebsite->status == $valwebsite::STATUS_DRAFT) ? '<span class="opacitymedium">' : '').$valwebsite->ref.(($valwebsite->status == $valwebsite::STATUS_DRAFT) ? '</span>' : ''); $out .= ' data-html="'.dol_escape_htmltag($outoption).'"'; @@ -2436,8 +2335,7 @@ if (!GETPOST('hide_websitemenu')) print '<input type="image" class="valignmiddle" src="'.img_picto('', 'refresh', '', 0, 1).'" name="refreshsite" value="'.$langs->trans("Load").'">'; } - if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) - { + if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) { print ' &nbsp; '; print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditCss")).'" name="editcss">'; @@ -2449,11 +2347,9 @@ if (!GETPOST('hide_websitemenu')) $exportlabel = $langs->trans("Export"); } - if ($atleastonepage) - { + if ($atleastonepage) { print '<input type="submit" class="button bordertransp" disabled="disabled" value="'.dol_escape_htmltag($importlabel).'" name="importsite">'; - } - else { + } else { print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($importlabel).'" name="importsite">'; } @@ -2474,8 +2370,7 @@ if (!GETPOST('hide_websitemenu')) print '</span>'; - if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) - { + if ($websitekey && $websitekey != '-1' && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) { print '<span class="websiteselection">'; //print '<a href="'.$_SERVER["PHP_SELF"].'?action=file_manager&website='.$website->ref.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("MediaFiles")).'"><span class="fa fa-image"><span></a>'; print dolButtonToOpenUrlInDialogPopup('file_manager', $langs->transnoentitiesnoconv("MediaFiles"), '<span class="fa fa-image"><span>', '/website/index.php?action=file_manager&website='.$website->ref, $disabled); @@ -2494,8 +2389,7 @@ if (!GETPOST('hide_websitemenu')) print '<span class="websitetools websiteselection">'; - if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') - { + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') { $urlext = $virtualurl; $urlint = $urlwithroot.'/public/website/index.php?website='.$websitekey; @@ -2504,22 +2398,16 @@ if (!GETPOST('hide_websitemenu')) $linktotestonwebserver .= '<span class="hideonsmartphone paddingrightonly">'.$langs->trans("TestDeployOnWeb", $virtualurl).'</span>'.img_picto('', 'globe'); $linktotestonwebserver .= '</a>'; $htmltext = ''; - if (empty($object->fk_default_home)) - { + if (empty($object->fk_default_home)) { $htmltext .= '<br><span class="error">'.$langs->trans("YouMustDefineTheHomePage").'</span><br><br>'; - } - elseif (empty($virtualurl)) - { + } elseif (empty($virtualurl)) { //$htmltext .= '<br><span class="error">'.$langs->trans("VirtualHostUrlNotDefined").'</span><br><br>'; - } - else { + } else { $htmltext .= '<br><center>'.$langs->trans("GoTo").' <a href="'.$virtualurl.'" target="_website">'.$virtualurl.'</a></center><br>'; } - if (!empty($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER)) - { + if (!empty($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER)) { $htmltext .= '<br>'.$langs->trans($conf->global->WEBSITE_REPLACE_INFO_ABOUT_USAGE_WITH_WEBSERVER); - } - else { + } else { $htmltext .= $langs->trans("SetHereVirtualHost", $dataroot); $htmltext .= '<br>'; $htmltext .= '<br>'.$langs->trans("CheckVirtualHostPerms", $langs->transnoentitiesnoconv("ReadPerm"), DOL_DOCUMENT_ROOT); @@ -2556,12 +2444,19 @@ if (!GETPOST('hide_websitemenu')) print '</span>'; } - if (in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm'))) - { - if ($action == 'editcss') print '<input type="submit" id="savefilean stay" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">'; - if (preg_match('/^create/', $action) && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; - if (preg_match('/^edit/', $action) && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; - if ($action != 'preview') print '<input type="submit" class="button button-cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">'; + if (in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm'))) { + if ($action == 'editcss') { + print '<input type="submit" id="savefilean stay" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">'; + } + if (preg_match('/^create/', $action) && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') { + print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + } + if (preg_match('/^edit/', $action) && $action != 'file_manager' && $action != 'replacesite' && $action != 'replacesiteconfirm') { + print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + } + if ($action != 'preview') { + print '<input type="submit" class="button button-cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">'; + } } print '</span>'; @@ -2570,8 +2465,7 @@ if (!GETPOST('hide_websitemenu')) // Toolbar for pages // - if ($websitekey && $websitekey != '-1' && !in_array($action, array('editcss', 'editmenu', 'importsite', 'file_manager', 'replacesite', 'replacesiteconfirm')) && !$file_manager) - { + if ($websitekey && $websitekey != '-1' && !in_array($action, array('editcss', 'editmenu', 'importsite', 'file_manager', 'replacesite', 'replacesiteconfirm')) && !$file_manager) { print '</div>'; // Close current websitebar to open a new one print '<!-- Bar for websitepage -->'; @@ -2587,8 +2481,7 @@ if (!GETPOST('hide_websitemenu')) //print '<span class="websiteselection">'; - if ($action != 'addcontainer') - { + if ($action != 'addcontainer') { $out = ''; $s = $formwebsite->selectContainer($website, 'pageid', $pageid, 0, $action, 'maxwidth200onsmartphone'); @@ -2617,8 +2510,7 @@ if (!GETPOST('hide_websitemenu')) } print $out; - } - else { + } else { print $langs->trans("New"); } @@ -2629,47 +2521,50 @@ if (!GETPOST('hide_websitemenu')) // Print nav arrows $pagepreviousid = 0; $pagenextid = 0; - if ($pageid) - { + if ($pageid) { $sql = 'SELECT MAX(rowid) as pagepreviousid FROM '.MAIN_DB_PREFIX.'website_page WHERE rowid < '.$pageid.' AND fk_website = '.$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $pagepreviousid = $obj->pagepreviousid; } + } else { + dol_print_error($db); } - else dol_print_error($db); $sql = 'SELECT MIN(rowid) as pagenextid FROM '.MAIN_DB_PREFIX.'website_page WHERE rowid > '.$pageid.' AND fk_website = '.$object->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $obj = $db->fetch_object($resql); - if ($obj) - { + if ($obj) { $pagenextid = $obj->pagenextid; } + } else { + dol_print_error($db); } - else dol_print_error($db); } - if ($pagepreviousid) print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.$pagepreviousid.'&action='.$action.'">'.img_previous($langs->trans("PreviousContainer")).'</a>'; - else print '<span class="valignmiddle opacitymedium">'.img_previous($langs->trans("Previous")).'</span>'; - if ($pagenextid) print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.$pagenextid.'&action='.$action.'">'.img_next($langs->trans("NextContainer")).'</a>'; - else print '<span class="valignmiddle opacitymedium">'.img_next($langs->trans("Next")).'</span>'; + if ($pagepreviousid) { + print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.$pagepreviousid.'&action='.$action.'">'.img_previous($langs->trans("PreviousContainer")).'</a>'; + } else { + print '<span class="valignmiddle opacitymedium">'.img_previous($langs->trans("Previous")).'</span>'; + } + if ($pagenextid) { + print '<a class="valignmiddle" href="'.$_SERVER['PHP_SELF'].'?website='.urlencode($object->ref).'&pageid='.$pagenextid.'&action='.$action.'">'.img_next($langs->trans("NextContainer")).'</a>'; + } else { + print '<span class="valignmiddle opacitymedium">'.img_next($langs->trans("Next")).'</span>'; + } $websitepage = new WebSitePage($db); - if ($pageid > 0 && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) - { + if ($pageid > 0 && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone')) { $websitepage->fetch($pageid); } - if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') - { + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite') { $disabled = ''; - if (empty($user->rights->website->write)) $disabled = ' disabled="disabled"'; + if (empty($user->rights->website->write)) { + $disabled = ' disabled="disabled"'; + } // Confirmation delete site if ($action == 'deletesite') { @@ -2698,8 +2593,7 @@ if (!GETPOST('hide_websitemenu')) print $formconfirm; } - if ($pageid > 0 && $atleastonepage) // pageid can be set without pages, if homepage of site is set and all pages were removed - { + if ($pageid > 0 && $atleastonepage) { // pageid can be set without pages, if homepage of site is set and all pages were removed // Confirmation to clone if ($action == 'createpagefromclone') { // Create an array for form @@ -2730,7 +2624,7 @@ if (!GETPOST('hide_websitemenu')) $value= $formadmin->select_language($preselectedlanguage, 'newlang', 0, null, $textifempty, 0, 0, 'minwidth200', 1, 0, 0, $onlylang, 1); $formquestion[] = array('type' => 'other', 'name' => 'newlang', 'label' => $form->textwithpicto($langs->trans("Language"), $langs->trans("DefineListOfAltLanguagesInWebsiteProperties")), 'value' => $value); - $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid, $langs->trans('ClonePage'), '', 'confirm_createpagefromclone', $formquestion, 0, 1, 300, 550); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$pageid, $langs->trans('ClonePage'), '', 'confirm_createpagefromclone', $formquestion, 0, 1, 300, 550); print $formconfirm; } @@ -2746,11 +2640,9 @@ if (!GETPOST('hide_websitemenu')) print '<div class="inline-block marginrightonly">'; // Button include dynamic contant print $langs->trans("ShowSubcontainers"); - if (empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) - { + if (empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) { print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=setshowsubcontainers&token='.newToken().'">'.img_picto($langs->trans("ShowSubContainersOnOff", $langs->transnoentitiesnoconv("Off")), 'switch_off', '', false, 0, 0, '', 'nomarginleft').'</a>'; - } - else { + } else { print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=unsetshowsubcontainers&token='.newToken().'">'.img_picto($langs->trans("ShowSubContainersOnOff", $langs->transnoentitiesnoconv("On")), 'switch_on', '', false, 0, 0, '', 'nomarginleft').'</a>'; } print '</div>'; @@ -2807,18 +2699,14 @@ if (!GETPOST('hide_websitemenu')) //$disableeditinline = $websitepage->grabbed_from; $disableeditinline = 0; - if ($disableeditinline) - { + if ($disableeditinline) { //print '<input type="submit" class="button bordertransp" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("OnlyEditionOfSourceForGrabbedContent")).'" value="'.dol_escape_htmltag($langs->trans("EditWithEditor")).'" name="editcontent">'; print '<a class="nobordertransp opacitymedium nohoverborder marginleftonlyshort"'.$disabled.' href="#" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("OnlyEditionOfSourceForGrabbedContent")).'">'.img_picto($langs->trans("OnlyEditionOfSourceForGrabbedContent"), 'switch_off', '', false, 0, 0, '', 'nomarginleft').'</a>'; - } - else { + } else { //print '<input type="submit" class="button nobordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("EditWithEditor")).'" name="editcontent">'; - if (empty($conf->global->WEBSITE_EDITINLINE)) - { + if (empty($conf->global->WEBSITE_EDITINLINE)) { print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=seteditinline&token='.newToken().'">'.img_picto($langs->trans("EditInLineOnOff", $langs->transnoentitiesnoconv("Off")), 'switch_off', '', false, 0, 0, '', 'nomarginleft').'</a>'; - } - else { + } else { print '<a class="nobordertransp nohoverborder marginleftonlyshort valignmiddle"'.$disabled.' href="'.$_SERVER["PHP_SELF"].'?website='.$object->ref.'&pageid='.$websitepage->id.'&action=unseteditinline&token='.newToken().'">'.img_picto($langs->trans("EditInLineOnOff", $langs->transnoentitiesnoconv("On")), 'switch_on', '', false, 0, 0, '', 'nomarginleft').'</a>'; } } @@ -2828,14 +2716,12 @@ if (!GETPOST('hide_websitemenu')) print '</div>'; // Set page as homepage - if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) - { + if ($object->fk_default_home > 0 && $pageid == $object->fk_default_home) { //$disabled=' disabled="disabled"'; //print '<span class="button bordertransp disabled"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fa fa-home"></span></span>'; //print '<input type="submit" class="button bordertransp" disabled="disabled" value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">'; print '<a href="#" class="button bordertransp disabled" disabled="disabled" title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fa fa-home valignmiddle btnTitle-icon"><span></a>'; - } - else { + } else { //$disabled=''; //print '<input type="submit" class="button bordertransp"'.$disabled.' value="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'" name="setashome">'; print '<a href="'.$_SERVER["PHP_SEFL"].'?action=setashome&token='.newToken().'&website='.$website->ref.'&pageid='.$pageid.'" class="button bordertransp"'.$disabled.' title="'.dol_escape_htmltag($langs->trans("SetAsHomePage")).'"><span class="fa fa-home valignmiddle btnTitle-icon"><span></a>'; @@ -2849,8 +2735,7 @@ if (!GETPOST('hide_websitemenu')) print '<span class="websitetools">'; - if (($pageid > 0 && $atleastonepage) && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) - { + if (($pageid > 0 && $atleastonepage) && ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone' || $action == 'deletesite')) { $realpage = $urlwithroot.'/public/website/index.php?website='.$websitekey.'&pageref='.$websitepage->pageurl; $pagealias = $websitepage->pageurl; @@ -2886,30 +2771,34 @@ if (!GETPOST('hide_websitemenu')) // TODO Add js to save alias like we save virtual host name and use dynamic virtual host for url of id=previewpageext } - if (!in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm', 'createsite', 'createcontainer', 'createfromclone', 'createpagefromclone', 'deletesite'))) - { - if ($action == 'editsource' || $action == 'editmeta') print '<input type="submit" id="savefilean stay" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">'; - if (preg_match('/^create/', $action)) print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; - if (preg_match('/^edit/', $action)) print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; - if ($action != 'preview') print '<input type="submit" class="button button-cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">'; + if (!in_array($action, array('editcss', 'editmenu', 'file_manager', 'replacesite', 'replacesiteconfirm', 'createsite', 'createcontainer', 'createfromclone', 'createpagefromclone', 'deletesite'))) { + if ($action == 'editsource' || $action == 'editmeta') { + print '<input type="submit" id="savefilean stay" class="button buttonforacesave" value="'.dol_escape_htmltag($langs->trans("SaveAndStay")).'" name="updateandstay">'; + } + if (preg_match('/^create/', $action)) { + print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + } + if (preg_match('/^edit/', $action)) { + print '<input type="submit" id="savefile" class="button buttonforacesave button-save" value="'.dol_escape_htmltag($langs->trans("Save")).'" name="update">'; + } + if ($action != 'preview') { + print '<input type="submit" class="button button-cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'" name="cancel">'; + } } print '</span>'; // end websitetools print '<span class="websitehelp">'; - if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) - { + if (GETPOST('editsource', 'alpha') || GETPOST('editcontent', 'alpha')) { $url = 'https://wiki.dolibarr.org/index.php/Module_Website'; $htmltext = $langs->transnoentitiesnoconv("YouCanEditHtmlSource", $url); $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSource2", $url); $htmltext .= $langs->transnoentitiesnoconv("YouCanEditHtmlSourceMore", $url); $htmltext .= '<br>'; - if ($conf->browser->layout == 'phone') - { + if ($conf->browser->layout == 'phone') { print $form->textwithpicto('', $htmltext, 1, 'help', 'inline-block', 1, 2, 'tooltipsubstitution'); - } - else { + } else { //img_help(($tooltiptrigger != '' ? 2 : 1), $alt) print $form->textwithpicto($langs->trans("SyntaxHelp").' '.img_help(2, $langs->trans("SyntaxHelp")), $htmltext, 1, 'none', 'inline-block', 1, 2, 'tooltipsubstitution'); } @@ -2917,11 +2806,9 @@ if (!GETPOST('hide_websitemenu')) print '</span>'; // end websitehelp - if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') - { + if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') { // Adding jquery code to change on the fly url of preview ext - if (!empty($conf->use_javascript_ajax)) - { + if (!empty($conf->use_javascript_ajax)) { print '<script type="text/javascript" language="javascript"> jQuery(document).ready(function() { jQuery("#websiteinputurl").keyup(function() { @@ -2979,115 +2866,96 @@ $head = array(); * Edit Site HTML header and CSS */ -if ($action == 'editcss') -{ +if ($action == 'editcss') { print '<div class="fiche">'; print '<br>'; - if (!GETPOSTISSET('WEBSITE_CSS_INLINE')) - { + if (!GETPOSTISSET('WEBSITE_CSS_INLINE')) { $csscontent = @file_get_contents($filecss); // Clean the php css file to remove php code and get only css part $csscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $csscontent); - } - else { + } else { $csscontent = GETPOST('WEBSITE_CSS_INLINE', 'none'); } if (!trim($csscontent)) { $csscontent = '/* CSS content (all pages) */'."\nbody.bodywebsite { margin: 0; font-family: 'Open Sans', sans-serif; }\n.bodywebsite h1 { margin-top: 0; margin-bottom: 0; padding: 10px;}"; } - if (!GETPOSTISSET('WEBSITE_JS_INLINE')) - { + if (!GETPOSTISSET('WEBSITE_JS_INLINE')) { $jscontent = @file_get_contents($filejs); // Clean the php js file to remove php code and get only js part $jscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $jscontent); - } - else { + } else { $jscontent = GETPOST('WEBSITE_JS_INLINE', 'none'); } - if (!trim($jscontent)) $jscontent = '/* JS content (all pages) */'."\n"; + if (!trim($jscontent)) { + $jscontent = '/* JS content (all pages) */'."\n"; + } - if (!GETPOSTISSET('WEBSITE_HTML_HEADER')) - { + if (!GETPOSTISSET('WEBSITE_HTML_HEADER')) { $htmlheadercontent = @file_get_contents($filehtmlheader); // Clean the php htmlheader file to remove php code and get only html part $htmlheadercontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htmlheadercontent); - } - else { + } else { $htmlheadercontent = GETPOST('WEBSITE_HTML_HEADER', 'none'); } - if (!trim($htmlheadercontent)) - { + if (!trim($htmlheadercontent)) { $htmlheadercontent = "<html>\n"; $htmlheadercontent .= $htmlheadercontentdefault; $htmlheadercontent .= "</html>"; - } - else { + } else { $htmlheadercontent = preg_replace('/^\s*<html>/ims', '', $htmlheadercontent); $htmlheadercontent = preg_replace('/<\/html>\s*$/ims', '', $htmlheadercontent); $htmlheadercontent = '<html>'."\n".trim($htmlheadercontent)."\n".'</html>'; } - if (!GETPOSTISSET('WEBSITE_ROBOT')) - { + if (!GETPOSTISSET('WEBSITE_ROBOT')) { $robotcontent = @file_get_contents($filerobot); // Clean the php htmlheader file to remove php code and get only html part $robotcontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $robotcontent); - } - else { + } else { $robotcontent = GETPOST('WEBSITE_ROBOT', 'nothtml'); } - if (!trim($robotcontent)) - { + if (!trim($robotcontent)) { $robotcontent .= "# Robot file. Generated with ".DOL_APPLICATION_TITLE."\n"; $robotcontent .= "User-agent: *\n"; $robotcontent .= "Allow: /public/\n"; $robotcontent .= "Disallow: /administrator/\n"; } - if (!GETPOSTISSET('WEBSITE_HTACCESS')) - { + if (!GETPOSTISSET('WEBSITE_HTACCESS')) { $htaccesscontent = @file_get_contents($filehtaccess); // Clean the php htaccesscontent file to remove php code and get only html part $htaccesscontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $htaccesscontent); - } - else { + } else { $htaccesscontent = GETPOST('WEBSITE_HTACCESS', 'nohtml'); } - if (!trim($htaccesscontent)) - { + if (!trim($htaccesscontent)) { $htaccesscontent .= "# Order allow,deny\n"; $htaccesscontent .= "# Deny from all\n"; } - if (!GETPOSTISSET('WEBSITE_MANIFEST_JSON')) - { + if (!GETPOSTISSET('WEBSITE_MANIFEST_JSON')) { $manifestjsoncontent = @file_get_contents($filemanifestjson); // Clean the manifestjson file to remove php code and get only html part $manifestjsoncontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $manifestjsoncontent); - } - else { + } else { $manifestjsoncontent = GETPOST('WEBSITE_MANIFEST_JSON', 'restricthtml'); } - if (!trim($manifestjsoncontent)) - { + if (!trim($manifestjsoncontent)) { //$manifestjsoncontent.=""; } - if (!GETPOSTISSET('WEBSITE_README')) - { + if (!GETPOSTISSET('WEBSITE_README')) { $readmecontent = @file_get_contents($filereadme); // Clean the readme file to remove php code and get only html part $readmecontent = preg_replace('/<\?php \/\/ BEGIN PHP[^\?]*END PHP \?>\n*/ims', '', $readmecontent); - } - else { + } else { $readmecontent = GETPOST('WEBSITE_README', 'none'); } - if (!trim($readmecontent)) - { + if (!trim($readmecontent)) { //$readmecontent.=""; } @@ -3245,8 +3113,7 @@ if ($action == 'editcss') } -if ($action == 'createsite') -{ +if ($action == 'createsite') { print '<div class="fiche">'; print '<br>'; @@ -3256,12 +3123,14 @@ if ($action == 'createsite') $head[$h][0] = dol_buildpath('/website/index.php',1).'?id='.$object->id; $head[$h][1] = $langs->trans("AddSite"); - $head[$h][2] = 'card'; + $head[$h][2] = 'card'; $h++; - print dol_get_fiche_head($head, 'card', $langs->trans("AddSite"), -1, 'globe'); - */ - if ($action == 'createcontainer') print load_fiche_titre($langs->trans("AddSite")); + print dol_get_fiche_head($head, 'card', $langs->trans("AddSite"), -1, 'globe'); + */ + if ($action == 'createcontainer') { + print load_fiche_titre($langs->trans("AddSite")); + } print '<!-- Add site -->'."\n"; //print '<div class="fichecenter">'; @@ -3269,10 +3138,18 @@ if ($action == 'createsite') print '<table class="border centpercent">'; $siteref = $sitedesc = $sitelang = $siteotherlang = ''; - if (GETPOST('WEBSITE_REF')) $siteref = GETPOST('WEBSITE_REF', 'alpha'); - if (GETPOST('WEBSITE_DESCRIPTION')) $sitedesc = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); - if (GETPOST('WEBSITE_LANG')) $sitelang = GETPOST('WEBSITE_LANG', 'aZ09'); - if (GETPOST('WEBSITE_OTHERLANG')) $siteotherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma'); + if (GETPOST('WEBSITE_REF')) { + $siteref = GETPOST('WEBSITE_REF', 'alpha'); + } + if (GETPOST('WEBSITE_DESCRIPTION')) { + $sitedesc = GETPOST('WEBSITE_DESCRIPTION', 'alpha'); + } + if (GETPOST('WEBSITE_LANG')) { + $sitelang = GETPOST('WEBSITE_LANG', 'aZ09'); + } + if (GETPOST('WEBSITE_OTHERLANG')) { + $siteotherlang = GETPOST('WEBSITE_OTHERLANG', 'aZ09comma'); + } print '<tr><td class="titlefieldcreate fieldrequired">'; print $form->textwithpicto($langs->trans('WebSite'), $langs->trans("Example").': www.mywebsite.com, myportal, ...'); @@ -3317,8 +3194,7 @@ if ($action == 'createsite') print '</table>'; - if ($action == 'createsite') - { + if ($action == 'createsite') { print '<div class="center">'; print '<input class="button" type="submit" name="addcontainer" value="'.$langs->trans("Create").'">'; @@ -3337,8 +3213,7 @@ if ($action == 'createsite') print '<br>'; } -if ($action == 'importsite') -{ +if ($action == 'importsite') { print '<div class="fiche">'; print '<br>'; @@ -3368,8 +3243,7 @@ if ($action == 'importsite') print '<br>'; } -if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of a web site OR properties of a web page -{ +if ($action == 'editmeta' || $action == 'createcontainer') { // Edit properties of a web site OR properties of a web page print '<div class="fiche">'; print '<br>'; @@ -3379,31 +3253,38 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of $head[$h][0] = dol_buildpath('/website/index.php',1).'?id='.$object->id; $head[$h][1] = $langs->trans("AddPage"); - $head[$h][2] = 'card'; + $head[$h][2] = 'card'; $h++; - print dol_get_fiche_head($head, 'card', $langs->trans("AddPage"), -1, 'globe'); - */ - if ($action == 'createcontainer') print load_fiche_titre($langs->trans("AddPage")); + print dol_get_fiche_head($head, 'card', $langs->trans("AddPage"), -1, 'globe'); + */ + if ($action == 'createcontainer') { + print load_fiche_titre($langs->trans("AddPage")); + } print '<!-- Edit or create page/container -->'."\n"; //print '<div class="fichecenter">'; $hiddenfromfetchingafterload = ' hideobject'; $hiddenmanuallyafterload = ' hideobject'; - if (GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching') $hiddenfromfetchingafterload = ''; - if (GETPOST('radiocreatefrom') == 'checkboxcreatemanually') $hiddenmanuallyafterload = ''; + if (GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching') { + $hiddenfromfetchingafterload = ''; + } + if (GETPOST('radiocreatefrom') == 'checkboxcreatemanually') { + $hiddenmanuallyafterload = ''; + } if ($action == 'editmeta' || empty($conf->use_javascript_ajax)) { // No autohide/show in such case $hiddenfromfetchingafterload = ''; $hiddenmanuallyafterload = ''; } - if ($action == 'createcontainer') - { + if ($action == 'createcontainer') { print '<br>'; - if (!empty($conf->use_javascript_ajax)) print '<input type="radio" name="radiocreatefrom" id="checkboxcreatefromfetching" value="checkboxcreatefromfetching"'.(GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching' ? ' checked' : '').'> '; + if (!empty($conf->use_javascript_ajax)) { + print '<input type="radio" name="radiocreatefrom" id="checkboxcreatefromfetching" value="checkboxcreatefromfetching"'.(GETPOST('radiocreatefrom') == 'checkboxcreatefromfetching' ? ' checked' : '').'> '; + } print '<label for="checkboxcreatefromfetching"><span class="opacitymediumxx">'.$langs->trans("CreateByFetchingExternalPage").'</span></label><br>'; print '<hr class="tablecheckboxcreatefromfetching'.$hiddenfromfetchingafterload.'">'; print '<table class="tableforfield centpercent tablecheckboxcreatefromfetching'.$hiddenfromfetchingafterload.'">'; @@ -3424,15 +3305,16 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '<br>'; - if (!empty($conf->use_javascript_ajax)) print '<input type="radio" name="radiocreatefrom" id="checkboxcreatemanually" value="checkboxcreatemanually"'.(GETPOST('radiocreatefrom') == 'checkboxcreatemanually' ? ' checked' : '').'> '; + if (!empty($conf->use_javascript_ajax)) { + print '<input type="radio" name="radiocreatefrom" id="checkboxcreatemanually" value="checkboxcreatemanually"'.(GETPOST('radiocreatefrom') == 'checkboxcreatemanually' ? ' checked' : '').'> '; + } print '<label for="checkboxcreatemanually"><span class="opacitymediumxx">'.$langs->trans("OrEnterPageInfoManually").'</span></label><br>'; print '<hr class="tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">'; } print '<table class="border tableforfield nobackground centpercent tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">'; - if ($action != 'createcontainer') - { + if ($action != 'createcontainer') { print '<tr><td class="titlefield fieldrequired">'; print $langs->trans('IDOfPage').' - '.$langs->trans('InternalURLOfPage'); print '</td><td>'; @@ -3462,9 +3344,8 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of $pageauthorid = $objectpage->fk_user_creat; $pageusermodifid = $objectpage->fk_user_modif; $pageauthoralias = $objectpage->author_alias; - $pagestatus = $objectpage->status; - } - else { + $pagestatus = $objectpage->status; + } else { $type_container = 'page'; $pagedatecreation = dol_now(); $pageauthorid = $user->id; @@ -3472,18 +3353,35 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of $pageauthoralias = ''; $pagestatus = 1; } - if (GETPOST('WEBSITE_TITLE', 'alpha')) $pagetitle = str_replace(array('<', '>'), '', GETPOST('WEBSITE_TITLE', 'alphanohtml')); - if (GETPOST('WEBSITE_PAGENAME', 'alpha')) $pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); - if (GETPOST('WEBSITE_ALIASALT', 'alpha')) $pagealiasalt = str_replace(array('<', '>'), '', GETPOST('WEBSITE_ALIASALT', 'alphanohtml')); - if (GETPOST('WEBSITE_DESCRIPTION', 'alpha')) $pagedescription = str_replace(array('<', '>'), '', GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml')); - if (GETPOST('WEBSITE_IMAGE', 'alpha')) $pageimage = GETPOST('WEBSITE_IMAGE', 'alpha'); - if (GETPOST('WEBSITE_KEYWORDS', 'alpha')) $pagekeywords = str_replace(array('<', '>'), '', GETPOST('WEBSITE_KEYWORDS', 'alphanohtml')); - if (GETPOST('WEBSITE_LANG', 'aZ09')) $pagelang = GETPOST('WEBSITE_LANG', 'aZ09'); - if (GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09')) $pageallowedinframes = GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09'); - if (GETPOST('htmlheader', 'none')) $pagehtmlheader = GETPOST('htmlheader', 'none'); + if (GETPOST('WEBSITE_TITLE', 'alpha')) { + $pagetitle = str_replace(array('<', '>'), '', GETPOST('WEBSITE_TITLE', 'alphanohtml')); + } + if (GETPOST('WEBSITE_PAGENAME', 'alpha')) { + $pageurl = GETPOST('WEBSITE_PAGENAME', 'alpha'); + } + if (GETPOST('WEBSITE_ALIASALT', 'alpha')) { + $pagealiasalt = str_replace(array('<', '>'), '', GETPOST('WEBSITE_ALIASALT', 'alphanohtml')); + } + if (GETPOST('WEBSITE_DESCRIPTION', 'alpha')) { + $pagedescription = str_replace(array('<', '>'), '', GETPOST('WEBSITE_DESCRIPTION', 'alphanohtml')); + } + if (GETPOST('WEBSITE_IMAGE', 'alpha')) { + $pageimage = GETPOST('WEBSITE_IMAGE', 'alpha'); + } + if (GETPOST('WEBSITE_KEYWORDS', 'alpha')) { + $pagekeywords = str_replace(array('<', '>'), '', GETPOST('WEBSITE_KEYWORDS', 'alphanohtml')); + } + if (GETPOST('WEBSITE_LANG', 'aZ09')) { + $pagelang = GETPOST('WEBSITE_LANG', 'aZ09'); + } + if (GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09')) { + $pageallowedinframes = GETPOST('WEBSITE_ALLOWED_IN_FRAMES', 'aZ09'); + } + if (GETPOST('htmlheader', 'none')) { + $pagehtmlheader = GETPOST('htmlheader', 'none'); + } - if ($action != 'createcontainer') - { + if ($action != 'createcontainer') { print '<!-- Status of page -->'."\n"; print '<tr><td class="fieldrequired">'; print $langs->trans('Status'); @@ -3501,8 +3399,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of $formwebsite->selectTypeOfContainer('WEBSITE_TYPE_CONTAINER', (GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha') ? GETPOST('WEBSITE_TYPE_CONTAINER', 'alpha') : $type_container), 0, '', 1); print '</td></tr>'; - if ($action == 'createcontainer') - { + if ($action == 'createcontainer') { print '<tr><td class="titlefield fieldrequired">'; print $langs->trans('WEBSITE_PAGE_EXAMPLE'); print '</td><td>'; @@ -3556,8 +3453,11 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print $langs->trans('Language'); print '</td><td>'; $onlykeys = array(); - if ($object->lang) $onlykeys[$object->lang] = $object->lang; - else $onlykeys[$langs->defaultlang] = $langs->defaultlang; + if ($object->lang) { + $onlykeys[$object->lang] = $object->lang; + } else { + $onlykeys[$langs->defaultlang] = $langs->defaultlang; + } if ($object->otherlang) { $tmparray = explode(',', $object->otherlang); foreach ($tmparray as $key) { @@ -3582,47 +3482,45 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '<!-- Translation of --><tr><td>'; print $langs->trans('TranslationLinks'); print '</td><td>'; - if ($action != 'createcontainer') - { + if ($action != 'createcontainer') { // Has translation pages $sql = 'SELECT rowid, lang from '.MAIN_DB_PREFIX.'website_page where fk_page = '.$objectpage->id; $resql = $db->query($sql); - if ($resql) - { + if ($resql) { $num_rows = $db->num_rows($resql); - if ($num_rows > 0) - { + if ($num_rows > 0) { print '<span class="opacitymedium">'.$langs->trans('ThisPageHasTranslationPages').':</span>'; $i = 0; $tmppage = new WebsitePage($db); $tmpstring = ''; - while ($obj = $db->fetch_object($resql)) - { + while ($obj = $db->fetch_object($resql)) { $result = $tmppage->fetch($obj->rowid); if ($result > 0) { - if ($i > 0) $tmpstring .= '<br>'; + if ($i > 0) { + $tmpstring .= '<br>'; + } $tmpstring .= $tmppage->getNomUrl(1).' ('.$tmppage->lang.')'; $translatedby++; $i++; } } - if ($i > 1) print '<br>'; - else print ' '; + if ($i > 1) { + print '<br>'; + } else { + print ' '; + } print $tmpstring; } + } else { + dol_print_error($db); } - else dol_print_error($db); } - if (empty($translatedby) && ($action == 'editmeta' || $action == 'createcontainer' || $objectpage->fk_page > 0)) - { + if (empty($translatedby) && ($action == 'editmeta' || $action == 'createcontainer' || $objectpage->fk_page > 0)) { $sourcepage = new WebsitePage($db); $result = $sourcepage->fetch($objectpage->fk_page); - if ($result == 0) - { + if ($result == 0) { // not found, we can reset value to clean database - } - elseif ($result > 0) - { + } elseif ($result > 0) { $translationof = $objectpage->fk_page; print '<span class="opacitymedium">'.$langs->trans('ThisPageIsTranslationOf').'</span> '; print $formwebsite->selectContainer($website, 'pageidfortranslation', ($translationof ? $translationof : -1), 1, $action, 'minwidth300', array($objectpage->id)); @@ -3643,8 +3541,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '</td></tr>'; // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { $langs->load('categories'); if (!GETPOSTISSET('categories')) { @@ -3686,8 +3583,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '<tr><td>'; print $langs->trans('Author'); print '</td><td>'; - if ($pageauthorid > 0) - { + if ($pageauthorid > 0) { $fuser->fetch($pageauthorid); print $fuser->getNomUrl(1); } else { @@ -3708,13 +3604,11 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of //print dol_print_date($pagedatecreation, 'dayhour'); print '</td></tr>'; - if ($action != 'createcontainer') - { + if ($action != 'createcontainer') { print '<tr><td>'; print $langs->trans('UserModif'); print '</td><td>'; - if ($pageusermodifid > 0) - { + if ($pageusermodifid > 0) { $fuser->fetch($pageusermodifid); print $fuser->getNomUrl(1); } @@ -3738,8 +3632,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '</td></tr>'; print '</table>'; - if ($action == 'createcontainer') - { + if ($action == 'createcontainer') { print '<div class="center tablecheckboxcreatemanually'.$hiddenmanuallyafterload.'">'; print '<input class="button" type="submit" name="addcontainer" value="'.$langs->trans("Create").'">'; @@ -3748,8 +3641,7 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '</div>'; } - if ($action == 'createcontainer') - { + if ($action == 'createcontainer') { print '<script type="text/javascript" language="javascript"> jQuery(document).ready(function() { var disableautofillofalias = 0; @@ -3794,27 +3686,26 @@ if ($action == 'editmeta' || $action == 'createcontainer') // Edit properties of print '<br>'; } -if ($action == 'editfile' || $action == 'file_manager') -{ +if ($action == 'editfile' || $action == 'file_manager') { print '<!-- Edit Media -->'."\n"; print '<div class="fiche"><br>'; //print '<div class="center">'.$langs->trans("FeatureNotYetAvailable").'</center>'; $module = 'medias'; - if (empty($url)) $url = DOL_URL_ROOT.'/website/index.php'; // Must be an url without param + if (empty($url)) { + $url = DOL_URL_ROOT.'/website/index.php'; // Must be an url without param + } include DOL_DOCUMENT_ROOT.'/core/tpl/filemanager.tpl.php'; print '</div>'; } -if ($action == 'editmenu') -{ +if ($action == 'editmenu') { print '<!-- Edit Menu -->'."\n"; print '<div class="center">'.$langs->trans("FeatureNotYetAvailable").'</center>'; } -if ($action == 'editsource') -{ +if ($action == 'editsource') { // Editing with source editor $contentforedit = ''; @@ -3824,10 +3715,13 @@ if ($action == 'editsource') $contentforedit .= $objectpage->content; //var_dump($_SESSION["dol_screenheight"]); $maxheightwin = 480; - if (isset($_SESSION["dol_screenheight"])) - { - if ($_SESSION["dol_screenheight"] > 680) $maxheightwin = $_SESSION["dol_screenheight"] - 400; - if ($_SESSION["dol_screenheight"] > 800) $maxheightwin = $_SESSION["dol_screenheight"] - 490; + if (isset($_SESSION["dol_screenheight"])) { + if ($_SESSION["dol_screenheight"] > 680) { + $maxheightwin = $_SESSION["dol_screenheight"] - 400; + } + if ($_SESSION["dol_screenheight"] > 800) { + $maxheightwin = $_SESSION["dol_screenheight"] - 490; + } } //var_dump($_SESSION["dol_screenheight"]); require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php'; @@ -3841,8 +3735,8 @@ if ($action == 'editsource') $contentforedit = ''; //$contentforedit.='<style scoped>'."\n"; // "scoped" means "apply to parent element only". Not yet supported by browsers - //$contentforedit.=$csscontent; - //$contentforedit.='</style>'."\n"; + //$contentforedit.=$csscontent; + //$contentforedit.='</style>'."\n"; $contentforedit .= $objectpage->content; $contentforedit = preg_replace('/(<img.*src=")(?!http)/', '\1'.DOL_URL_ROOT.'/viewimage.php?modulepart=medias&file=', $contentforedit, -1, $nbrep); @@ -3856,8 +3750,7 @@ print "</div>\n"; print "</form>\n"; -if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction == 'replace') -{ +if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction == 'replace') { print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">'; print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="replacesiteconfirm">'; @@ -3919,8 +3812,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '</div>'; // Categories - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { print '<div class="tagtr">'; print '<div class="tagtd paddingrightonly marginrightonly opacitymedium" style="padding-right: 10px !important">'; print $langs->trans("Category"); @@ -3939,16 +3831,14 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '</div></div>'; - if ($action == 'replacesiteconfirm') - { + if ($action == 'replacesiteconfirm') { print '<!-- List of search result -->'."\n"; print '<div class="rowsearchresult clearboth">'; print '<br>'; print '<br>'; - if ($listofpages['code'] == 'OK') - { + if ($listofpages['code'] == 'OK') { $arrayofselected = is_array($toselect) ? $toselect : array(); $param = ''; $nbtotalofrecords = count($listofpages['list']); @@ -3957,10 +3847,18 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = // List of mass actions available $arrayofmassactions = array(); - if ($user->rights->website->writephp && $searchkey) $arrayofmassactions['replace'] = $langs->trans("Replace"); - if ($user->rights->website->write) $arrayofmassactions['setcategory'] = $langs->trans("ClassifyInCategory"); - if ($permissiontodelete) $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); - if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) $arrayofmassactions = array(); + if ($user->rights->website->writephp && $searchkey) { + $arrayofmassactions['replace'] = $langs->trans("Replace"); + } + if ($user->rights->website->write) { + $arrayofmassactions['setcategory'] = $langs->trans("ClassifyInCategory"); + } + if ($permissiontodelete) { + $arrayofmassactions['predelete'] = '<span class="fa fa-trash paddingrightonly"></span>'.$langs->trans("Delete"); + } + if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); + } $massactionbutton = $form->selectMassAction('', $arrayofmassactions); $massactionbutton .= '<div class="massactionother massactionreplace hidden">'; @@ -3988,12 +3886,24 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = $param = 'action=replacesiteconfirm&website='.urlencode($website->ref); $param .= '&searchstring='.urlencode($searchkey); - if (GETPOST('optioncontent')) $param .= '&optioncontent=content'; - if (GETPOST('optionmeta')) $param .= '&optionmeta=meta'; - if (GETPOST('optionsitefiles')) $param .= '&optionsitefiles=optionsitefiles'; - if (GETPOST('optioncontainertype')) $param .= '&optioncontainertype='.GETPOST('optioncontainertype', 'aZ09'); - if (GETPOST('optionlanguage')) $param .= '&optionlanguage='.GETPOST('optionlanguage', 'aZ09'); - if (GETPOST('optioncategory')) $param .= '&optioncategory='.GETPOST('optioncategory', 'aZ09'); + if (GETPOST('optioncontent')) { + $param .= '&optioncontent=content'; + } + if (GETPOST('optionmeta')) { + $param .= '&optionmeta=meta'; + } + if (GETPOST('optionsitefiles')) { + $param .= '&optionsitefiles=optionsitefiles'; + } + if (GETPOST('optioncontainertype')) { + $param .= '&optioncontainertype='.GETPOST('optioncontainertype', 'aZ09'); + } + if (GETPOST('optionlanguage')) { + $param .= '&optionlanguage='.GETPOST('optionlanguage', 'aZ09'); + } + if (GETPOST('optioncategory')) { + $param .= '&optioncategory='.GETPOST('optioncategory', 'aZ09'); + } print '<div class="div-table-responsive-no-min">'; print '<table class="noborder centpercent">'; @@ -4012,10 +3922,8 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = $totalnbwords = 0; - foreach ($listofpages['list'] as $answerrecord) - { - if (get_class($answerrecord) == 'WebsitePage') - { + foreach ($listofpages['list'] as $answerrecord) { + if (get_class($answerrecord) == 'WebsitePage') { print '<tr>'; // Type of container @@ -4035,8 +3943,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = // Categories - Tags print '<td>'; - if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) - { + if (!empty($conf->categorie->enabled) && !empty($user->rights->categorie->lire)) { // Get current categories $existing = $c->containing($answerrecord->id, Categorie::TYPE_WEBSITE_PAGE, 'object'); if (is_array($existing)) { @@ -4103,10 +4010,11 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '<td class="nowrap center">'; print '<!-- Status of page -->'."\n"; - if ($massactionbutton || $massaction) - { + if ($massactionbutton || $massaction) { $selected = 0; - if (in_array($answerrecord->id, $arrayofselected)) $selected = 1; + if (in_array($answerrecord->id, $arrayofselected)) { + $selected = 1; + } print '<input id="'.$answerrecord->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$answerrecord->id.'"'.($selected ? ' checked="checked"' : '').'>'; } print '</td>'; @@ -4213,8 +4121,7 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '</table>'; print '</div>'; print '<br>'; - } - else { + } else { print '<div class="warning">'.$listofpages['message'].'</div>'; } @@ -4224,10 +4131,8 @@ if ($action == 'replacesite' || $action == 'replacesiteconfirm' || $massaction = print '</form>'; } -if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') -{ - if ($pageid > 0 && $atleastonepage) - { +if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpagefromclone') { + if ($pageid > 0 && $atleastonepage) { // $filejs // $filecss // $filephp @@ -4291,10 +4196,11 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa $tmp = preg_split('(<style[^>]*>|</style>)', $objectpage->htmlheader); $tmpstyleinheader = ''; $i = 0; - foreach ($tmp as $valtmp) - { + foreach ($tmp as $valtmp) { $i++; - if ($i % 2 == 0) $tmpstyleinheader .= $valtmp."\n"; + if ($i % 2 == 0) { + $tmpstyleinheader .= $valtmp."\n"; + } } $tmpout .= $tmpstyleinheader."\n"; // Clean style that may affect global style of Dolibarr @@ -4312,8 +4218,7 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa $newcontent = $objectpage->content; // If mode WEBSITE_SUBCONTAINERSINLINE is on - if (!empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) - { + if (!empty($conf->global->WEBSITE_SUBCONTAINERSINLINE)) { // TODO Check file $filephp exists, if not create it. //var_dump($filetpl); @@ -4324,8 +4229,7 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa if (empty($res)) { print "ERROR: Failed to include file '".$filephp."'. Try to edit and save page."; } - } catch (Exception $e) - { + } catch (Exception $e) { print $e->getMessage(); } $newcontent = ob_get_contents(); @@ -4333,12 +4237,10 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa } // Change the contenteditable to "true" or "false" when mode Edit Inline is on or off - if (empty($conf->global->WEBSITE_EDITINLINE)) - { + if (empty($conf->global->WEBSITE_EDITINLINE)) { // Remove the contenteditable="true" $newcontent = preg_replace('/(div|section)(\s[^\>]*)contenteditable="true"/', '\1\2', $newcontent); - } - else { + } else { // Keep the contenteditable="true" when mode Edit Inline is on } $out .= dolWebsiteReplacementOfLinks($object, $newcontent, 0, 'html', $objectpage->id)."\n"; @@ -4359,33 +4261,30 @@ if ($action == 'preview' || $action == 'createfromclone' || $action == 'createpa print $out; /*file_put_contents($filetpl, $out); - if (! empty($conf->global->MAIN_UMASK)) - @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); + if (! empty($conf->global->MAIN_UMASK)) + @chmod($filetpl, octdec($conf->global->MAIN_UMASK)); - // Output file on browser - dol_syslog("index.php include $filetpl $filename content-type=$type"); - $original_file_osencoded=dol_osencode($filetpl); // New file name encoded in OS encoding charset + // Output file on browser + dol_syslog("index.php include $filetpl $filename content-type=$type"); + $original_file_osencoded=dol_osencode($filetpl); // New file name encoded in OS encoding charset - // This test if file exists should be useless. We keep it to find bug more easily - if (! file_exists($original_file_osencoded)) - { - dol_print_error(0,$langs->trans("ErrorFileDoesNotExists",$original_file)); - exit; - } + // This test if file exists should be useless. We keep it to find bug more easily + if (! file_exists($original_file_osencoded)) + { + dol_print_error(0,$langs->trans("ErrorFileDoesNotExists",$original_file)); + exit; + } - //include_once $original_file_osencoded; - */ + //include_once $original_file_osencoded; + */ /*print '<iframe class="websiteiframenoborder centpercent" src="'.DOL_URL_ROOT.'/public/website/index.php?website='.$websitekey.'&pageid='.$pageid.'"/>'; - print '</iframe>';*/ - } - else { - if (empty($websitekey) || $websitekey == '-1') - { + print '</iframe>';*/ + } else { + if (empty($websitekey) || $websitekey == '-1') { print '<br><br><div class="center previewnotyetavailable"><span class="">'.$langs->trans("NoWebSiteCreateOneFirst").'</span></div><br><br><br>'; print '<div class="center"><div class="logo_setup"></div></div>'; - } - else { + } else { print '<br><br><div class="center previewnotyetavailable"><span class="">'.$langs->trans("PreviewOfSiteNotYetAvailable", $object->ref).'</span></div><br><br><br>'; print '<div class="center"><div class="logo_setup"></div></div>'; } diff --git a/htdocs/website/samples/wrapper.php b/htdocs/website/samples/wrapper.php index 24b804058ea..b847f607bf3 100644 --- a/htdocs/website/samples/wrapper.php +++ b/htdocs/website/samples/wrapper.php @@ -1,8 +1,12 @@ <?php // BEGIN PHP File wrapper.php - DO NOT MODIFY - It is just a copy of file website/samples/wrapper.php $websitekey = basename(__DIR__); -if (strpos($_SERVER["PHP_SELF"], 'website/samples/wrapper.php')) die("Sample file for website module. Can be called directly."); -if (!defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) { require_once './master.inc.php'; } // Load master if not already loaded +if (strpos($_SERVER["PHP_SELF"], 'website/samples/wrapper.php')) { + die("Sample file for website module. Can be called directly."); +} +if (!defined('USEDOLIBARRSERVER') && !defined('USEDOLIBARREDITOR')) { + require_once './master.inc.php'; +} // Load master if not already loaded include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; $encoding = ''; @@ -17,42 +21,36 @@ $limit = GETPOST('limit', 'int'); // Parameters for RSS $rss = GETPOST('rss', 'aZ09'); -if ($rss) $original_file = 'blog.rss'; +if ($rss) { + $original_file = 'blog.rss'; +} // If we have a hash public (hashp), we guess the original_file. -if (!empty($hashp)) -{ +if (!empty($hashp)) { include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php'; $ecmfile = new EcmFiles($db); $result = $ecmfile->fetch(0, '', '', '', $hashp); - if ($result > 0) - { + if ($result > 0) { $tmp = explode('/', $ecmfile->filepath, 2); // $ecmfile->filepath is relative to document directory // filepath can be 'users/X' or 'X/propale/PR11111' - if (is_numeric($tmp[0])) // If first tmp is numeric, it is subdir of company for multicompany, we take next part. - { + if (is_numeric($tmp[0])) { // If first tmp is numeric, it is subdir of company for multicompany, we take next part. $tmp = explode('/', $tmp[1], 2); } $moduleparttocheck = $tmp[0]; // moduleparttocheck is first part of path - if ($modulepart) // Not required, so often not defined, for link using public hashp parameter. - { - if ($moduleparttocheck == $modulepart) - { + if ($modulepart) { // Not required, so often not defined, for link using public hashp parameter. + if ($moduleparttocheck == $modulepart) { // We remove first level of directory $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir //var_dump($original_file); exit; - } - else { + } else { print 'Bad link. File is from another module part.'; } - } - else { + } else { $modulepart = $moduleparttocheck; $original_file = (($tmp[1] ? $tmp[1].'/' : '').$ecmfile->filename); // this is relative to module dir } - } - else { + } else { print "ErrorFileNotFoundWithSharedLink"; exit; } @@ -60,21 +58,29 @@ if (!empty($hashp)) // Define attachment (attachment=true to force choice popup 'open'/'save as') $attachment = true; -if (preg_match('/\.(html|htm)$/i', $original_file)) $attachment = false; -if (isset($_GET["attachment"])) $attachment = (GETPOST("attachment", 'alphanohtml') ? true : false); -if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS_WEBSITE)) $attachment = false; +if (preg_match('/\.(html|htm)$/i', $original_file)) { + $attachment = false; +} +if (isset($_GET["attachment"])) { + $attachment = (GETPOST("attachment", 'alphanohtml') ? true : false); +} +if (!empty($conf->global->MAIN_DISABLE_FORCE_SAVEAS_WEBSITE)) { + $attachment = false; +} // Define mime type $type = 'application/octet-stream'; -if (GETPOSTISSET('type')) $type = GETPOST('type', 'alpha'); -else $type = dol_mimetype($original_file); +if (GETPOSTISSET('type')) { + $type = GETPOST('type', 'alpha'); +} else { + $type = dol_mimetype($original_file); +} // Security: Delete string ../ into $original_file $original_file = str_replace("../", "/", $original_file); // Cache or not -if (GETPOST("cache", 'aZ09') || image_format_supported($original_file) >= 0) -{ +if (GETPOST("cache", 'aZ09') || image_format_supported($original_file) >= 0) { // Important: Following code is to avoid page request by browser and PHP CPU at // each Dolibarr page access. header('Cache-Control: max-age=3600, public, must-revalidate'); @@ -99,7 +105,9 @@ if ($rss) { $website->fetch('', $websitekey); $filters = array('type_container'=>'blogpost'); - if ($l) $filters['lang'] = $l; + if ($l) { + $filters['lang'] = $l; + } $MAXNEWS = ($limit ? $limit : 20); $arrayofblogs = $websitepage->fetchAll($website->id, 'DESC', 'date_creation', $MAXNEWS, 0, $filters); @@ -118,8 +126,7 @@ if ($rss) { dol_syslog("build_exportfile Build export file format=".$format.", type=".$type.", cachedelay=".$cachedelay.", filename=".$filename.", filters size=".count($filters), LOG_DEBUG); // Clean parameters - if (!$filename) - { + if (!$filename) { $extension = 'rss'; $filename = $format.'.'.$extension; } @@ -132,19 +139,16 @@ if ($rss) { $buildfile = true; - if ($cachedelay) - { + if ($cachedelay) { $nowgmt = dol_now(); include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; - if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) - { + if (dol_filemtime($outputfile) > ($nowgmt - $cachedelay)) { dol_syslog("build_exportfile file ".$outputfile." is not older than now - cachedelay (".$nowgmt." - ".$cachedelay."). Build is canceled"); $buildfile = false; } } - if ($buildfile) - { + if ($buildfile) { $langs->load("other"); $title = $desc = $langs->transnoentities('LatestBlogPosts'); @@ -155,18 +159,17 @@ if ($rss) { // Write file $result = build_rssfile($format, $title, $desc, $eventarray, $outputfiletmp, '', $website->virtualhost.'/wrapper.php?rss=1'.($l ? '&l='.$l : ''), $l); - if ($result >= 0) - { - if (dol_move($outputfiletmp, $outputfile, 0, 1)) $result = 1; - else { + if ($result >= 0) { + if (dol_move($outputfiletmp, $outputfile, 0, 1)) { + $result = 1; + } else { $error = 'Failed to rename '.$outputfiletmp.' into '.$outputfile; dol_syslog("build_exportfile ".$error, LOG_ERR); dol_delete_file($outputfiletmp, 0, 1); print $error; exit(-1); } - } - else { + } else { dol_syslog("build_exportfile build_xxxfile function fails to for format=".$format." outputfiletmp=".$outputfile, LOG_ERR); dol_delete_file($outputfiletmp, 0, 1); $langs->load("errors"); @@ -175,56 +178,63 @@ if ($rss) { } } - if ($result >= 0) - { + if ($result >= 0) { $attachment = false; - if (isset($_GET["attachment"])) $attachment = $_GET["attachment"]; + if (isset($_GET["attachment"])) { + $attachment = $_GET["attachment"]; + } //$attachment = false; $contenttype = 'application/rss+xml'; - if (isset($_GET["contenttype"])) $contenttype = $_GET["contenttype"]; + if (isset($_GET["contenttype"])) { + $contenttype = $_GET["contenttype"]; + } //$contenttype='text/plain'; $outputencoding = 'UTF-8'; - if ($contenttype) header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); - if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); + if ($contenttype) { + header('Content-Type: '.$contenttype.($outputencoding ? '; charset='.$outputencoding : '')); + } + if ($attachment) { + header('Content-Disposition: attachment; filename="'.$filename.'"'); + } // Ajout directives pour resoudre bug IE //header('Cache-Control: Public, must-revalidate'); //header('Pragma: public'); - if ($cachedelay) header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate'); - else header('Cache-Control: private, must-revalidate'); + if ($cachedelay) { + header('Cache-Control: max-age='.$cachedelay.', private, must-revalidate'); + } else { + header('Cache-Control: private, must-revalidate'); + } // Clean parameters $outputfile = $dir_temp.'/'.$filename; $result = readfile($outputfile); - if (!$result) print 'File '.$outputfile.' was empty.'; + if (!$result) { + print 'File '.$outputfile.' was empty.'; + } // header("Location: ".DOL_URL_ROOT.'/document.php?modulepart=agenda&file='.urlencode($filename)); exit; } -} -// Get logos -elseif ($modulepart == "mycompany" && preg_match('/^\/?logos\//', $original_file)) -{ +} elseif ($modulepart == "mycompany" && preg_match('/^\/?logos\//', $original_file)) { + // Get logos readfile(dol_osencode($conf->mycompany->dir_output."/".$original_file)); -} -else { +} else { // Find the subdirectory name as the reference include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; $check_access = dol_check_secure_access_document($modulepart, $original_file, $entity, $refname); $accessallowed = $check_access['accessallowed']; $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals']; $fullpath_original_file = $check_access['original_file']; // $fullpath_original_file is now a full path name - if ($hashp) - { + if ($hashp) { $accessallowed = 1; // When using hashp, link is public so we force $accessallowed $sqlprotectagainstexternals = ''; } // Security: // Limit access if permissions are wrong - if (!$accessallowed) - { + if (!$accessallowed) { print 'Access forbidden'; exit; } @@ -238,8 +248,7 @@ else { $fullpath_original_file_osencoded = dol_osencode($fullpath_original_file); // New file name encoded in OS encoding charset // This test if file exists should be useless. We keep it to find bug more easily - if (!file_exists($fullpath_original_file_osencoded)) - { + if (!file_exists($fullpath_original_file_osencoded)) { print "ErrorFileDoesNotExists: ".$original_file; exit; } @@ -248,13 +257,20 @@ else { //top_httphead($type); header('Content-Type: '.$type); header('Content-Description: File Transfer'); - if ($encoding) header('Content-Encoding: '.$encoding); + if ($encoding) { + header('Content-Encoding: '.$encoding); + } // Add MIME Content-Disposition from RFC 2183 (inline=automatically displayed, attachment=need user action to open) - if ($attachment) header('Content-Disposition: attachment; filename="'.$filename.'"'); - else header('Content-Disposition: inline; filename="'.$filename.'"'); + if ($attachment) { + header('Content-Disposition: attachment; filename="'.$filename.'"'); + } else { + header('Content-Disposition: inline; filename="'.$filename.'"'); + } header('Content-Length: '.dol_filesize($fullpath_original_file)); readfile($fullpath_original_file_osencoded); } -if (is_object($db)) $db->close(); +if (is_object($db)) { + $db->close(); +} // END PHP diff --git a/htdocs/website/websiteaccount_card.php b/htdocs/website/websiteaccount_card.php index 17f50e709b7..e63c3cb8fef 100644 --- a/htdocs/website/websiteaccount_card.php +++ b/htdocs/website/websiteaccount_card.php @@ -53,12 +53,15 @@ $search_array_options = $extrafields->getOptionalsFromPost($object->table_elemen // Initialize array of search criterias $search_all = GETPOST("search_all", 'alpha'); $search = array(); -foreach ($object->fields as $key => $val) -{ - if (GETPOST('search_'.$key, 'alpha')) $search[$key] = GETPOST('search_'.$key, 'alpha'); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } } -if (empty($action) && empty($id) && empty($ref)) $action = 'view'; +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} // Security check - Protection if external user //if ($user->socid > 0) accessforbidden(); @@ -80,10 +83,11 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be includ $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} -if (empty($reshook)) -{ +if (empty($reshook)) { $error = 0; $permissiontoadd = $user->rights->website->write; @@ -130,8 +134,7 @@ jQuery(document).ready(function() { // Part to create -if ($action == 'create') -{ +if ($action == 'create') { print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("WebsiteAccount"))); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; @@ -163,8 +166,7 @@ if ($action == 'create') } // Part to edit record -if (($id || $ref) && $action == 'edit') -{ +if (($id || $ref) && $action == 'edit') { print load_fiche_titre($langs->trans("WebsiteAccount")); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; @@ -194,9 +196,10 @@ if (($id || $ref) && $action == 'edit') } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ - if ($object->fk_soc > 0 && empty($socid)) $socid = $object->fk_soc; +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { + if ($object->fk_soc > 0 && empty($socid)) { + $socid = $object->fk_soc; + } $res = $object->fetch_optionals(); @@ -213,8 +216,11 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Call Hook formConfirm $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook - if (empty($reshook)) $formconfirm .= $hookmanager->resPrint; - elseif ($reshook > 0) $formconfirm = $hookmanager->resPrint; + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } // Print form confirm print $formconfirm; @@ -223,8 +229,12 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Object card // ------------------------------------------------------------ $linkback = ''; - if ($socid) $linkback = '<a href="'.DOL_URL_ROOT.'/societe/website.php?socid='.$socid.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToListForThirdParty").'</a>'; - if ($fk_website) $linkback = '<a href="'.DOL_URL_ROOT.'/website/website_card.php?fk_website='.$fk_website.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; + if ($socid) { + $linkback = '<a href="'.DOL_URL_ROOT.'/societe/website.php?socid='.$socid.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToListForThirdParty").'</a>'; + } + if ($fk_website) { + $linkback = '<a href="'.DOL_URL_ROOT.'/website/website_card.php?fk_website='.$fk_website.'&restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>'; + } $morehtmlref = '<div class="refidno">'; /* @@ -236,41 +246,43 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea // Project if (! empty($conf->projet->enabled)) { - $langs->load("projects"); - $morehtmlref.='<br>'.$langs->trans('Project') . ' '; - if ($user->rights->website->creer) - { - if ($action != 'classify') - { - $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; - if ($action == 'classify') { - //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); - $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; - $morehtmlref.='<input type="hidden" name="action" value="classin">'; - $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; - $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); - $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; - $morehtmlref.='</form>'; - } 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.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; - $morehtmlref.=$proj->ref; - $morehtmlref.='</a>'; - } else { - $morehtmlref.=''; - } - } + $langs->load("projects"); + $morehtmlref.='<br>'.$langs->trans('Project') . ' '; + if ($user->rights->website->creer) + { + if ($action != 'classify') + { + $morehtmlref.='<a class="editfielda" href="' . $_SERVER['PHP_SELF'] . '?action=classify&amp;id=' . $object->id . '">' . img_edit($langs->transnoentitiesnoconv('SetProject')) . '</a> : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='<form method="post" action="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'">'; + $morehtmlref.='<input type="hidden" name="action" value="classin">'; + $morehtmlref.='<input type="hidden" name="token" value="'.newToken().'">'; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.='<input type="submit" class="button valignmiddle" value="'.$langs->trans("Modify").'">'; + $morehtmlref.='</form>'; + } 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.='<a href="'.DOL_URL_ROOT.'/projet/card.php?id=' . $object->fk_project . '" title="' . $langs->trans('ShowProject') . '">'; + $morehtmlref.=$proj->ref; + $morehtmlref.='</a>'; + } else { + $morehtmlref.=''; + } + } } */ $morehtmlref .= '</div>'; - if ($socid > 0) $object->next_prev_filter = 'te.fk_soc = '.$socid; + if ($socid > 0) { + $object->next_prev_filter = 'te.fk_soc = '.$socid; + } dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'rowid', $morehtmlref); @@ -301,36 +313,35 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '<div class="tabsAction">'."\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 ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } - if (empty($reshook)) - { + if (empty($reshook)) { // Send if (empty($user->socid)) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&mode=init#formmailbeforetitle">'.$langs->trans('SendMail').'</a></div>'."\n"; } - if ($user->rights->website->write) - { + if ($user->rights->website->write) { print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n"; } /* - if ($user->rights->sellyoursaas->create) - { - if ($object->status == 1) - { - print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a></div>'."\n"; - } - else - { - print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a></div>'."\n"; - } - } - */ - - if ($user->rights->website->delete) + if ($user->rights->sellyoursaas->create) { + if ($object->status == 1) + { + print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=disable">'.$langs->trans("Disable").'</a></div>'."\n"; + } + else + { + print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=enable">'.$langs->trans("Enable").'</a></div>'."\n"; + } + } + */ + + if ($user->rights->website->delete) { print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n"; } } @@ -343,21 +354,20 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea $action = 'presend'; } - if ($action != 'presend') - { + if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre print '</div><div class="fichehalfright"><div class="ficheaddleft">'; /* - $MAXEVENT = 10; + $MAXEVENT = 10; - // List of actions on element - include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; - $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT); - */ + // List of actions on element + include_once DOL_DOCUMENT_ROOT . '/core/class/html.formactions.class.php'; + $formactions = new FormActions($db); + $somethingshown = $formactions->showactions($object, 'websiteaccount', $socid, 1, '', $MAXEVENT); + */ print '</div></div></div>'; } From 00d2d28d687cc3e85edd62b2a1646b53bc410947 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 12:34:41 +0100 Subject: [PATCH 59/64] NEW: Can create a lot from list Make code like modulebuilder --- .../product/stock/class/productlot.class.php | 3 +- htdocs/product/stock/productlot_card.php | 263 +++++++++++------- htdocs/product/stock/productlot_list.php | 9 +- 3 files changed, 174 insertions(+), 101 deletions(-) diff --git a/htdocs/product/stock/class/productlot.class.php b/htdocs/product/stock/class/productlot.class.php index 90df912e69d..96650c034f3 100644 --- a/htdocs/product/stock/class/productlot.class.php +++ b/htdocs/product/stock/class/productlot.class.php @@ -95,7 +95,8 @@ class Productlot extends CommonObject 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'position'=>500), 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501), 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'), - 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511) + 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511), + 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000), ); /** diff --git a/htdocs/product/stock/productlot_card.php b/htdocs/product/stock/productlot_card.php index 64902b02e86..0fd29543c6c 100644 --- a/htdocs/product/stock/productlot_card.php +++ b/htdocs/product/stock/productlot_card.php @@ -36,8 +36,35 @@ $langs->loadLangs(array('stocks', 'other', 'productbatch')); // Get parameters $id = GETPOST('id', 'int'); -$action = GETPOST('action', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'myobjectcard'; // To manage different context of search $backtopage = GETPOST('backtopage', 'alpha'); + +// Initialize technical objects +$object = new ProductLot($db); +$extrafields = new ExtraFields($db); +$hookmanager->initHooks(array('productlotcard', 'globalcard')); // Note that conf->hooks_modules contains array + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Initialize array of search criterias +$search_all = GETPOST("search_all", 'alpha'); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } +} + +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} + $batch = GETPOST('batch', 'alpha'); $productid = GETPOST('productid', 'int'); $ref = GETPOST('ref', 'alpha'); // ref is productid_batch @@ -51,22 +78,6 @@ $search_import_key = GETPOST('search_import_key', 'int'); if (empty($action) && empty($id) && empty($ref)) $action = 'list'; - -// Protection if external user -if ($user->socid > 0) -{ - //accessforbidden(); -} -//$result = restrictedArea($user, 'mymodule', $id); - - -$object = new ProductLot($db); -$extrafields = new ExtraFields($db); -$formfile = new FormFile($db); - -// fetch optionals attributes and labels -$extrafields->fetch_name_optionals_label($object->table_element); - // Load object //include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals if ($id || $ref) @@ -81,6 +92,15 @@ if ($id || $ref) $object->ref = $object->batch; // For document management ( it use $object->ref) } +// Protection if external user +if ($user->socid > 0) +{ + //accessforbidden(); +} +//$result = restrictedArea($user, 'mymodule', $id); + + + // Initialize technical object to manage hooks of modules. Note that conf->hooks_modules contains array array $hookmanager->initHooks(array('productlotcard', 'globalcard')); @@ -93,16 +113,26 @@ $usercanread = $user->rights->produit->lire; $usercancreate = $user->rights->produit->creer; $usercandelete = $user->rights->produit->supprimer; +$upload_dir = $conf->productbatch->multidir_output[$conf->entity]; + +$permissiontoadd = $usercancreate; + + /* * Actions */ $parameters = array(); $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks -if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +if (empty($reshook)) { + $error = 0; + + $backurlforlist = dol_buildpath('/product/stock/productlot_list.php', 1); -if (empty($reshook)) -{ if ($action == 'seteatby' && $user->rights->stock->creer) { $newvalue = dol_mktime(12, 0, 0, $_POST['eatbymonth'], $_POST['eatbyday'], $_POST['eatbyyear']); @@ -117,6 +147,11 @@ if (empty($reshook)) if ($result < 0) dol_print_error($db, $object->error); } + $triggermodname = 'PRODUCT_LOT_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'; + /* if ($action == 'update_extras') { $object->oldcopy = dol_clone($object); @@ -152,8 +187,6 @@ if (empty($reshook)) $error = 0; - /* object_prop_getpost_prop */ - $object->entity = GETPOST('entity', 'int'); $object->fk_product = GETPOST('fk_product', 'int'); $object->batch = GETPOST('batch', 'alpha'); @@ -241,11 +274,15 @@ if (empty($reshook)) else setEventMessages($object->error, null, 'errors'); } } - - // Actions to build doc - $upload_dir = $conf->productbatch->multidir_output[$conf->entity]; - $permissiontoadd = $usercancreate; +*/ + // Action to build doc include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + + // Actions to send emails + $triggersendname = 'PRODUCT_LOT_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_PRODUCT_LOT_TO'; + $trackid = 'productlot'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; } @@ -255,69 +292,98 @@ if (empty($reshook)) * View */ -llxHeader('', 'ProductLot', ''); - $form = new Form($db); +$formfile = new FormFile($db); + +$title = $langs->trans("ProductLot"); +$help_url = ''; +llxHeader('', $title, $help_url); + // Part to create -if ($action == 'create') -{ - print load_fiche_titre($langs->trans("Batch")); +if ($action == 'create') { + print load_fiche_titre($langs->trans("Batch"), '', 'object_'.$object->picto); print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">'; + print '<input type="hidden" name="token" value="'.newToken().'">'; print '<input type="hidden" name="action" value="add">'; - print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + if ($backtopage) { + print '<input type="hidden" name="backtopage" value="'.$backtopage.'">'; + } + if ($backtopageforcancel) { + print '<input type="hidden" name="backtopageforcancel" value="'.$backtopageforcancel.'">'; + } - print dol_get_fiche_head(); + print dol_get_fiche_head(array(), ''); - print '<table class="border centpercent">'."\n"; - // print '<tr><td class="fieldrequired">'.$langs->trans("Label").'</td><td><input class="flat" type="text" size="36" name="label" value="'.$label.'"></td></tr>'; - // - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldfk_product").'</td><td><input class="flat" type="text" name="fk_product" value="'.GETPOST('fk_product').'"></td></tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldbatch").'</td><td><input class="flat" type="text" name="batch" value="'.GETPOST('batch').'"></td></tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldfk_user_creat").'</td><td><input class="flat" type="text" name="fk_user_creat" value="'.GETPOST('fk_user_creat').'"></td></tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldfk_user_modif").'</td><td><input class="flat" type="text" name="fk_user_modif" value="'.GETPOST('fk_user_modif').'"></td></tr>'; - print '<tr><td class="fieldrequired">'.$langs->trans("Fieldimport_key").'</td><td><input class="flat" type="text" name="import_key" value="'.GETPOST('import_key').'"></td></tr>'; + // Set some default values + //if (! GETPOSTISSET('fieldname')) $_POST['fieldname'] = 'myvalue'; + + print '<table class="border centpercent tableforfieldcreate">'."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; print '</table>'."\n"; print dol_get_fiche_end(); - print '<div class="center"><input type="submit" class="button" name="add" value="'.$langs->trans("Create").'"> &nbsp; <input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'"></div>'; + print '<div class="center">'; + print '<input type="submit" class="button" name="add" value="'.dol_escape_htmltag($langs->trans("Create")).'">'; + print '&nbsp; '; + print '<input type="'.($backtopage ? "submit" : "button").'" class="button button-cancel" name="cancel" value="'.dol_escape_htmltag($langs->trans("Cancel")).'"'.($backtopage ? '' : ' onclick="javascript:history.go(-1)"').'>'; // Cancel for create does not post form if we don't know the backtopage + print '</div>'; print '</form>'; + + //dol_set_focus('input[name="ref"]'); } // Part to show record -if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) -{ +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { $res = $object->fetch_optionals(); - //print load_fiche_titre($langs->trans("Batch")); - $head = productlot_prepare_head($object); - print dol_get_fiche_head($head, 'card', $langs->trans("Batch"), -1, 'barcode'); - + print dol_get_fiche_head($head, 'card', $langs->trans("Batch"), -1, $object->picto); + $formconfirm = ''; + + // Confirmation to delete if ($action == 'delete') { $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBatch'), $langs->trans('ConfirmDeleteBatch'), 'confirm_delete', '', 0, 1); - print $formconfirm; } - + // Call Hook formConfirm + $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); + $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } + + // Print form confirm + print $formconfirm; + + // Object card + // ------------------------------------------------------------ $linkback = '<a href="'.DOL_URL_ROOT.'/product/stock/productlot_list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>'; $shownav = 1; if ($user->socid && !in_array('batch', explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL))) $shownav = 0; - dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch'); + $morehtmlref = ''; + + dol_banner_tab($object, 'id', $linkback, $shownav, 'rowid', 'batch', $morehtmlref); print '<div class="fichecenter">'; print '<div class="underbanner clearboth"></div>'; - - print '<table class="border centpercent">'."\n"; + print '<table class="border centpercent tableforfield">'."\n"; // Product print '<tr><td class="titlefield">'.$langs->trans("Product").'</td><td>'; @@ -345,44 +411,49 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print '</td>'; print '</tr>'; } - // Other attributes - $cols = 2; + + // Other attributes. Fields from hook formObjectOptions and Extrafields. include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php'; print '</table>'; print '</div>'; + print '<div class="clearboth"></div>'; + print dol_get_fiche_end(); - - // Buttons - print '<div class="tabsAction">'."\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)) - { - /*TODO if ($user->rights->stock->lire) - { - print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n"; - } - - if ($user->rights->stock->supprimer) - { - print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n"; - } - */ - } - print '</div>'."\n"; - - + // Link to other lists print '<a href="'.DOL_URL_ROOT.'/product/reassortlot.php?sref='.urlencode($producttmp->ref).'&search_batch='.urlencode($object->batch).'">'.$langs->trans("ShowCurrentStockOfLot").'</a><br>'; print '<br>'; print '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?search_product_ref='.urlencode($producttmp->ref).'&search_batch='.urlencode($object->batch).'">'.$langs->trans("ShowLogOfMovementIfLot").'</a><br>'; - + print '<br>'; + + + // Buttons for actions + if ($action != 'presend' && $action != 'editline') { + print '<div class="tabsAction">'."\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)) { + /*TODO if ($user->rights->stock->lire) + { + print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=edit">'.$langs->trans("Modify").'</a></div>'."\n"; + } + + if ($user->rights->stock->supprimer) + { + print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a></div>'."\n"; + } + */ + } + + print '</div>'."\n"; + } + } @@ -391,30 +462,32 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea * Documents generes */ -if (empty($action)) -{ +if ($action != 'presend') { print '<div class="fichecenter"><div class="fichehalfleft">'; print '<a name="builddoc"></a>'; // ancre + $includedocgeneration = 1; + // Documents - $filedir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product_batch').dol_sanitizeFileName($object->ref); - $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; - $genallowed = $usercanread; - $delallowed = $usercancreate; + if ($includedocgeneration) { + $objref = dol_sanitizeFileName($object->ref); + $relativepath = $objref.'/'.$objref.'.pdf'; + $filedir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product_batch').dol_sanitizeFileName($object->ref); + $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; + $genallowed = $usercanread; // If you can read, you can build the PDF to read content + $delallowed = $usercancreate; // If you can create/edit, you can remove a file on card + print $formfile->showdocuments('product_batch', $objref, $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 28, 0, '', 0, '', $langs->default_lang, '', $object); + } - print $formfile->showdocuments('product_batch', dol_sanitizeFileName($object->ref), $filedir, $urlsource, $genallowed, $delallowed, '', 0, 0, 0, 28, 0, '', 0, '', $object->default_lang, '', $object); - $somethingshown = $formfile->numoffiles; - - print '</div>'; - - // List of actions on element - print '<div class="fichehalfright"><div class="ficheaddleft">'; + print '</div><div class="fichehalfright"><div class="ficheaddleft">'; + + $MAXEVENT = 10; + include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php'; $formactions = new FormActions($db); - $somethingshown = $formactions->showactions($object, 'productlot', $socid, 1); - print '</div></div>'; + $somethingshown = $formactions->showactions($object, 'productlot', $socid, 1, '', $MAXEVENT); - print '</div>'; + print '</div></div></div>'; } // End of page diff --git a/htdocs/product/stock/productlot_list.php b/htdocs/product/stock/productlot_list.php index e03de931a58..6e818be629d 100644 --- a/htdocs/product/stock/productlot_list.php +++ b/htdocs/product/stock/productlot_list.php @@ -124,9 +124,9 @@ if (is_array($extrafields->attributes[$object->table_element]['label']) && count $object->fields = dol_sort_array($object->fields, 'position'); $arrayfields = dol_sort_array($arrayfields, 'position'); -$permissiontoread = $user->rights->stock->read; -$permissiontoadd = $user->rights->stock->write; -$permissiontodelete = $user->rights->stock->delete; +$permissiontoread = $user->rights->stock->lire; +$permissiontoadd = $user->rights->stock->mouvement->creer; +//$permissiontodelete = $user->rights->stock->supprimer; @@ -321,8 +321,7 @@ print '<input type="hidden" name="sortorder" value="'.$sortorder.'">'; //print '<input type="hidden" name="page" value="'.$page.'">'; print '<input type="hidden" name="contextpage" value="'.$contextpage.'">'; -$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/mymodule/myobject_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); -$newcardbutton = ''; +$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/product/stock/productlot_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); From 16906abc097f27e538038b97781caf7f4e351004 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 12:47:57 +0100 Subject: [PATCH 60/64] FIX File attachment on lots --- htdocs/core/class/conf.class.php | 4 ++-- htdocs/product/stock/productlot_card.php | 2 +- htdocs/product/stock/productlot_document.php | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/htdocs/core/class/conf.class.php b/htdocs/core/class/conf.class.php index 3191e5edd47..39600605414 100644 --- a/htdocs/core/class/conf.class.php +++ b/htdocs/core/class/conf.class.php @@ -437,8 +437,8 @@ class Conf $this->service->dir_temp = $rootfortemp."/produit/temp"; // Module productbatch - $this->productbatch->multidir_output = array($this->entity => $rootfordata."/produitlot"); - $this->productbatch->multidir_temp = array($this->entity => $rootfortemp."/produitlot/temp"); + $this->productbatch->multidir_output = array($this->entity => $rootfordata."/productlot"); + $this->productbatch->multidir_temp = array($this->entity => $rootfortemp."/productlot/temp"); // Module contrat $this->contrat->multidir_output = array($this->entity => $rootfordata."/contract"); diff --git a/htdocs/product/stock/productlot_card.php b/htdocs/product/stock/productlot_card.php index 8601ce25ebc..0968e2ea7ce 100644 --- a/htdocs/product/stock/productlot_card.php +++ b/htdocs/product/stock/productlot_card.php @@ -397,7 +397,7 @@ if (empty($action)) print '<a name="builddoc"></a>'; // ancre // Documents - $filedir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product_batch').dol_sanitizeFileName($object->ref); + $filedir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, 'product_batch'); $urlsource = $_SERVER["PHP_SELF"]."?id=".$object->id; $genallowed = $usercanread; $delallowed = $usercancreate; diff --git a/htdocs/product/stock/productlot_document.php b/htdocs/product/stock/productlot_document.php index 535486f8c62..2882bbf1c9f 100644 --- a/htdocs/product/stock/productlot_document.php +++ b/htdocs/product/stock/productlot_document.php @@ -26,7 +26,7 @@ /** * \file htdocs/product/stock/productlot_document.php * \ingroup product - * \brief Page des documents joints sur les lots produits + * \brief Page of attached documents for porudct lots */ require '../../main.inc.php'; @@ -79,7 +79,7 @@ if ($id || $ref) $object->fetch($id, $productid, $batch); $object->ref = $object->batch; // For document management ( it use $object->ref) - if (!empty($conf->productbatch->enabled)) $upload_dir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 0, $object, $modulepart).dol_sanitizeFileName($object->ref); + if (!empty($conf->productbatch->enabled)) $upload_dir = $conf->productbatch->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, $modulepart); } From 886965be7604250b3e4fec896f119195be3b61bb Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 12:54:57 +0100 Subject: [PATCH 61/64] Show product on lot record tab document --- htdocs/product/stock/productlot_document.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/htdocs/product/stock/productlot_document.php b/htdocs/product/stock/productlot_document.php index db3e5aebe14..ca522f48da7 100644 --- a/htdocs/product/stock/productlot_document.php +++ b/htdocs/product/stock/productlot_document.php @@ -142,6 +142,13 @@ if ($object->id) print '<div class="underbanner clearboth"></div>'; print '<table class="border tableforfield" width="100%">'; + // Product + print '<tr><td class="titlefield">'.$langs->trans("Product").'</td><td>'; + $producttmp = new Product($db); + $producttmp->fetch($object->fk_product); + print $producttmp->getNomUrl(1, 'stock')." - ".$producttmp->label; + print '</td></tr>'; + print '<tr><td class="titlefield">'.$langs->trans("NbOfAttachedFiles").'</td><td colspan="3">'.count($filearray).'</td></tr>'; print '<tr><td>'.$langs->trans("TotalSizeOfAttachedFiles").'</td><td colspan="3">'.dol_print_size($totalsize, 1, 1).'</td></tr>'; print '</table>'; From cb1e36de9ca910ad84cfcb1303b6d60d924004cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fr=C3=A9d=C3=A9ric=20FRANCE?= <frederic34@users.noreply.github.com> Date: Fri, 26 Feb 2021 12:58:41 +0100 Subject: [PATCH 62/64] really fix typo --- htdocs/projet/event.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/htdocs/projet/event.php b/htdocs/projet/event.php index 91f763a5e83..8cbd1895b89 100644 --- a/htdocs/projet/event.php +++ b/htdocs/projet/event.php @@ -30,7 +30,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php'; // Load translation files required by the page -$langs->load('projects', 'enventorganization'); +$langs->load('projects', 'eventorganization'); $action = GETPOST('action', 'aZ09'); $id = GETPOST('id', 'int'); From ad63ac6bb0b95ca5b64aefcb09af28b54fe4c0c3 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 13:08:24 +0100 Subject: [PATCH 63/64] Update societe.class.php --- htdocs/societe/class/societe.class.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 899e03438f5..0ac078280c1 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1601,7 +1601,7 @@ class Societe extends CommonObject $sql .= ', fj.libelle as forme_juridique'; $sql .= ', e.libelle as effectif'; $sql .= ', c.code as country_code, c.label as country'; - $sql .= ', d.code_departement as state_code,r.code_region as region_code, d.nom as state'; + $sql .= ', d.code_departement as state_code, d.nom as state, r.code_region as region_code'; $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto'; $sql .= ', te.code as typent_code'; $sql .= ', i.libelle as label_incoterms'; @@ -1612,7 +1612,7 @@ class Societe extends CommonObject $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid'; - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.rowid '; + $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_regions as r ON d.fk_region = r.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid'; $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'societe_remise as sr ON sr.rowid = (SELECT MAX(rowid) FROM '.MAIN_DB_PREFIX.'societe_remise WHERE fk_soc = s.rowid AND entity IN ('.getEntity('discount').'))'; From a296b86ee1a4f75cbadef9e5cb5030eeaaae6973 Mon Sep 17 00:00:00 2001 From: Laurent Destailleur <eldy@destailleur.fr> Date: Fri, 26 Feb 2021 13:15:02 +0100 Subject: [PATCH 64/64] Update societe.class.php --- htdocs/societe/class/societe.class.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php index 0ac078280c1..115750dd0ab 100644 --- a/htdocs/societe/class/societe.class.php +++ b/htdocs/societe/class/societe.class.php @@ -1601,7 +1601,8 @@ class Societe extends CommonObject $sql .= ', fj.libelle as forme_juridique'; $sql .= ', e.libelle as effectif'; $sql .= ', c.code as country_code, c.label as country'; - $sql .= ', d.code_departement as state_code, d.nom as state, r.code_region as region_code'; + $sql .= ', d.code_departement as state_code, d.nom as state'; + $sql .= ', r.rowid as region_id, r.code_region as region_code'; $sql .= ', st.libelle as stcomm, st.picto as stcomm_picto'; $sql .= ', te.code as typent_code'; $sql .= ', i.libelle as label_incoterms'; @@ -1690,6 +1691,7 @@ class Societe extends CommonObject $this->state_id = $obj->state_id; $this->state_code = $obj->state_code; + $this->region_id = $obj->region_id; $this->region_code = $obj->region_code; $this->state = ($obj->state != '-' ? $obj->state : '');